Skip to main content

10 Useful jQuery Snippets

By Sam Deering



Free JavaScript Book!

Write powerful, clean and maintainable JavaScript.

RRP $11.95

Nowadays, jQuery is far the most favorite Javascript framework of many developers. Through jQuery they will be able to create stunning visual effects, manipulate data, etc. You had been probably in my other posts before so I won’t explain much from what are the benefits can be gained from jQuery.

1. Quick Copy Paste

2. Date of Birth

	var day = $("#day").val();
	var month = $("#month").val();
	var year = $("#year").val();
	var age = 18;
	var mydate = new Date();
	mydate.setFullYear(year, month-1, day);

	var currdate = new Date();
	currdate.setFullYear(currdate.getFullYear() - age);
	if ((currdate - mydate) < 0){
		alert("Sorry, only persons over the age of " + age + " may enter this site");
		return false;
	return true;

3. Text Search [js] $.fn.egrep = function(pat) { var out = []; var textNodes = function(n) { if (n.nodeType == Node.TEXT_NODE) { var t = typeof pat == 'string' ? n.nodeValue.indexOf(pat) != -1 : pat.test(n.nodeValue); if (t) { out.push(n.parentNode); } } else { $.each(n.childNodes, function(a, b) { textNodes(b); }); } }; this.each(function() { textNodes(this); }); return out; };

4. XML file Parser

function parseXml(xml) {
  //find every Tutorial and print the author
    $("#output").append($(this).attr("author") + "");

5. Class Hover add and Remove

function(){ $(this).addClass('hover_style_class') },
function(){ $(this).removeClass('hover_style_class') }

6. Partial Page Refresh

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

7. Mouse Position

function rPosition(elementID, mouseX, mouseY) {
  var offset = $('#'+elementID).offset();
  var x = mouseX - offset.left;
  var y = mouseY -;

  return {'x': x, 'y': y};

8. Delay Animation or Effect


9. Popup Windows Opener

jQuery('a.popup').live('click', function(){$(this).attr('href'),'','height=200,width=150');
	if (window.focus) {newwindow.focus()}
	return false;

10. Each Element

$("input").each(function (i) {
//do something with each and pass i as the number of the element

Sam Deering has 15+ years of programming and website development experience. He was a website consultant at Console, ABC News, Flight Centre, Sapient Nitro, and the QLD Government and runs a tech blog with over 1 million views per month. Currently, Sam is the Founder of Crypto News, Australia.

New books out now!

Learn valuable skills with a practical introduction to Python programming!

Give yourself more options and write higher quality CSS with CSS Optimization Basics.