14.08.2016 Views

Beginning JavaScript with DOM Scripting and Ajax, 2nd Edition

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 6 ■ Common Uses of <strong>JavaScript</strong>: Images <strong>and</strong> Windows<br />

init : function(){},<br />

roll : function( e ){}<br />

}<br />

<strong>DOM</strong>help.addEvent( window, 'load', ro.init, false );<br />

Let’s start fleshing out the skeleton. First up are the properties <strong>and</strong> the init method. In it, you predefine a<br />

variable called oversrc <strong>and</strong> store all the images of the document in an array called imgs. You loop through the<br />

images <strong>and</strong> skip those that don’t have the right CSS class attached to them:<br />

automatedRollover.js (excerpt)<br />

ro = {<br />

rollClass : 'roll',<br />

overSrcAddOn : '_on',<br />

preLoads : [],<br />

init : function() {<br />

var oversrc;<br />

var imgs = document.images;<br />

for( var i = 0; i < imgs.length; i++ ) {<br />

if( !<strong>DOM</strong>help.cssjs('check', imgs[i], ro.rollClass ) ) {<br />

continue;<br />

}<br />

If the image has the right CSS class attached to it, you read its source attribute, replace the full stop in it by the<br />

suffix defined in the overSrcAddOn property followed by a full stop, <strong>and</strong> store the result in the oversrc variable:<br />

automatedRollover.js (continued)<br />

oversrc = imgs[i].src.toString().replace('. ',ro.overSrcAddOn + '. ');<br />

■ ■Note For example, the first image in the document has the src but_1.gif. The value of oversrc <strong>with</strong> the suffix<br />

property defined here would be but_1_on.gif.<br />

You then create a new image object <strong>and</strong> store it as a new item of the preLoads array. Set the src attribute of the<br />

new image to oversrc. Use addEvent() from the <strong>DOM</strong>help library to add an event h<strong>and</strong>ler for both mouseover <strong>and</strong><br />

mouseout that points to the roll method.<br />

automatedRollover.js (continued)<br />

ro.preLoads[i] = new Image();<br />

ro.preLoads[i].src = oversrc;<br />

<strong>DOM</strong>help.addEvent( imgs[i], 'mouseover', ro.roll, false );<br />

<strong>DOM</strong>help.addEvent( imgs[i], 'mouseout', ro.roll, false );<br />

}<br />

},<br />

154<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!