Monday, 20 June 2011

Java-Script tricks-2

Embed this code in script tag of you page's HTML to disable right-click contextual menu

$(document).ready(function(){
    $(document).bind("contextmenu",function(e){
        return false;
    });
})

This is a highly-requested code to use two CSS columns, and make them having exactly the same height.

function equalHeight(group) {
    tallest = 0;
    group.each(function() {
        thisHeight = $(this).height();
        if(thisHeight > tallest) {
            tallest = thisHeight;
        }
    });
    group.height(tallest);
}

/*
Usage:
$(document).ready(function() {
    equalHeight($(".recent-article"));
    equalHeight($(".footer-col"));
});
*/

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

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

That what I call a very simple, but very useful tip: This will return the number of matched elements:

$('element').size();

No comments:

Post a Comment