O'Reilly logo

Smashing Mobile Web Development by Greg Avola

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

JavaScript

Most mobile apps tend to be extremely interactive and, therefore, rely on a lot of JavaScript. JavaScript allows you to script everything from the touchscreen interface to server-side communication.

Basic events

Event handling is part of the core of most JavaScript interactivity, because it applies special scripts to handle a variety of user inputs, from clicks to form element interaction. Here are some of the events that are available to both mobile and non-mobile browsers.

Event handlers are built a bit differently in some browsers, so you attach them with jQuery in this section to avoid any cross-browser issues.

onClick

Undoubtedly the most used event handler, onClick handles mouse clicks from the user. Using the jQuery counterpart click(), you can attach a click event to an element:

$(‘.my-element’).click(function(e) {

// what to do on click

});

As you can see here, you pass a callback function to click(), which is called whenever the user clicks this element.

With jQuery, you can reference the clicked item in a number of ways, the easiest being $(this). For instance, you could hide the element once it’s clicked:

$(‘.my-element’).click(function(e) {

// hide the element

$(this).hide();

});

For mobile, it is often better to use touch events instead of click events, which you learn about later in this appendix.

Disabling default click behavior

Often, you want to disable the original click event. For instance, if you are loading a link via AJAX, you wouldn’t want ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required