HTML5 and CSS3, Second Edition

(singke) #1
html5_popups_with_custom_data/original_example_3.html
$("a.popup").click(function(event){
event.preventDefault();
window.open(this.getAttribute('href'));
});

We use a jQuery selector to grab all elements with the class of popup, and then
add an observer to each element’s click event.

The function we pass to the click() method will be executed when someone
clicks the link. The preventDefault method prevents the default click-event
behavior. In this case, it prevents the browser from following the link and
displaying a new page.

However, we’ve lost the information on how to size and position the window.
We want a page designer who isn’t very familiar with JavaScript to still be
able to set the dimensions of a window on a per-link basis.

Custom Data Attributes to the Rescue!


Situations like this are common when building any JavaScript-enabled
application. As we’ve seen, storing the window’s desired height and width
with the code is desirable, but the onclick() approach has lots of drawbacks.
Instead we can embed these attributes on the element. All we have to do is
construct the link like this:

html5_popups_with_custom_data/popup.html
<ahref="help/holiday_pay.html"
data-width="600"
data-height="400"
title="HolidayPay"
class="popup">Holidaypay</a>

Now we modify the click() event we wrote to grab the options from the link’s
custom data attributes and pass them to the window.open() method.

html5_popups_with_custom_data/popup.html
$("a.popup").click(function(event){
event.preventDefault();
varlink= this;
varhref= link.getAttribute("href");
varheight= link.getAttribute("data-height");
varwidth= link.getAttribute("data-width");

window.open(href,"popup",
"height="+ height+",width="+ width+"");
});

Chapter 2. New Structural Tags and Attributes • 32


Download from Wow! eBook <www.wowebook.com> report erratum • discuss

Free download pdf