Posts tagged with “DOM”

Useful jQuery snippets for everyone

Tuesday, 27 April, 2010

jQuery: Write less, do more!Whether you want to play with the DOM a little bit, get some help with your design or code or just need to experiment, we have found some jQuery snippets that you will definitely find inspirational (remember that in WordPress you need to replace $ with jQuery).

Here are some of our favorites:

How to detect any browser:

This way you can redirect IE users to getforefox.com :P

(if ($.browser.safari)) { } // Detects Safari
(if ($.browser.msie && $.browser.version > 6 )) // Detects IE6 and above
(if ($.browser.msie && $.browser.version <= 6 )) // Detects IE6 and below
(if ($.browser.mozilla && $.browser.version >= '1.8' )) // Detects FireFox 2 and above

How to switch CSS:

$('link[media='screen']').attr('href', 'Alternative.css');

How to style table rows:

Just add a tr.odd CSS color rule!

$("tr:odd").addClass("odd");

How to make elements disappear after a given amount of time:

Great for notifications!

//Here's how we used to do it in 1.3.2 using setTimeout
setTimeout(function() {
$('.mydiv').hide('blind', {}, 500)
}, 5000);
//And here's how you can do it with 1.4 using the delay() feature (this is a lot like sleep)
$(".mydiv").delay(5000).hide('blind', {}, 500);

How to center elements:

For the CSS impaired :P

jQuery.fn.center = function () {
this.css('position','absolute');
this.css('top', ( $(window).height() - this.height() ) / +$(window).scrollTop() + 'px');
this.css('left', ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + 'px');return this;}
//Use the above function as: $(element).center();

These tricks and many more here and here.