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

Events and More Events

In this chapter we have covered the events that jQuery deems important enough to have their own functions. This is a relatively small set of the events that a typical browser support. For example, the MDN Event Reference has a very long list of standard events and an equally long list of non-standard events. 

You can use any of these events via jQuery using the on, one and off functions to attach handlers. You might think that you are safe to use the standard events but all you can assume is a reasonable expectation that modern browsers will have implemented them. What you cannot assume is that they have implemented them in the same way. Small differences in implementation often cause big problems and unfortunately jQuery offers no help in smoothing over browser differences for the vast majority of events. 

For example the wheel event is the standard for detecting when a mouse wheel has been rotated. You can use it something like:

$(document).on("wheel",function(event){
   console.log(event.originalEvent.deltaY);
});

Notice that to access the deltaY property we need to use the originalEvent object because jQuery doesn't unpack this into its event object. The deltaY is negative and positive according to which way the wheel has been rotated. 

This is easy but until recently the wheel event didn't work with Safari or with Edge. Finding out which browsers support which events isn't easy and finding out exactly how they support them is even harder. In practice all you can reasonably do is to try your program out on the browsers that you need to support. 

Immediate Events

So far the key idea in understanding JavaScript and even handling has been the idea that JavaScript has only one thread of execution (unless you create others using web workers say). What this means for events is that only one event handler can be active at any given moment. If another event occurs while an event handler or any JavaScript is running then it is simply added to the event queue and it gets its chance to run when the currently executing code stops running and frees the thread. This is sometimes explained as "run to completion" in the sense that any JavaScript that is running runs until it is completed and isn't interrupted by the system to do something else.

This really is the big idea but like all principles there are minor exceptions and these aren't well documented or particularly well thought out. 

Consider for a moment the following program:

$("#button1").click(function(){
   $("#button2").click();
   console.log("button click 1");
  });
$("#button2").click(function(){
   console.log("button click 2");
  });

Two buttons each with their own click event handlers that display messages on the console. The complication  is that the first button click handler fires the click event on the second button. 

What do you see on the event log?

By the "run to completion" rule the first button's event handler should fire the click event on button2, which should be added to the even queue to all the currently executing event handler to complete. So you should see button click 1 followed by button click 2. 

You don't - you actually see button click 2 followed by button click 1.

When you fire an event in code it behaves more like a function call. Indeed this is exactly what is happening when you fire an event in software all that happens is that the functions that are stored in the list of event handlers are called one after another. There is still only a single thread of execution but it transfers to the other event handler before completing the current event handler.

This is something we will have to return to when we look at custom events in the next chapter.

There are also example where an event handler is called immediately when a real not a just a software event occurs but these are rare, very browser and even OS dependent. The one that is usually quoted is the firing of a resize event while an Alert is shown on the screen.

The important point is that JavaScript is single-threaded and only one thing happens at a time, but the rules for how control is passed from one event handler to another can be more complicated than you might expect. 

 

Summary 

  • There are five categories of event that jQuery provides special shortcut functions for: mouse, keyboard, form, browser and document.

  • Mouse events are most familiar. The click event is safe to use with touch screen devices as it is generally fired if the user taps. The double click event is best avoided. The right click is handled using the context menu event and this generally works on touch devices as a long tap.

  • The lower level mouse events - mousedown, mouseup and mousemove are best avoided for touch devices.  

  • Click works only with the prime button, usually the left button. You can program your own click event for the other buttons using mousedown and mouseup.\

  • Mousemove can be used to provide the user with free-form interaction, but any handler has to be short to avoid blocking the UI.

  • A drag and drop operation needs the coordinated use of mousedown, mousemove and mouse up. It is easy to implement from first principles, but you could also use jQuery UI or the HTML5 drag and drop.

  • Keyboard events respond either to the particular key that has been pressed or the character that the key generates. 

  • The keypress event is fired when a complete keypress has occurred and it returns that actual character the key generates taking account of any other keys pressed at the time.  The keydown and keyup events fire on a key being pressed down or released respectively and they return a keycode which identifies the key, not the character it generates. 

  • Form events are concerned with detecting when form elements gain or lose focus and with changes the user makes to the data they hold. 

  • Browser events are concerned with letting you know when the UI needs to take account of changes in the display. The resize event if fired when the browser window is resized so you can re-arrange elements.

  • The scroll event is fired when the document or a scrollable element has been scrolled. 

  • The only document event is ready which is fired when the DOM is built and ready to work with. How to load scripts and when to run them is a complex issue but the simplest thing to do is load jQuery in the head and either use the ready event to run your program or place your program at the end of the page. 

  • There are lots of other events that you can use with the help of jQuery but as soon as you stray from the most used there is the problem of browser support and browser variations. 

  • If you fire an event in software, it isn't run asynchronously. It is an example of an immediate event and it is more like a function call to the list of event handlers. 

 

 

Just jQuery
Events, Async & AJAX

Is now available as a print book: Amazon 

jquery2cover

 

Contents

  1. Events, Async & Ajax (Book Only)
  2. Reinventing Events
  3. Working With Events
  4. Asynchronous Code
  5. Consuming Promises
  6. Using Promises 
  7. WebWorkers
  8. Ajax the Basics - get
  9. Ajax the Basics -  post
  10. Ajax - Advanced Ajax To The Server
  11. Ajax - Advanced Ajax To The Client
  12. Ajax - Advanced Ajax Transports And JSONP
  13. Ajax - Advanced Ajax The jsXHR Object
  14. Ajax - Advanced Ajax Character Coding And Encoding 

Also Available:

buy from Amazon

smallcoverjQuery

 

Advanced Attributes

 

Banner


JavaScript Canvas - Fetch API

Working with lower-level data is very much part of graphics. This extract from Ian Elliot's book on JavaScript Graphics looks at how to use typed arrays to access graphic data.



JavaScript Jems - The Inheritance Tax

JavaScript should not be judged as if it was a poor version of the other popular languages - it isn't a Java or a C++ clone. It does things its own way.  In particular, it doesn't do inheritance  [ ... ]


Other Articles

To be informed about new articles on I Programmer, sign up for our weekly newsletter, subscribe to the RSS feed and follow us on Twitter, Facebook or Linkedin.

espbook

 

Comments




or email your comment to: comments@i-programmer.info

 



Last Updated ( Thursday, 05 May 2022 )