Tuesday, September 2, 2014

JavaScript and jQuery anatomy: element, event listener, and callback function

JavaScript
var shoppingCartButtonElement = document.getElementById(‘UpdateShoppingCartButton’);
shoppingCartButtonElement.addEventListener(“click”, function() {
alert( "Handler for click called." );
});

Here are each of the JS portions broken down into their parts:
ELEMENT: the element (class or ID you are trying to get)
shoppingCartButtonElement 
EVENT LISTENER: in this case, waits for the user to interact and registers that the click happened.
.addEventListener(“click”,
CALLBACK FUNCTION (METHOD): once the event occurs, do stuff.
function() {
alert( "Handler for click called." );
});

Now, let's do the same for..
jQuery:
$( "#UpdateShoppingCartButton" ).click(function() {
  alert( "Handler for .click() called." );
});

Here are each of the jQuery portions broken down into their parts:
ELEMENT: the element (class or ID you are trying to get)
$( "#UpdateShoppingCartButton" )
EVENT LISTENER: in this case, waits for the user to interact and registers that the click happened.
.click
CALLBACK FUNCTION (METHOD): once the event occurs, do stuff.
(function() {
  alert( "Handler for .click() called." );
});