14.08.2016 Views

Beginning JavaScript with DOM Scripting and Ajax, 2nd Edition

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 11 ■ Using Third-Party <strong>JavaScript</strong><br />

jqueryTest.js (continued)<br />

function() {<br />

$(this.parentNode.nextSibling).slideUp('slow');<br />

$(this).html('Show Code');<br />

}<br />

)<br />

}<br />

)<br />

The other case of toggle() in this example uses slideUp() to slowly hide the code example <strong>and</strong> changes the text<br />

of the link back to “Show Code”.<br />

jQuery also allows for simple <strong>Ajax</strong> requests. jQuery uses the load(), $.get(), <strong>and</strong> $.post() methods as<br />

explained at http://api.jquery.com/category/ajax/. For example, if you want to create the PRE elements<br />

<strong>and</strong> load the real code examples into them when the user clicks a link, this is pretty easy to do. Check the demo<br />

exampleJQuery<strong>Ajax</strong>.html to see the following script in action:<br />

jqueryTest<strong>Ajax</strong>.js<br />

$(document).ready (<br />

function() {<br />

$('a.codeExample').each (<br />

function( i ) {<br />

$(this).after('');<br />

}<br />

)<br />

$('pre.codeExample').hide();<br />

$('a.codeExample').toggle (<br />

function() {<br />

if(!this.old){<br />

this.old = $(this).html();<br />

}<br />

$(this).html('Hide Code');<br />

parseCode(this);<br />

},<br />

function() {<br />

$(this).html(this.old);<br />

$(this.nextSibling).hide();<br />

}<br />

)<br />

function parseCode(o){<br />

if(!o.nextSibling.hascode){<br />

$.get (o.href,<br />

function(code){<br />

code=code.replace(/&/mg,'&#38;');<br />

code=code.replace(//mg,'&#62;');<br />

code=code.replace(/\"/mg,'&#34;');<br />

code=code.replace(/\r?\n/g,'');<br />

code=code.replace(//g,'');<br />

326<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!