0

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
1
  • If you're consistently using it as an ID, you can use this.id to retrieve it inside whatever function you're running Commented Feb 26, 2015 at 13:05

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

4 Comments

Actually the button is the image. This is what I toggle.
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.
@dkar can you recreate your problem in the attached fiddle
@dkar function(idImg){ alert(idImg)}

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.