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\$ 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

\$\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

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.