shxfee
shxfee

Reputation: 5306

scope collision while writing a jQuery plugin

I am trying to write a simple jQuery plugin just to see how its done. But i cant seem to run it twice simultaneously. Its basically a count down and all it does is get the text() value in a div and count it down until it reaches 1.

$('#box1').startCounter();
$('#box2').startCounter();

This call changes both this variables inside the function to point to #box2. Here is my jsfiddle

Its pretty confusing how this changes around in a jQuery plugin. thanks for any help :)

Upvotes: 1

Views: 160

Answers (1)

Felix Kling
Felix Kling

Reputation: 817238

You defined $this in global scope, so when startCount is called on the second element, the value is overwritten. Use var to make it local:

var $this = this;

DEMO


Instead of invoking the function again the element, you could also do something like this:

$.fn.startCount = function(count, div) {
    count = (count) ? count : parseInt($('span.no-display',this).text());
    var $target =  $('div.counter', this);

    var run = function() {
        if (count <= 1) {
            this.fadeOut().mouseout();
        }       
        else {
            count--;
            $target.text(count);
            setTimeout(run, 1000);
        }
    };
    run();
}

DEMO 2


And to make your plugin work in environments where $ does not refer to jQuery (jQuery.noConflict()), you should do:

(function($) {
    $.fn.startCount = ...
}(jQuery)); 

Upvotes: 3

Related Questions