Skip to content

Instantly share code, notes, and snippets.

@harmstyler
Last active January 4, 2016 00:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save harmstyler/8543048 to your computer and use it in GitHub Desktop.
Save harmstyler/8543048 to your computer and use it in GitHub Desktop.

Div full Width/Height of viewport with jQuery

This handy piece of code allows you to create a full width/height div according to the viewport. The code also handles window resizing. Great for modal dialogs or popups.

// global vars
var winWidth = $(window).width();
var winHeight = $(window).height();

// set initial div height / width
$('div').css({
  'width': winWidth,
  'height': winHeight,
});

// make sure div stays full width/height on resize
$(window).resize(function(){
  $('div').css({
    'width': winWidth,
    'height': winHeight,
  });
});

Source: http://www.jqueryrain.com/2013/03/div-full-widthheight-of-viewport-with-jquery/

Equal column heights

When you’re using columns to display content on your site, it definitely look better if the columns have an equal height. The code below will take all div elements with the .col class and will adjust their heights according to the bigger element. Super useful!

var maxheight = 0;
$("div.col").each(function(){
  if($(this).height() > maxheight) { maxheight = $(this).height(); }
});

$("div.col").height(maxheight);

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

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 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;
		}
	});
});

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

Load external content

Do you need to add some external content to a div? It is pretty easy to do with jQuery, as demonstrated in the example below:

$("#content").load("somefile.html", function(response, status, xhr) {
  // error handling
  if(status == "error") {
    $("#content").html("An error occured: " + xhr.status + " " + xhr.statusText);
  }
});

Source: http://api.jquery.com/load/

Partial page refresh

If you need to refresh only a portion of a page, the 3 lines of code below will definitely help. In this example, a #refresh div is automatically refreshed every 10 seconds.

setInterval(function() {
$("#refresh").load(location.href+" #refresh>*","");
}, 10000); // milliseconds to wait

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

Preload images

Query make it easy to preload images in the background so visitors won’t have to wait forever when they would like to display an image. This code is ready to use, just update the image list on line 8.

$.preloadImages = function() {
  for(var i = 0; i<arguments.length; i++) {
    $("<img />").attr("src", arguments[i]);
  }
}

$(document).ready(function() {
  $.preloadImages("hoverimage1.jpg","hoverimage2.jpg");
});

Source: http://css-tricks.com/snippets/jquery/image-preloader/

Automatically load content on scroll

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

Sort a list alphabetically

On some cases, it can be very useful a sort a long list by alphabetical order. This snippet take any list and order its element alphabetically.

$(function() {
  $.fn.sortList = function() {
    var mylist = $(this);
    var listitems = $('li', mylist).get();
    listitems.sort(function(a, b) {
      var compA = $(a).text().toUpperCase();
      var compB = $(b).text().toUpperCase();
      return (compA < compB) ? -1 : 1;
    });
    $.each(listitems, function(i, itm) {
      mylist.append(itm);
    });
  }
  $("ul#demoOne").sortList();
});

Source: http://stackoverflow.com/questions/13394796/javascript-jquery-to-sort-alphabetically-a-list-with-anchors

Table Stripes (Zebra)

When displaying data on a table, alternating colors on each row definitely increases readability. Here’s a snippet to automatically add a CSS class to one row of out two.

$(document).ready(function(){                             
  $("table tr:even").addClass('stripe');
});

Source: http://www.alovefordesign.com/5-jquery-must-have-code-snippets/

Test password strength

When you let users defining their password, it is generally a good thing to indicate how strong the password is. This is exactly what this code do.

First, assume this HTML:

<input type="password" name="pass" id="pass" />
<span id="passstrength"></span>

And here is the corresponding jQuery code. The entered password will be evaluated using regular expressions and a message will be returned to the user to let him know if his chosen password is strong, medium, weak, or too short.

$('#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/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment