Showing posts with label jQuery. Show all posts
Showing posts with label jQuery. Show all posts

Monday, February 22, 2010

Image preloading techniques deeply

For better display and visitor interaction, image preloading must be implemented in some cases. We can preload image following two techniques:

1.Using JavaScript
2.Using CSS

Using JavaScript :

The simplest way to preload an image is to instantiate a new Image() object in JavaScript and pass the URL of the image you want to preload.

For example, if you want to preload an image, simply create a new JavaScript Image() object and place the script in the head section of the page to ensure it runs as soon as the page loads.

<script type="text/javascript">
Image= new Image();
Image.src = "pic1.jpg";
</script>

Preloading Image with JavaScript array

In practice, you will need to preload more than just one image to smooth effect on image rollovers. A JavaScript array of images can be preloaded as:
<script type="text/javascript">
     images = new Array();
     images[0]="pic1.jpg";
     images[1]="pic2.jpg";
     images[2]="pic3.jpg";
    imageObj = new Image();
     // start preloading
     for(i=0; i<images.length; i++)
     {
          imageObj.src=images[i];
     }
</script>

Preloading Image with jQuery

Image preloading which is pretty simple with jQuery is the solution. The code snippet that is around the Internet for some time provides image preloading:

jQuery.preloadImages = function() {  
     for(var i = 0; i<arguments.length; i++)  
    {
          jQuery("<img>").attr("src", arguments[i]);  
    }
}
In order to use the above function, an array of image urls should be provided:
$.preloadImages("image.gif", "/themes/images/BD/image2.png", "/themes/images/BD/flicker.jpg");

Using CSS :

Image preloading with CSS can be achieved by a simple <div> with style "display:none;" containing all <img> tags of images to be preloaded.

<div style="display:none;">
  <img src="/images/imageA.jpg" >
  <img src="/images/imageB.jpg" >
</div>

The CSS preloading code must be in the BODY area of the HTML code. It will not work in the HEAD section. The optimum position depends on how the preloaded images will be used. If the images will be used sometime after the web page has finished loading, the preload <div> can be placed below the page content. If the images will be used immediately, such as automatic background image change, the preload <div> should be placed on the top section of the BODY area.

Now compare these two methods to understand the safest and easiest method for preloading images:

Preloading with JavaScript

In order to preload images with JavaScript, browsers should support JavaScript and it should be turned on. Without JavaScript, the preloading will not happen and each time the image is needed, it will be fetched. If the preloaded images will be used on image effects such as rollovers or other effects that require JavaScript, preloading with JavaScript is the best choice. That way, for browsers that are not supporting JavaScript, the images will not be preloaded. 

The JavaScript preloading code can be placed anywhere in the page including the HEAD area of the page. If all preloading is done with JS, most of the search engine spiders won’t index the images.

Preloading with CSS

Preloading with CSS will work even if the browser’s JavaScript is turned off. The CSS preloading section should be placed in the BODY of the HTML. 

Search engine spiders index the images when they are preloaded with CSS.

Notes on Image Preloading:

Users with slow Internet connection speeds will navigate away if you preload too many or too large images before page content is displayed. 

The JavaScript and the CSS/HTML image preloading code can be used on the same web page at the same time.

Both techniques can be used more than once on the same web page to preload additional images at different points.

Tuesday, February 16, 2010

Fully Understanding $.grep()

At its core, $.grep is a simple little method that will filter through an array and sift out any items that don't pass a particular control. For example, if we have an array of the numbers 1-10, and want to filter out any values that are below 5, we can do:
var nums = '1,2,3,4,5,6,7,8,9,10'.split(',');

nums = $.grep(nums, function(num, index) {
  // num = the current value for the item in the array
  // index = the index of the item in the array
  return num > 5; // returns a boolean
});

console.log(nums) // 6,7,8,9,10
Or let's say that you have an array of numbers and strings, and you want to sift out all of the strings, leaving just an array of numbers. One way that we can accomplish this task is with $.grep.
var arr = '1,2,3,4,five,six,seven,8,9,ten'.split(',');

arr = $.grep(arr, function(item, index) {
  // simply find if the current item, when passed to the isNaN, 
  // returns true or false. If false, get rid of it!
  return !isNaN(item); 
});

console.log(arr); // 1,2,3,4,8,9

live demo

Saturday, February 13, 2010

DIsable Right Click with jQuery

There are a lot of examples of javascript code snippets to disable right click on web pages. However, jQuery makes it a lot easier:

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

Saturday, January 16, 2010

Flex Level Drop Down Menu With jQuery

Flex Level Drop Down Menu is a jQuery plugin that lets you add a multi level drop down menu to any link on the page. You can use this plugin to create both horizontal or vertical menu bars, since drop down menu can appear below or to the right of the anchor element.

Structure wise Flex Level Drop Down Menu is simply defined as a regular nested UL on the page, making it very intuitive to set up. By default menu will appear beneath the anchor link, with no additional x or y offset. You can modify both of these aspects using configuration options.
Features
  • Lets you associate a multi level drop down menu to any link on the page, by inserting the custom attribute "data-flexmenu" inside the link.
  • Control whether the menu drops down or to the right of the anchor link, through the use of the custom attribute "data-dir".
  • Ability to fine tune the position of the drop down menu relative to the anchor link, by specifying a custom x and y offset using the attribute "data-offsets".
  • Each drop down menu is simply defined as a regular, hidden nested UL on the page.
  • Main and sub menus repositions themselves when too close to the right or bottom edges of the browser window so they remain in view
  • Ability to customize the expand animation speed
  • Ability to specify the delay before each menu and its sub menus appear/ disappear when the mouse rolls over and out of them.
