10 Useful jQuery Snippets

Sam Deering
Share

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

$("#lda-form").submit(function(){
	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) 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
  $(xml).find("Tutorial").each(function()
  {
    $("#output").append($(this).attr("author") + "");
  });
}

5. Class Hover add and Remove

$('.onhover').hover(
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 - offset.top;

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

8. Delay Animation or Effect

$(".alert").delay(2000).fadeOut();

9. Popup Windows Opener

jQuery('a.popup').live('click', function(){
	newwindow=window.open($(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
});