Monday, December 6, 2010

Tips for using jQuery

Find if something is hidden:


We use .hide(), .show() methods in jquery to change the visibility of an element. Use following code to check the whether an element is visible or not.
if($(element).is(":visible") == "true") {
//The element is Visible
}

Center an element on the Screen:

To make align the element to center.




jQuery.fn.center = function () {
this.css("position","absolute");
this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
return this;
}


//Use the above function as:
$(element).center();

Disable right-click contextual menu:

There’s many Javascript snippets available to disable right-click contextual menu, but JQuery makes things a lot easier:
$(document).ready(function(){
$(document).bind("contextmenu",function(e){
return false;
});
});

Get mouse cursor x and y axis:

This script will display the x and y value – the coordinate of the mouse pointer.
$().mousemove(function(e){
//display the x and y axis values inside the P element
$('p').html("X Axis : " + e.pageX + " | Y Axis " + e.pageY);
});
<p></p>

Font resizing:

Font Resizing is a very common feature in many modern websites. Here’s how to do it with JQuery.
$(document).ready(function(){
// Reset Font Size
var originalFontSize = $('html').css('font-size');
$(".resetFont").click(function(){
$('html').css('font-size', originalFontSize);
});
// Increase Font Size
$(".increaseFont").click(function(){
var currentFontSize = $('html').css('font-size');
var currentFontSizeNum = parseFloat(currentFontSize, 10);
var newFontSize = currentFontSizeNum*1.2;
$('html').css('font-size', newFontSize);
return false;
});
// Decrease Font Size
$(".decreaseFont").click(function(){
var currentFontSize = $('html').css('font-size');
var currentFontSizeNum = parseFloat(currentFontSize, 10);
var newFontSize = currentFontSizeNum*0.8;
$('html').css('font-size', newFontSize);
return false;
});
});

Preloading images:

When you’re using images in Javascript, a good thing is to preload it before you have to use it. This code will do the job:
jQuery.preloadImages = function()
{
for(var i = 0; i").attr("src", arguments[i]);
}
};

// Usage
$.preloadImages("image1.gif", "/path/to/image2.png", "some/image3.jpg");

0 comments:

Post a Comment