Developed by Dynamic Drive; Flex Level Drop Down Menu is available for download for Free. You can find further information, demo & download on Dynamic Drive Website.

Sunday, January 10, 2010

Creating a plugin for jQuery ( Macros in jQuery)

Creating a plugin for jQuery is incredibly simple and is a very useful way to abstract complex behaviours so that they can be used repeatedly as part of your jQuery "chains".

But, when the time comes, and you’re faced with the decision to either create a jQuery plugin or to simply create a regular function, everything suddenly becomes quite complicated. First, you'll wonder whether the piece of behaviour you want to abstract is best kept under the jQuery namespace, and then you'll doubt its applicability to the DOM-centred jQuery chain, and then sometimes you’ll recede to something you’re much more comfortable with, a regular ol' JavaScript function.

If we forget about the plugins available online, and we simply focus on your plugins, made and used within a specific project, then the question of whether a plugin is really the right route becomes all the more difficult to answer. Are you going to benefit from extending jQuery’s API? Will the readability of your code benefit?


For example:

function applyColors(elems) {
    $(elems).css({
        color: config.color,
        backgroundColor: config.bgColor,
        borderColor: config.bdColor
    });
}
 
// Call it:
var myElems = $('div.something');
applyColors(myElems);

applyColors encapsulates some behaviour that is needed frequently, and that’s why it’s been abstracted into a function. To some, this approach is lacking in that it doesn’t harness the full power of jQuery, and more specifically, jQuery’s plugin mechanism. How about this:

jQuery.fn.applyColors = function( {
    return this.css({
        color: config.color,
        backgroundColor: config.bgColor,
        borderColor: config.bdColor
    });
};
 
// Call it:
$('div.something').applyColors();

Cleaner? More readable? I think so.
Many developers are not prepared to extend jQuery’s API with their own simple abstractions. I don’t know why. But, I hope, that jQuery macros can help in lowering the barrier to extending jQuery. For Details

jQuery Captify Plugin v1.1.3

Captify is a plugin for jQuery written by Brian Reavis (@brianreavis) to display simple, pretty image captions that appear on rollover. It has been tested on Firefox, Chrome, Safari, and the wretched Internet Explorer. Captify was inspired by ImageCaptions, another jQuery plugin for displaying captions like these.

The goal of Captify is to be easy to use, small/simple, and completely ready for use in production environments (unlike ImageCaptions at the moment). Also, it's only 2.3kb!

What do you think? Feel free to drop by my blog and/or follow me on twitter!

For details

Saturday, January 9, 2010

10 jQuery snippets for efficient developers

jQuery is by far my favorite Javascript framework, which allows developers to create stunning visual effects, manipulate data properly, and much more. In this article, I have compiled 10 extremely useful jQuery snippets.

Load jQuery from Google
http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js
Source

Validate a date of birth using jQuery
Validating dates of birth are a common task on websites that have content available only for users 18+ years old. Using jQuery, this is very easy to do, as shown in the following example:

$("#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)
Source

Make sure an image has loaded properly
How do you know if an image has been properly loaded? In some particular cases such as a captcha, problems with the user experience may happen if an image hasn’t been loaded properly.
Using the simple piece of code below, you’ll be able to know if your image is displayed on the user screen.

$('#myImage').attr('src', 'image.jpg').load(function() {
alert('Image Loaded');
});
Source

XHTML 1.0 Strict valid target="blank" attribute
The target="blank" attribute can be useful when you want a link to be opened in a new tab or window. Though, the target=”blank” attribute is not valid XHTML 1.0 Strict.
using jQuery, you can achieve the same functionality without having validation problems.

$("a[@rel~='external']").click( function() {
window.open( $(this).attr('href') );
return false;
});

Source

Search within text using jQuery
The following function will allow full text search on the page using jQuery. The feature is not only cool, but useful at the same time.

$.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;
};
Source

"outerHTML" function
The well-known innerHTML property is very useful: It allows you to get the content of an HTML element. But what if you need the content, and also the HTML tags? You have to create an “outerHTML” function like this one:

jQuery.fn.outerHTML = function() {
return $('
').append( this.eq(0).clone() ).html();
};< /div>

Source

Clean way to open popup windows
Although their popularity decreased with the rise of popup blockers, pop-up windows can still be useful in some particular cases. Here is a nice snippet to open links in pop-up windows. Just add the popup css class to your link to make it work.

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

Quick and easy browser detection
Cross-browser issues are definitely the biggest problem a front-end web developer has to face at work. Thanks to jQuery, detecting browsers have never been so easy, as shown below:

//A. Target Safari
if( $.browser.safari ) $("#menu li a").css("padding", "1em 1.2em" );

//B. Target anything above IE6
if ($.browser.msie && $.browser.version > 6 ) $("#menu li a").css("padding", "1em 1.8em" );

//C. Target IE6 and below
if ($.browser.msie && $.browser.version <= 6 ) $("#menu li a").css("padding", "1em 1.8em" ); //D. Target Firefox 2 and above if ($.browser.mozilla && $.browser.version >= "1.8" ) $("#menu li a").css("padding", "1em 1.8em" );
Source

Get relative mouse position
Do you ever want to be able to get the relative mouse position? This very handy function will return the mouse position (x and y) according to its parent element.

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

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

Parse as xml file using jQuery
XML files are very important on the Internet, and any developer has to parse them from time to time. Thanks to jQuery and all its powerful functions, the whole process is painless, as demonstrated in the example code below:

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

Nice looking autocomplete plugin for jQuery

http://code.drewwilson.com/entry/autosuggest-jquery-plugin