jQuery 3 - Using Events
jQuery 3 - Using Events
Written by Ian Elliot   
Monday, 01 May 2017
Article Index
jQuery 3 - Using Events
Drag and Drop and Keyboard Events
Form, Browser and Document Events
Immediate Events

Form Events

Forms are a very standard way of getting input from the user and as such are the next obvious thing to consider after mouse and keyboard events. 

There are a set of events associated with the movement of the focus from one element to another. The element that has the focus is the one that user input is directed at and this is what makes it important. 

focus and blur

The focus event fires when an element gets the focus and the blur event fires when it loses it. In modern browsers any element can fire the focus and blur event even if it isn't within a form element. These events don't bubble up to parents.

focusin and focusout

These are bubbling versions of focus and blur. That is an element will receive this event if any of its children gets or loses the focus. 

There are two events associated with detecting when the user has changed data in a form:

change

The change event is fired when the value of an input, textarea or select element changes. For checkboxes and radio buttons the event is fired at once so that you can process the users new selection. For input and textarea the event is only fired after the element loses focus. The reason for this is that the user may well be editing and changing what they are entering and rather than fire a change even for each keystroke the system waits until the user moves to another field in the form before informing you of the change. 

select

Now we come to a difficult event because what you do after it generally depends on the browser. The select event is triggered when the user selects some text by dragging in either an input text field or a textarea box. This much is easy but usually after this you need to access the selection and this used to be very browser specific. Unfortunately jQuery doesn't normalize this but there are jQuery plugins that do. Modern browsers that support HTML5 however do provide a standard way to work with selected text.  The input text and textarea Element support the selectionStart and selectionEnd attributes and these are easy to access using the jQuery prop function. The attributes give the start and end position of the selection in the String returned by the val function. 

For example, if we have the following textarea:

<textarea id="edit">text</textarea>

Then we can work with the selection using an event handler:

$("#edit").select(function(event){
  var edit= $(event.target);
  var start= edit.prop("selectionStart");
  var end=edit.prop("selectionEnd");
  var text=edit.val();
  text=text.slice(start,end);
  edit.val(text);
 });

The event.target is wrapped as a jQuery object and then the prop func is used to retrieve the start and end of the selection. The contents of the textarea are then retrieved using val. The start and end are then used to reduce the string to just the selection and this is made the new contents of the textarea. The result is that only the characters that are selected remain in the textarea. 

This is typical of how text manipulation works. The markers, start and end, are retrieved and used to process the contents of the text field as a string which is restored to make the changes visible to the user. 

submit

The final form event is submit. This is fired when the user submits the form. Generally you use an event handler to make any final validation needed but always remember that validation is best performed early if at all possible. It is also used to fire the submit action on the form so that you can use Elements other than a submit button.  

For more information and examples see the Forms chapter in Just jQuery The Core UI Amazon.com.

Browser Events

There are only two browser generated events that jQuery specifically handles related to the viewing window size and scrolling Elements.

resize

The resize even is fired whenever the user resizes the browser window. Obviously the purpose of this event is to give you the opportunity to modify the layout or sometimes to restrict the size change. The only real problem with handling resize is that different browsers fire the event in different ways. Some fire the event every time the user adjusts the size of the window and other only fire it once at the end of the resize. Sometimes this doesn't cause any difficulty because the resize handler doesn't do very much work. However in many cases the resize event handler has a lot of work to do and it slows the UI down too much. The good news is that all modern browsers Firefox, Chrome, IE 11 and Edge fire the event only when the user drops the window border. 

scroll

This event is fired on any element that has an overflow property set to scroll or auto when scroll is being used. It fires no matter how the scroll has occurred - via mouse or keyboard. In most cases you can allow the browser to take care of the scroll implementation but sometimes you need to intervene. 

For example if you want to generate content as the user scrolls an element:

<div id="target"
 style="overflow: scroll; width: 200px; height: 100px;">
#</br>
#</br>
#</br>
#</br>
#</br>
</div>

This starts off with just a column of hashes. When the user scrolls to see more content the scroll event is triggered and the event handler called:

var count=0;
$( "#target" ).scroll(function() {
    count++;
    $( "#target" ).append(count.toString()+ "</br>" );
  });

In this case we simply append the value of a counter.

A common occurrence is the use of the jQuery scrollLeft and scrolltop function within scroll event handlers to discover how far the Element has been scrolled and to test for a horizontal or vertical scroll. You can also use them to set the scroll position. The positions are returned in pixels that are currently scrolled off the left or top. 

Document Events

The only important document event provided by jQuery is ready. THis is fired when the DOM is fully loaded. However this is not as simple as it might sound. You want to run your JavaScript when the resources that it works with are ready but there is no simple definition of when a page is "ready". The fact that your JavaScript is about to modify the page indicates that there is a sense in which the page still isn't "ready". 

There is also the matter of where you start your JavaScript loading. Unless you use the async or defer attributes a script is loaded and the processing of the page stops until it has been executed and releases the UI thread. That is script loading is by default synchronous with the processing of the page. 

If you place your script tag in the head then the browser will stop rendering the page and download your code. In this case you need to use the ready event to make sure that the DOM is ready for you to work with it. 

However if you place the script tag at the end of the page the browser will download your code and run it after showing the user the page. This can make it look as if your page loads faster. 

There is also the complication of the async and defer attributes. If you use async then the script is loaded in the background and executes as soon as it is ready. If you use defer then the script is loaded asynchronously but not executed until the page is parsed. 

It is generally held that you get the best perceived load time by placing any JavaScript loads at the very end of the page. However if you do this you cannot have any code higher up the page that makes use of the code loaded at the end. You also don't need to use the jQuery ready event as the page will be loaded and ready before your code is loaded and ready. One disadvantage is that the user could start to interact with the page before your code is usable. 

Another problem is that you have to make sure that jQuery is loaded before your code tries to make use of it. You can't even make use of the ready event if jQuery isn't loaded. This may seem obvious but it is a common error. 

If you want to be safe load jQuery in the header without specifying async or defer. Then place your code in a ready event handler any where on the page below the loading of jQuery. You can include an async or defer attribute on your own code if you want to avoid blocking the UI. 

You can use the ready event in a number of ways but the preferred method is:

$(handler);

A typical way to work with jQuery is:

<head>
 <title>TODO supply a title</title>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width,
                                 initial-scale=1.0">
 <script
   src="/https://code.jquery.com/jquery-3.1.1.js"
   integrity=
  "sha256-16cdPddA6VdVInumRGo6IbivbERE8p7CQR3HzTBuELA="
   crossorigin="anonymous">
 </script>
 <script>
  $(function () {
   your code
  });
 </script>
</head>

Notice that placing your code inside a ready event handler has the beneficial side-effect of making all of the variables you create local variables which are accessible only from your code. This is another example of closure working in our favour. 

It is worth mentioning that the ready event makes use of the jQuery.ready function which returns a Promise object. Promises and deferreds are discussed in Chapter 4, but you could write in place of $(handler):

$.when($.ready).then(handler);

There is no particular advantage to this. There might be an advantage if you need to compose promises to make more complicated behavior. You can also use it for error handling. More on these topics in Chapters 4 and 5.



Last Updated ( Monday, 01 May 2017 )
 
 

   
Banner
Copyright © 2017 i-programmer.info. All Rights Reserved.
Joomla! is Free Software released under the GNU/GPL License.