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 ...
Get Smashing Mobile Web Development now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.