12.07.2015 Views

Pro JavaScript for Web Apps pdf - EBook Free Download

Pro JavaScript for Web Apps pdf - EBook Free Download

Pro JavaScript for Web Apps pdf - EBook Free Download

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

CHAPTER 2 GETTING STARTEDDealing with Default ActionsTo make life easier <strong>for</strong> the programmer, the browser per<strong>for</strong>ms some actions automatically when certainevents are triggered <strong>for</strong> specific element types. These are known as default actions, and they mean youdon’t have to create event handlers <strong>for</strong> every single event and element in an HTML document. Forexample, the browser will navigate to the URL specified by the href attribute of an a element in responseto the click event. This is the basis <strong>for</strong> navigation in a web page.I cheated a little by setting the href attribute to #. This is a common technique when definingelements whose actions are going to be managed by <strong>JavaScript</strong> because the browser won’t navigate awayfrom the current document when the default action is per<strong>for</strong>med. In other words, I don’t have to worryabout the default action because it doesn’t really do anything that the user will notice.Default actions can be more important when you need to change the behavior of the element andyou can’t do little tricks like using # as a URL. Listing 2-10 provides a demonstration, where I havechanged the href attribute <strong>for</strong> the a element to a real web page. I have used the attr method to set thehref attribute of the a element to http://apress.com. With this modification, clicking the elementdoesn’t submit the <strong>for</strong>m anymore; it navigates to the Apress website.Listing 2-10. Managing Default Actions...$(document).ready(function() {$('#buttonDiv input:submit').hide();$('Submit Order').appendTo("#buttonDiv").attr("href", "http://apress.com").addClass("button").click(function() {$('<strong>for</strong>m').submit();}).hover(function(e){var elem = $('#buttonDiv a')if (e.type == "mouseenter") {elem.addClass("buttonHover");} else {elem.removeClass("buttonHover");}})})...To fix this, a call to the preventDefault method on the Event object passed to the event handlerfunction is required. This disables the default action <strong>for</strong> the event, meaning that only the code in theevent handler function will be used. You can see the use of this method in Listing 2-11.28www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!