0

I have a button named "on" (on.png) and a button named "off" (off.png). They are designed to act as on/off switches, so when clicked, the other should load. Since I don't want to deal with the path (which is the same for both), I am trying to do an attribute replace. The jQuery code below, however, does nothing and I can't find the error. Any help is appreciated.

$('#btnDining').css({'cursor':'pointer'}).on('click', function(e){
   var src = $(this).attr('src');
   $(this).attr('src', function(i, src){
      return (src.indexOf('off.png')!=-1)?src.replace("_off","_on"):src.replace("_on","_off");
   });
}); // end button click

3 Answers 3

1

You can do that :

$('#btnDining').css({'cursor':'pointer'}).on('click', function(e){
   var src = $(this).attr('src');
   src = (src.indexOf('off.png')!=-1)?src.replace("_off","_on"):src.replace("_on","_off");

   $(this).attr('src', src);
});

And I think, it's a more readable way..

Sign up to request clarification or add additional context in comments.

2 Comments

This killed all the scripts on the page but I don't see a syntax error.
I fixed it, forgot a '(' ! Sorry for the mistake
0

You are over-complicating things. Try something like this:

$('#btnDining').css('cursor','pointer').on('click', function(e){
   this.src = /_off/.test(this.src) ? 
        this.src.replace("_off","_on") : 
        this.src.replace("_on","_off");
}); // end button click

Also, consider using a CSS background-image as you will have more effective and cleaner code if you simply toggle classes and swap background images instead.

1 Comment

code is fine but background image and toggling classes is much smarter.
0

You are define src in the function scope of the outer function, then redefining it in the inner function scope.

$('#btnDining').css({'cursor':'pointer'}).on('click', function(e){
   var src = $(this).attr('src');
   $(this).attr('src', function(i, source){
      return (src.indexOf('off.png')!=-1)?src.replace("_off","_on"):src.replace("_on","_off");
   });
}); // end button click

I'm not sure which src is which. However, changing the function variable name in the attr function should fix your issue.

1 Comment

Do I not have to pass in the 'scr' from the outer function to the inner function? If not, then I don't need the var src line at all.

Your Answer

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.