Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

Lesson 2: Working with jQuery CHAPTER 6 295


this object, the jQuery text method retrieves the inner text of the element and assigns it to an
innerText variable.

Adding event listeners


In HTML5, you can use the addEventListener function to subscribe to an event. If you want a
browser-independent way to add an event listener, you can use the jQuery .on method. There
is also a corresponding .off method to remove an event listener. The .on method can be used
as follows.
$('#btnSubmit').on('click', myFunction);

In this example, a button whose id is btnSubmit is located, using jQuery and the .on
method to add a call to the user-defined myFunction function to the click event of the but-
ton. To remove the event listener, use the same code but replace the .on with .off as follows.
$('#btnSubmit').off('click', myFunction);

Triggering event handlers


When you need to trigger the event handlers by using code, you’ll find that jQuery can
help. Probably the most common reason to trigger event handlers by using code is to test
your code. Using jQuery’s trigger or the triggerHandler method causes the handler code to
execute.
The trigger method causes the default behavior of the control to execute, whereas the
triggerHandler method does not. For example, executing the trigger method on a submit
button causes the submit action to take place in addition to executing your event handler
code. Another difference is that the trigger method executes for all elements matched in the
jQuery selector, whereas the triggerHandler method executes for only the first element. The
following is an example of triggering the event handler code for the click event on a submit
button.
$('#btnSubmit').triggerHandler('click');

Initializing code when the browser is ready


You will often need to execute initialization code after the HTML document is loaded and
ready, and jQuery executes with a browser-independent way to execute code when the docu-
ment is loaded as follows.
<script>
$(document).ready(function () {
initialize();
});
</script>
Free download pdf