user1919
user1919

Reputation: 3938

Pass a variable inside a function Jquery

I have written this code:

var idImg = 'something';
$('#'+idImg).clickToggle(addMarker, destroyMarker);

Where clickToggle() is:

    $.fn.clickToggle = function(func1, func2) {

        var funcs = [func1, func2];
        this.data('toggleclicked', 0);
        this.click(function() {
            var data = $(this).data();
            var tc = data.toggleclicked;
            //$.proxy(funcs[tc], this)();
            funcs[tc].call(this);
            data.toggleclicked = (tc + 1) % 2;
        });
        return this;
    };

And addMarker() is a function which needs to get the variable idImg.

How can I pass the global variable idImg inside the addMarker function?

Thanks

EDITED

 $(document).ready(function(){
     $('img').hover(function() { 
       var idImg = $(this).attr('id');      
       $('#'+idImg).clickToggle(addMarker, destroyMarker);});
  });




 $.fn.clickToggle = function(func1, func2) {

    var funcs = [func1, func2];
    this.data('toggleclicked', 0);
    this.click(function() {
        var data = $(this).data();
        var tc = data.toggleclicked;
        $.proxy(funcs[tc], this)();
        data.toggleclicked = (tc + 1) % 2;
    });
    return this;
 };

var addMarker = function(){ alert(idImg)}  <-- I WANT THIS

 var destroyMarker = function(){
        DO SOMETHING ELSE
 };

Upvotes: 0

Views: 78

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

You can use an anonymous function

$('#'+idImg).clickToggle(function(){
    addMarker(idImg)
}, destroyMarker);

Demo: Fiddle

But in this case since that is the id of the button, this inside addMarker refers to the button so you could also use this.id to refer to something.

Demo: Fiddle

Upvotes: 2

Related Questions