2
\$\begingroup\$

I have about 5 of these but I can't figure out how to consolidate them.

$('#togglemass').toggle(function () {
 $("#plusmass").attr("src", "minus.png");
 },
 function () {
 $(".plusmass").attr("src", "plus.png");
 });
$('#togglestar').toggle(function () {
 $(".plusstar").attr("src", "minus.png");
 },
 function () {
 $(".plusstar").attr("src", "plus.png");
 });
200_success
146k22 gold badges190 silver badges479 bronze badges
asked Mar 20, 2012 at 20:34
\$\endgroup\$
1
  • 1
    \$\begingroup\$ You should explain your use case and show the HTML to this, because I think the optimization could start on the HTML level. For example, I think you should't need to hard code the selector to the "plus" image in the JavaScript, but refer to it via the HTML structure. \$\endgroup\$ Commented Mar 21, 2012 at 9:03

1 Answer 1

1
\$\begingroup\$
$(function() {
 var togglePlusMin = function(clicker, img) {
 $(clicker).toggle(function() {
 $(img).attr("src", "minus.png");
 }, function() {
 $(img).attr("src", "plus.png");
 });
 };
 // can be used by
 togglePlusMin('#togglemass', '#plusmass'); 
 // BONUS: this will also work:
 var star = $('#togglestar'),
 starIcon = $('img.plusstar');
 togglePlusMin(star, starIcon);
})

As a comment, its generally a bad idea to use ids without a second context parameter

seand
2,4651 gold badge20 silver badges29 bronze badges
answered Mar 21, 2012 at 2:36
\$\endgroup\$
1
  • \$\begingroup\$ I have the worst luck, this is the 2nd time in a week someone beat me to an answer by a few seconds. \$\endgroup\$ Commented Mar 21, 2012 at 2:43

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.