\$\begingroup\$
\$\endgroup\$
1
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
-
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– RoToRa2012年03月21日 09:03:14 +00:00Commented Mar 21, 2012 at 9:03
1 Answer 1
\$\begingroup\$
\$\endgroup\$
1
$(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
-
\$\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– seand2012年03月21日 02:43:02 +00:00Commented Mar 21, 2012 at 2:43
default