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");
  });
\$\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\$
    – RoToRa
    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

\$\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\$
    – seand
    Mar 21, 2012 at 2:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.