Академический Документы
Профессиональный Документы
Культура Документы
These tips and tricks all have one thing in common- they are all smashingly useful. With this stuff in your back pocket, youll be ready to go change the world, and even better, write jQuery like you know what youre doing. Its gonna be fun. Well start with some basic tricks, and move to some more advanced stuff like actually extending jQuerys methods and filters. Of course, you should be familiar with the basics of jQuery first. If you havent used jQuery before, I highly recommend browsing the documentation and watching jQuery for Absolute Beginners Video Series. Otherwise, youre ready to dig in!
This is a very quick, easy way to cause delayed actions in jQuery without using setTimeout. The way we make it work is to add an animate function into your chain and animate the element to 100% opacity (which its already at), so it looks like nothing is happening. For instance, lets say that you wanted to open a dialog and then fade it away after 5 seconds. Using animate, you can do it like this:
$(function(){ 1 $("body").append("<div class='dialog'></div>").<em>animate({ 2 opacity : 1.0 }, 5000)</em>.fadeOut(); 3 });
Dont you just love jQuery chaining? Youre welcome to read more about this technique from Karl Swedberg. UPDATE: jQuery 1.4 has eliminated the need for this hack with a method called delay(). It is just what is sounds like a function specifically made to delay an animation effect. Way to go, jQuery!
$(function(){ 1 var reversedSet = $("li").get().reverse(); 2 //Use get() to return an array of elements, and then reverse it 3 4 $(reversedSet).each(function(){ 5 //Now we can plug our reversed set right into the each 6 function. Could it be easier? 7 }); 8 });
This works because 0 evaluates false, so the expression only evaluates true if there is at least one element in the jQuery object. You can also use size() to do the same thing.
$(function(){ 1 jQuery.fn.equalHeight = function () { 2 var tallest = 0; 3 this.each(function() { 4 tallest = ($(this).height() > tallest)? 5 $(this).height() : tallest; 6 }); 7 return this.height(tallest); 8 } 9 10 //Now you can call equalHeight 11 $(".content-column").equalHeight(); 12 });
An interesting and similar concept is the awesome jQuery masonry plugin, if youre interested in checking it out.
1 2 3 4 5 6 7 8 9 10 11 12 13 <strong>//ADD FIRST-CHILD SUPPORT:</strong> jQuery.fn.firstChild = function(){ 14 return this.each(function(){ 15 var currentClass = $(this).attr('class').split(' 16 17 ')[0]; //Get first class name $(this).children(":first").addClass(currentClass 18 19 + '-first-child'); 20 }); 21 } $(".searchform").firstChild(); });
The great thing about setting it up that way firstChild(), hoverOn() and hoverOff() are very reusable. Now, in the CSS we can simply add the nav-item-hover or searchform-firstchild classes as additional selectors:
1 2 3 4 5 6 7 8 .nav-item:hover, <strong>.nav-item-hover</strong>{ background:#FFFFFF; border: solid 3px #888; } .searchform:first-child, <strong>.searchform-first-child</strong>{ background:#FFFFFF; border: solid 3px #888; }
Its not pretty, but it is valid and it works. Ive got to say, though, that I sure am looking forward to the day we wont have to bother with this stuff!
A popular effect is to fill a sites search box with a value (like search) and then use jQuery to clear the default value when the field receives focus, reverting if the field is empty when blurred. That is easily accomplished with a couple lines of jQuery:
1 $(function(){ 2 //set default value: 3 $("#searchbox") 4 .val('search?'); .focus(function(){this.val('')}) 5 .blur(function(){ 6 (this.val() === '')? this.val('search?') : null; 7 8 }); 9 });
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
Brian also added some nice-looking CSS, which you could add as a css file or define in an object literal and apply it using jQuery.css(). Feel free to go check out his in-depth explanation if you want to learn more.
You can check out the jQuery docs on this one to see all the possibilites, or view this keycode reference if youd like to look up a certain keys character code.
7 // Increase Font Size $(".increaseFont").click(function(){ 8 var currentFontSize = $('html').css('font-size'); 9 var currentFontSizeNum = parseFloat(currentFontSize, 10); 10 var newFontSize = currentFontSizeNum*1.2; 11 12 $('html').css('font-size', newFontSize); return false; 13 14 }); 15 // Decrease Font Size $(".decreaseFont").click(function(){ 16 var currentFontSize = $('html').css('font-size'); 17 var currentFontSizeNum = parseFloat(currentFontSize, 10); 18 var newFontSize = currentFontSizeNum*0.8; 19 20 $('html').css('font-size', newFontSize); return false; 21 22 }); 23 });
As I said, this is nice trick to know and adds some of that dynamic friendliness that people enjoy so much.
This works by grabbing all links with an external rel and adding a blank target. Same result, its just not hardcoded into the site.
Of course, this is very basic, but its an essential facet to any AJAX navigation. You can also check out SpeckyBoys post on Easy-to-Use Free Ajax Navigation Solutions.
1 2 3 4 5 6 7 8 9 10
beautifiers and photo sliders, making it easy to keep a consistent look throughout a website or app. You can check out the Theming Reference here.
For Javascript users the body now has a JS class, so in our CSS we can add styles like this:
ul.navigation{ display:block; } .JS ul.navigation{ display:none; }
This gives us a great way to change styles based on whether or not Javascript is supported/enabled, and we can still keep the styling in the CSS file. Another interesting related use of this technique is to add browser classes to the body, enabling easy browserspecific styling. You can read more about that here.
Reference ids rather than classes (id selection is native and therefore quicker) Use for instead of each() Limit DOM manipulation by adding elements in one big chunk rather than one at a time Take advantage of event delegation Link to Googles jQuery copy rather than hosting your own its faster and always up to date
Basically, it all boils down to not making jQuery do any more work than it has to (and using native abilites whenever possible). Giulio Bai wrote an excellent post on jQuery perfomance, if youd like to dig in deeper.
Its definitely better practice to use feature-detection rather than browser sniffing, and this is a very efficient way to do it. Read more about jQuery.supports properties here.
An alternate technique is to wrap jQuery calls in an anonymous function and pass jQuery in as a parameter. Then you can use whatever alias you want, including the $. This is especially useful for plugin authoring:
1 (function($){ $(document).ready(function(){ 2 3 //You can use normal jQuery syntax here 4 }); 5 })(jQuery);
Im sure you can imagine the huge extent of possibilities this presents. Again, its worth reading the documentation if you havent used data() before.
11 12 13
By extending and improving jQuerys default functionality, you can open up a whole new world of cool possibilities.
This is another one that has been talked about a lot in the development community, so you may have this already figured out. If not, get ready because this will open some whole new windows for jQuery efficiency. The short story is, jQuery allows us to extend its expression object, which means we can add whatever custom selectors we want. For example, say we wanted to add a selector version of the isChildOf() method we wrote earlier:
1 $(function(){ 2 jQuery.extend(jQuery.expr[':'], { 'child-of' : function(a,b,c) { 3 return (jQuery(a).parents(c[3]).length > 0); 4 5 } 6 }); 7 8 //'child-of' is now a valid selector: 9 $("li:child-of(ul.test)").css("background","#000"); 10 });
Debuggable has a great post on this one as well, if youd like to read more about how the parameters work, etc.
<h3>Popular</h3> 2 <ul> 3 <li>Item #1</li> 4 <li>Item #2</li> 5 <li>Item #3</li> 6 </ul> 7 8 </div> 9 <div class="widget"> <h3>Recent</h3> 10 <ul> 11 <li>Item #1</li> 12 <li>Item #2</li> 13 <li>Item #3</li> 14 </ul> 15 16 </div>
With a bit of styling, this would look just fine, so we know our jQuery is going to degrade gracefully. Now we can write the code:
$(document).ready(function() { $("div.widget").hide().filter(":first").before("<ul class='tabs'></ul><div class='tabcontent'></div>").add("div.widget").each(function(){ $(this).find("ul").appendTo(".tab-content"); $("ul.tabs").append("<li>" +$(this).find(":header:first").text()+ "</li>"); }); $("ul.tabs li").click(function(){ $(this).addClass("active"); $(".tab-content ul").slideUp().eq($("ul.tabs li").index(this)).slideDown(); }); $("ul.tabs li:first").click(); });
1 2 3 4 5 6 7 8 9 10 11
Of course, thats just one way to do it. If youd like to see some other approaches, see Extra Tuts jQuery Tabs Tutorials collection.