Useful jQuery code snippets

Smooth scrolling to #anchor

On your site footer, it is very useful to provide a quick way for your visitors to scroll back to the top of the page. Here is a simple way to smooth scroll to a #anchor of your choice.

// HTML:
// <h1 id="anchor">Lorem Ipsum</h1>
// <p><a href="#anchor" class="topLink">Back to Top</a></p>


$(document).ready(function() {

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

});

Source: http://snipplr.com/view/26739/jquery–smooth-scroll-to-anchor/

Image resizing using jQuery

Although you should resize your images on server side (using PHP and GD for example) it can be useful to be able to resize images using jQuery. Here’s a handy code snippet to do it.

$(window).bind("load", function() {
	// IMAGE RESIZE
	$('#product_cat_list img').each(function() {
		var maxWidth = 120;
		var maxHeight = 120;
		var ratio = 0;
		var width = $(this).width();
		var height = $(this).height();
	
		if(width > maxWidth){
			ratio = maxWidth / width;
			$(this).css("width", maxWidth);
			$(this).css("height", height * ratio);
			height = height * ratio;
		}
		var width = $(this).width();
		var height = $(this).height();
		if(height > maxHeight){
			ratio = maxHeight / height;
			$(this).css("height", maxHeight);
			$(this).css("width", width * ratio);
			width = width * ratio;
		}
	});
	//$("#contentpage img").show();
	// IMAGE RESIZE
});

Source: http://snipplr.com/view/62552/mage-resize/

Load content on scroll automatically

Some websites such as Twitter loads content on scroll. Which means that all content is dynamically loaded on a single page as long as you scroll down.

Here’s how you can replicate this effect on your website:

var loading = false;
$(window).scroll(function(){
	if((($(window).scrollTop()+$(window).height())+250)>=$(document).height()){
		if(loading == false){
			loading = true;
			$('#loadingbar').css("display","block");
			$.get("load.php?start="+$('#loaded_max').val(), function(loaded){
				$('body').append(loaded);
				$('#loaded_max').val(parseInt($('#loaded_max').val())+50);
				$('#loadingbar').css("display","none");
				loading = false;
			});
		}
	}
});

$(document).ready(function() {
	$('#loaded_max').val(50);
});

Source: http://fatfolderdesign.com/173/content-load-on-scroll-with-jquery

Test Password Strength

When building forms, it’s a very good practice to provide verifications on the front-end first so the visitor do not have to submit the form endlessly to correct problems. This code snippet is using regular expressions to test if a password is strong enough. Of course, don’t forget to validate your forms on the server side as well!

$('#pass').keyup(function(e) {
     var strongRegex = new RegExp("^(?=.{8,})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\W).*$", "g");
     var mediumRegex = new RegExp("^(?=.{7,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))).*$", "g");
     var enoughRegex = new RegExp("(?=.{6,}).*", "g");
     if (false == enoughRegex.test($(this).val())) {
             $('#passstrength').html('More Characters');
     } else if (strongRegex.test($(this).val())) {
             $('#passstrength').className = 'ok';
             $('#passstrength').html('Strong!');
     } else if (mediumRegex.test($(this).val())) {
             $('#passstrength').className = 'alert';
             $('#passstrength').html('Medium!');
     } else {
             $('#passstrength').className = 'error';
             $('#passstrength').html('Weak!');
     }
     return true;
});

Source: http://css-tricks.com/snippets/jquery/password-strength/

Equalize heights of div elements

Equalizing heights of div elements is not possible (or very hacky) to do in pure CSS, so jQuery is here to help. The code below will automatically adjust the heights of div elements according to the higher one.

var maxHeight = 0;

$("div").each(function(){
   if ($(this).height() > maxHeight) { maxHeight = $(this).height(); }
});

$("div").height(maxHeight);

Source: http://css-tricks.com/snippets/jquery/equalize-heights-of-divs/

Simple and efficient png fix for IE6

In 2013, IE6 is finally almost gone and people are using newer browsers. But still, in some situations you have to care about this horrible browser and provide a IE6-compliant website. As IE6 can’t deal with png transparency, here’s a super simple jQuery hack to force png rendering.

Just add a .pngfix class to anything you want fixed or put in some other jQuery selector.

$('.pngfix').each( function() {
   $(this).attr('writing-mode', 'tb-rl');
   $(this).css('background-image', 'none');
   $(this).css( 'filter', 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="path/to/image.png",sizingMethod="scale")');
});

Source: http://itknowledgeexchange.techtarget.com/itanswers/

Parsing json with jQuery

Parsing json data with jQuery is not complicated at all. Here is an efficient example on how to parse json data and append it to your web page.

function parseJson(){
	//Start by calling the json object, I will be using a 
        //file from my own site for the tutorial 
	//Then we declare a callback function to process the data
	$.getJSON('hcj.json',getPosts);
 
	//The process function, I am going to get the title, 
        //url and excerpt for 5 latest posts
	function getPosts(data){
 
		//Start a for loop with a limit of 5 
		for(var i = 0; i < 5; i++){
			//Build a template string of 
                        //the post title, url and excerpt
			var strPost = '<h2>' 
				      + data.posts[i].title
				      + '</h2>'
				      + '<p>'
				      + data.posts[i].excerpt
				      + '</p>'
				      + '<a href="'
				      + data.posts[i].url
				      + '" title="Read '
				      + data.posts[i].title
				      + '">Read ></a>';
 
			//Append the body with the string
			$('body').append(strPost);
 
		}
	}
 
}
 
//Fire off the function in your document ready
$(document).ready(function(){
	parseJson();				   
});

Source: http://hankchizljaw.co.uk/tutorials/parse-json-with-jquery-snippet/06/05/2012/

Alternating Row Colors

On big lists or tables, alternating row colors can drastically improve readability. Here’s how to alternate row colors on a list of elements using some jQuery. You can use any HTML element you like, td, tr, li, etc…

//jquery
  $('div:odd').css("background-color", "#F4F4F8");
  $('div:even').css("background-color", "#EFF1F1");


//html example
<div>Row 1</div>
<div>Row 2</div>
<div>Row 3</div>
<div>Row 4</div>

Facebook like image preloader

Ever noticed how fast images load when paging through a Facebook photo album? This is because Facebook is preloading each of these images into your browser’s cache before you even view them. Here’s how you can achieve a similar behavior on your website using some jQuery magic.

var nextimage = "/images/some-image.jpg";
$(document).ready(function(){
window.setTimeout(function(){
var img = $("<img>").attr("src", nextimage).load(function(){
//all done
});
}, 100);
});

Source: http://www.nealgrosskopf.com/tech/thread.php?pid=77

Make entire div clickable

Here’s an easy way to make the parent div of a link clickable. Let’s say you have this html code:

<div class="myBox">
     blah blah blah.
    <a href="http://google.com">link</a>
</div>

The following lines of jQuery will make the entire div clickable:

$(".myBox").click(function(){
     window.location=$(this).find("a").attr("href"); 
     return false;
});

Source: http://css-tricks.com/snippets/jquery/make-entire-div-clickable/

Leave a Reply

Your email address will not be published. Required fields are marked *