13.02.2013 Views

WEB STANDARDS CREATIVITY

WEB STANDARDS CREATIVITY

WEB STANDARDS CREATIVITY

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

if (target.className.match(pattern))<br />

{<br />

return true;<br />

}<br />

return false;<br />

};<br />

function addClass(target, classValue)<br />

{<br />

if (!hasClass(target, classValue))<br />

{<br />

if (target.className == "")<br />

{<br />

target.className = classValue;<br />

}<br />

else<br />

{<br />

target.className += " " + classValue;<br />

}<br />

}<br />

return true;<br />

};<br />

function removeClass(target, classValue)<br />

{<br />

var removedClass = target.className;<br />

var pattern = new RegExp("(^| )" + classValue + "( |$)");<br />

removedClass = removedClass.replace(pattern, "$1");<br />

removedClass = removedClass.replace(/ $/, "");<br />

target.className = removedClass;<br />

return true;<br />

};<br />

It’s not correct to do a direct string comparison on an element’s class, because it can actually contain multiple classes, each<br />

separated by a space. This is the same reason you shouldn’t do a direct assignment to the class, because you might overwrite<br />

existing classes. hasClass() checks whether the value you’re searching for is one of the multiple classes. addClass() makes<br />

sure you don’t overwrite any existing classes or add the same class more than once. removeClass() removes only the specified<br />

class while leaving all others intact.<br />

Now that the click event is in place, every time that a user clicks the expand/collapse link for a content module, it will add<br />

or remove the collapsed class as necessary. And that finishes our expand/collapse behavior!<br />

chapter 9 Creating Dynamic Interfaces Using JavaScript<br />

229

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

Saved successfully!

Ooh no, something went wrong!