12 useful jQuery tricks & Snippets That you might not know


Today, I have compiled 12 jQuery snippets that might help you in daily coding.

1. Find duplicated id and remove the one with JQuery

[js]
//Featured article fix//
var myFeatured = $(‘body.front div.featured’).attr(‘id’);
var theHidden;

$(‘body.front .front-latest-news div.article’).each(function(){
theHidden = $(this).attr(‘id’);

if(theHidden == myFeatured){
$(‘body.front div.front-latest-news div#’+theHidden).hide();
}
});
[/js]

source: http://snipplr.com/view/20737/

2. Scroll to Top of Page with jQuery

[js]

$(‘#someAnchor’).click(function() {
$(‘html, body’).animate({ scrollTop:0 }, ‘fast’);
return false;
});
[/js]

source: http://snipplr.com/view/36451/scroll-to-top-of-page-with-jquery/

3. Jquery Dropdown Select

[js]

var pId = "<? echo $_GET['category'] ?>";
<div>$("select#category option[name=" + pId + "]").prop("selected", true);</div>
[/js]

source: http://snipplr.com/view/63485/php-jquery-dropdown-select

4. Preloading images

Preloading images is useful: Instead of loading an image when the user request it, we preload them in the background so they are ready to be displayed. Doing so in jQuery is very simple, as shown below:

[js]
(function($) {
var cache = [];
// Arguments are image paths relative to the current page.
$.preLoadImages = function() {
var args_len = arguments.length;
for (var i = args_len; i–;) {
var cacheImage = document.createElement(‘img’);
cacheImage.src = arguments[i];
cache.push(cacheImage);
}
}

jQuery.preLoadImages("image1.gif", "/path/to/image2.png");
[/js]

Source: http://engineeredweb.com/blog/09/12/preloading-images-jquery-and-javascript

5. target=”blank” links

The following snippet will open all links with the rel=”external” attribute in a new tab/window. The code can be easily customized to only open links with a specific class.

[js]
$(‘a[@rel$='external']‘).click(function(){
this.target = "_blank";
});

/*
Usage:
<a href="https://freebiesdesign.com" rel="external">freebiesdesign.com/a>
*/

[/js]

Source: http://snipplr.com/view/315/-jquery–target-blank-links/

6. Smooth scrolling to an anchor

jQuery is known for its ability to let developers easily create stunning visual effects.
A simple, but nice effect is smooth sliding to an anchor. The following snippet will create a smooth sliding effect when a link with the topLinkclass is clicked.

[js]
$(document).ready(function() {
$("a.topLink").click(function() {
$("html, body").animate({
scrollTop: $($(this).attr("href")).offset().top + "px"
}, {
duration: 500,
easing: "swing"
});
return false;
});
});

[/js]

Source: http://snipplr.com/view.php?codeview&id=26739

7. Fade in/out on hover

Another very cool effect – which is very popular among clients – is indeed the fade in/fade out on mouseover. The code below set opacity to 100% on hover, and to 60% on mouseout.

[js]
$(document).ready(function(){
$(".thumbs img").fadeTo("slow", 0.6); // This sets the opacity of the thumbs to fade down to 60% when the page loads

$(".thumbs img").hover(function(){
$(this).fadeTo("slow", 1.0); // This should set the opacity to 100% on hover
},function(){
$(this).fadeTo("slow", 0.6); // This should set the opacity back to 60% on mouseout
});
});
[/js]

Source: http://snipplr.com/view/18606/

8. Equal column height

When building a column based website, you often want that all columns have the same height, as displayed in a good old table. This snippet calculate the height of the higher column and automatically adjust all other columns to this height.

[js]
var max_height = 0;
$("div.col").each(function(){
if ($(this).height() > max_height) { max_height = $(this).height(); }
});
$("div.col").height(max_height);
[/js]

Source: http://web.enavu.com/tutorials/top-10-jquery-snippets-including-jquery-1-4/

9. Enable HTML5 markup on older browsers

HTML5 is definitely the future of client-side web development. Unfortunely, some old browsers do not even recognize new tags such as header or section. This code will force old browsers to recognize the new tags introduced by HTML5.

[js](function(){if(!/*@cc_on!@*/0)return;var e = "abbr,article,aside,audio,bb,canvas,
datagrid,datalist,details,dialog,eventsource,figure,footer,header,hgroup,mark,menu,
meter,nav,output,progress,section,
time,video".split(‘,’),i=e.length;while(i–){document.createElement(e[i])}})()
[/js]

A better solution is to link the .js file to the <head> part of your HTML page:

[js]<!–[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]–>[/js]

Source: http://remysharp.com/2009/01/07/html5-enabling-script/

10. Test if the browser supports a specific CSS3 property

Here is a simple jQuery function to check if the client browser supports a specific CSS3 property. In this example, border-radius is the property we want to check, but of course this can be modified easily.

Note that when passing the property, you have to omit the dash to prevent syntax error. So instead of border-radius, you have to pass “borderRadius” or “BorderRadius”.

[js]

var supports = (function() {
var div = document.createElement(‘div’),
vendors = ‘Khtml Ms O Moz Webkit’.split(‘ ‘),
len = vendors.length;

return function(prop) {
if ( prop in div.style ) return true;

prop = prop.replace(/^[a-z]/, function(val) {
return val.toUpperCase();
});

while(len–) {
if ( vendors[len] + prop in div.style ) {
// browser supports box-shadow. Do what you need.
// Or use a bang (!) to test if the browser doesn’t.
return true;
}
}
return false;
};
})();

if ( supports(‘textShadow’) ) {
document.documentElement.className += ‘ textShadow';
[/js]

Source: http://snipplr.com/view/44079

11. Get url parameters

Getting url parameters is pretty easy using jQuery. The following snippet will do the job!

[js]
$.urlParam = function(name){
var results = new RegExp(‘[\\?&]‘ + name + ‘=([^&#]*)’).exec(window.location.href);
if (!results) { return 0; }
return results[1] || 0;
}
[/js]

Source: http://snipplr.com/view/26662

12. Disable the “Enter” key in forms

By default, a form can be submitted by pressing the “Enter” key. Thought, on some form, this keyboard shortcut can cause problems. Here is how you can prevent unwanted form submission by disabling the “Enter” key with jQuery.

[js]

$("#form").keypress(function(e) {
if (e.which == 13) {
return false;
}
});
[/js]

Source: http://snipplr.com/view/10943/disable-enter-via-jquery/