Wednesday, May 6, 2015

Create own plugin for JQUERY

Image loading is a technique used to defer initialization of an object until the point at which it is needed.
Image loading images can help in decreasing web page size and load time.


Plugin Declaration

(function ( $ ) {
$.fn.bgveerload = function() {

  //plugin logic section

};
}( jQuery ));


The above snippet is a basic declaration for a JQuery plugin. bgveerload is the name of function which will be used to execute code in
plugin(name it whatever you like).

Now, if you need to call the above function on a group of  elements with class veer. Then you need to write the following code.


$(".veer").veerload();

Plugin Logic

Let’s have a look at the logic to veer load background images. The following piece of code will go in plugin logic section mentioned in
above snippet.


var elem = this;
Here this object refers to the current element on which function is being executed.


var veerload = function(elem){
var viewport_height = $(window).height();
var scrollTop = $(document).scrollTop();
//if there is any element left whose background image is not loaded
if(elem.filter(":not('.loaded')").length){
//loop through all the elements
elem.filter(":not('.loaded')").each(function() {
        var offset_top = $(this).offset().top;
var elem_height = $(this).height();
if(offset_top + elem_height/5 < viewport_height + scrollTop){
var bg_img = $(this).data('bgimg');
$(this).css({'background-image':"url("+bg_img+")"});
$(this).addClass('loaded');
}
   });
}
}
Now in above code i have declared a function veerload that does the work of veer loading background images.

I am loading the background image of a container only when the container is visible more that 33% in viewport. Once the background image is loaded then i add a class loaded to that element, so that i don’t have to check that element next time for veer loading.

Now that I have written veer load function, i need to call this function on certain events i.e on initialize, window scroll and window resize.


//call on initialise
veerload(elem);

//call after window scrolls
$(window).scroll(function(){
veerload(elem);
});

//call after window resize
$(window).resize(function(){
veerload(elem);
});
That’s it, i am done with the plugin.

HTML markup


<div class="img-box veer" data-bgimg='images/1.jpg'></div>

I have added a data attribute data-bgimg to specify background image.

Now, i just need to call the function in order to view veer loading in action.


$(document).ready(function(){
$('.veer').bgveerload();
});

No comments:

Post a Comment

Dharamart.blogspot.in