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
};
asked Feb 26, 2015 at 13:02
user1919
3,96819 gold badges72 silver badges105 bronze badges
1 Answer 1
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
answered Feb 26, 2015 at 13:04
Arun P Johny
389k68 gold badges533 silver badges532 bronze badges
Sign up to request clarification or add additional context in comments.
4 Comments
user1919
Actually the button is the image. This is what I toggle.
user1919
Hmm. I try both but doesnt seem to work. In the first case I added the anonymous function and the idImg as input in the addMarker() but didnt work.
Arun P Johny
@dkar can you recreate your problem in the attached fiddle
Arun P Johny
@dkar
function(idImg){ alert(idImg)}lang-js
this.idto retrieve it inside whatever function you're running