Pro HTML5 and CSS3 Design Patterns

(avery) #1

CHAPTER 17 ■ LAYOUTS


Event Styling


HTML


<head>
<!-- only script elements are shown -->

<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.3/jquery.min.js"></script>
</head>

page.js


$(document).ready(function(e){
$('.rollup-trigger').click(function(e){
$(this).closest('.rollup').children().not('.rollup-trigger').toggleClass('hidden');
$(this).parent().removeClass('hidden');
});
});

Event Styling


Problem You want to attach events to HTML elements without putting JavaScript in the body of the document.
You want to attach events to elements using CSS selectors so there is a direct connection between how
elements are styled and how they respond to events. You want events to modify element classes so you
can use stylesheets to control how dynamic HTML styles a document. In other words, you want to
completely separate content, style, and JavaScript. You don’t want to put JavaScript or styles in the
content, and you don’t want to put styles or content in the JavaScript code.

Solution You can use JavaScript libraries to attach events to elements at runtime. All you need are a few
<script> tags in the document head to load the JavaScript libraries. This technique completely
removes the need to put code in event attributes, such as <div onclick="someFunction();">.
To attach events to elements at runtime, you can use one of many different JavaScript libraries.
jQuery is used for this example; you can find documentation at http://docs.jquery.com/.
You can use this library by attaching its JavaScript files to your document. A browser downloads and
executes each JavaScript file in the order it occurs in the document. The last JavaScript file is typically
unique to the current page. It initializes the libraries, and it assigns event handlers to elements.
In the example, I name this file page.js. The code doesn’t slow down the rendering of the document,
and it ensures that events are added to elements after they exist.
Free download pdf