02.06.2013 Views

jQuery Cookbook - Cdn.oreilly.com - O'Reilly

jQuery Cookbook - Cdn.oreilly.com - O'Reilly

jQuery Cookbook - Cdn.oreilly.com - O'Reilly

SHOW MORE
SHOW LESS

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

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

Solution<br />

(function($) {<br />

$.fn.myPlugin = function(settings) {<br />

return this.each(function() {<br />

settings = $.extend({ onShow: null }, settings);<br />

$(this).show();<br />

if ( $.isFunction( settings.onShow ) ) {<br />

settings.onShow.call(this);<br />

}<br />

});<br />

};<br />

$(document).ready(function() {<br />

$('div').myPlugin({<br />

onShow: function() {<br />

alert('My callback!');<br />

}<br />

});<br />

});<br />

})(<strong>jQuery</strong>);<br />

Discussion<br />

While the JavaScript language provides the typeof operator, inconsistent results and<br />

edge cases across web browsers need to be taken into account. <strong>jQuery</strong> provides<br />

the .isFunction() method to ease the developer’s job. Worth pointing out is that since<br />

version 1.3, this method works for user-defined functions and returns inconsistent results<br />

with built-in language functions such as this:<br />

<strong>jQuery</strong>.isFunction( document.getElementById );<br />

which returns false in versions of Internet Explorer.<br />

4.8 Removing Whitespace from Strings or Form Values with<br />

<strong>jQuery</strong>.trim<br />

Problem<br />

You have an input form and need to remove the whitespace that a user may have entered<br />

at either the beginning or end of a string.<br />

Solution<br />

<br />

<br />

(function($) {<br />

$(document).ready(function() {<br />

$('input.cleanup').blur(function() {<br />

var value = $.trim( $(this).val() );<br />

$(this).val( value );<br />

4.8 Removing Whitespace from Strings or Form Values with <strong>jQuery</strong>.trim | 83

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

Saved successfully!

Ooh no, something went wrong!