Creating Pop-up Windows with Custom Data Attributes

0
148

If you’ve built any web application that uses JavaScript to grab information out of the document, you know that it can sometimes involve a bit of hackery and parsing to make things work. You’ll end up inserting extra information into event handlers or abusing the rel or class attributes to inject behavior. Those days are now over thanks to the introduction of custom data attributes.

Custom data attributes all start with the prefix data- and are ignored by the validator for HTML5 documents. You can attach a custom data attribute to any element you’d like, whether it be metadata about a photograph, latitude and longitude coordinates, or, as you’ll see in this tip, dimensions for a pop-up window. Best of all, you can use custom data attributes right now in nearly every web browser, since they can be easily grabbed with JavaScript.

Separating Behavior from Content, or Why onclick Is Bad
Over the years, pop-up windows have gotten a bad reputation, and often rightly so. They’re often used to get you to look at an ad, to convince unsuspecting web surfers to install spyware or viruses, or, worse, to give away personal information that is then resold. It’s no wonder most browsers have some type of pop-up blocker available.

Pop-ups aren’t all bad, though. Web application developers often rely on pop-up windows to display online help, additional options, or other important user interface features. To make pop-ups less annoying, we
need to implement them in an unobtrusive manner. When you look at AwesomeCo’s human resources page, you see several links that display policies in pop-up windows. Most of them look like this:

<a href=’#’
onclick=”window.open(‘holiday_pay.html’,WinName, ‘width=300,height=300);”>
Holiday pay
</a>

This is a pretty common way to build links that spawn pop-ups. In fact, this is the way JavaScript newbies often learn how to make pop-up windows. There are a couple of problems that we should address with this approach before moving on, though.

Improve Accessibility

The link destination isn’t set! If JavaScript is disabled, the link won’t take the user to the page. That’s a huge problem we need to address immediately. Do not ever omit the href attribute or give it a value like this under any circumstances. Give it the address of the resource that would normally pop up.

<a href=’holiday_pay.html’
oncl i ck= “window. open(this.href, WinName, ‘width=300, height=300) ; “>
Holiday pay
</a>

The JavaScript code then reads the attached element’s href attribute for the link’s location.

The first step toward building accessible pages is to ensure that all the functionality works without JavaScript.

Abolish the onclick

Keep the behavior separate from the content, just like you keep the presentation information separate by using linked style sheets. Using onclick is easy at first, but imagine a page with fifty links, and you’ll see how the onclick method gets out of hand. You’ll be repeating that
JavaScript over and over again. And if you generate this code from some server-side code, you’re just increasing the number of JavaScript events and making the resulting HTML much bigger than it needs to be.

Instead, give each of the anchors on the page a class that identifies them.

<a href=”holiday_pay”>Holiday Pay</a>

var links = $(“a.popup”) ]
1 i nks.cli ck(function(event){
event.preventDefault() ;
window.open($(this).attrC’href’));
} ) ;

We use a jQuery selector to grab the element with the class of popup, and then we add an observer to each element’s click event. The code 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.

One thing we’ve lost, though, is the information on how to size and position the window, which is something we had in the original example. We want a page designer who isn’t that 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. What we can do instead is embed these attributes as  attributes on the element. All we have to do is construct the link like this:

<a href=”he!p/holi day_pay.html”
data-width=”600″
data-height=”400″
title=”Holiday Pay”
cl ass=”popup”>Holiday pay</a>

Now we just modify the click event we wrote to grab the options from the custom data attributes of the link and pass them to the window.open method.

$(function(){
$( “.popup”) . cl i ckCfuncti on (event) {
event.preventDefaul t();
var href = $(this) .attr(“href”) ;
var width = $(this) ,attr(“data-width”) ;
var height = $(this).attr(“data-height”) ;
var popup = window.open (href,”popup”,
“height=” + height +”,width=” + width + “”);
} ) ;

That’s all there is to it! The link now opens in a new window.

A Word of Caution

In this example, we used custom data attributes to provide additional information to a client-side script. It’s a clever approach to a specific problem and Illustrates one way to use
these attributes. It does tend to mix presentation Information with our markup, but it’s a simple way to show you how easy It is to use JavaScript to read values you embed in your page.

Falling Back

These attributes work in older browsers right now as long as they support JavaScript. The custom data attributes won’t trip up the browser, and your document will be valid since you’re using the HTML5 doctype, since the attributes that start with data- will all be ignored.

The Future

We can do some interesting things with these new tags and attributes once they’re widely supported. We can identify and disable navigation and article footers very easily using print style sheets,

nav, arti cle>footer{di splay:none}

We can use scripting languages to quickly identify all of the articles on a page or on a site. But most important, we mark up content with appropriate tags that describe it so we can write better style sheets and better JavaScript.

Custom data attributes give developers the flexibility to embed all sorts of information in their markup.

You can use them with JavaScript to determine whether a form tag should submit via Ajax, by simply locating any form tag with dataremote= true, which is something that the Ruby on Rails framework is doing.

You can also use them to display dates and times in a user’s time zone while still caching the page. Simply put the date on the HTML page as UTC, and convert it to the user’s local time on the client side. These attributes allow you to embed real, usable data in your pages, and you can expect to see more and more frameworks and libraries taking advantage of them. I’m sure you’ll find lots of great uses for them in your own work.

And we can help wipe out Divitis once and for all!