jQuery Events Test

Goal: Trigger an event from a a function and execute a handler when that event is called.

by Brian Layman

HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
 <h4>You should see created divs below this if you inspect this element.</h4>
 <h4 id="endMarker">You should see created divs above this if you inspect this element.</h4>
<input id="index" value="0">
<button onclick="addElement( jQuery( '#index' ).val() );$( '#index' ).val( function( i, oldval ) { return parseInt( oldval, 10 ) + 1;} )">Add a Script Div</button>

JavaScript

function addElement (index) { 
	divID = "div-gpt-ad-1231231231-" + index;
  var newDiv = document.createElement( "div" ); 
  newDiv.setAttribute( "id", encodeURIComponent( divID ) );
  var newHR = document.createElement( "hr" ); 
  newDiv.appendChild( newHR ); //add the text node to the newly created div. 
  $.event.trigger({
    type: "newMessage",
    message: "Adding New Line",
    time: new Date()
  });
  // add the newly created element and its content into the DOM 
  var currentDiv = document.getElementById( "endMarker" ); 
  document.body.insertBefore( newDiv, currentDiv ); 
}

// newMessage event subscribers
$(document).on("newMessage", newMessageHandler);

// newMessage event handler
function newMessageHandler(e) {
	alert(e.message);
}