Yoona Yoona - 3 months ago 10
Javascript Question

Make jQuery function run individually

I create function to get specific height of some different div that has same class 'parallax', the problem is that it works but it can only get height of only first div and apply it to others.here my code, please suggest me what to do, I'm still a beginner.

jQuery.fn.do_para = function() {
var section_effect = jQuery(this);
var height = section_effect.height();
alert(height);
//do something with height
}

if(jQuery('.page_section').hasClass('parallax')) {
jQuery(this).do_para();
}


html looks like this

<div class="page_section parallax" style="height:500px"></div>
<div class="page_section"></div>
<div class="page_section parallax" style="height:700px"></div>

Answer

The problem would be because this in the outer part of a jQuery plugin refers to the jQuery object/collection itself, not the individual elements of that collection. So, instead of:

 jQuery.fn.do_para = function() {
    var section_effect = jQuery(this);
    var height = section_effect.height();
    alert(height);
    //do something with height
 }

You should instead use:

 jQuery.fn.do_para = function() {

    // if you don't want to return the collection
    // omit the 'return' (but this will break
    // the traditional jQuery chaining if you do):
    return this.each(function(){

        // within the each() method 'this' refers
        // to each individual element of the
        // collection passed to the plugin:
        var section_effect = jQuery(this);

        var height = section_effect.height();
        alert(height);
        //do something with height
    });
 }

The reason the problem was referring to the whole collection is that when a jQuery method is used as a getter (using the method without passing an argument) it will refer to the first element in the collection, and return the value from that first element.

If you'd wanted, for some reason, to retrieve an array of values instead you could have used: jQuery.fn.do_para = function() { var section_effect = jQuery(this);

    // here we use the map() method to iterate over
    // the collection and, from each element in the
    // collection, return the height:
    var height = section_effect.map(function(){
      $(this).height();

    // here we use get() to turn the jQuery map into
    // an Array:
    }).get();

    alert(height);
    //do something with height
 }

Incidentally if, within the plugin's code, you want to use an alias for jQuery – to save typing, if nothing else – then you can instead compose your plugin in the following way, using an Immedately-Invoked Function Expression:

// the argument to the function is the
// alias with which you refer to
// jQuery:
(function ($) {

  $.fn.do_para = function(){
    return this.each(function(){
      var section_effect = $(this);
      // rest of your code..
    });
  });

// passing jQuery into the function:
})(jQuery);

Bibliography:

Comments