I have a button that I want to change every time it is clicked. It is working correctly, except for the fact that it doesn't change on the first 2 clicks. What is wrong with my logic?
var soc_selected = new Boolean(false);
$('#soccer-button').click(function() {
if (soc_selected == false) {
$('#soccer-button').css('background', 'url(assets/img/sports/soccer_us.png)');
soc_selected ^= true;
}
else if (soc_selected == true){
$('#soccer-button').css('background', 'url(assets/img/sports/soccer.png)');
soc_selected ^= true;
}
});
Why do you need all these strange manipulations with XOR, which actually result in integer, but not a boolean?
You can make it much simpler:
var soc_selected = false; // not Boolean(false)
$('#soccer-button').click(function() {
var bg = soc_selected
? 'url(assets/img/sports/soccer_us.png)'
: 'url(assets/img/sports/soccer.png)';
$('#soccer-button').css('background', bg);
soc_selected = !soc_selected;
});
In my opinion, it looks much more transparent and clear now.
Another good option is to define styles in CSS classes and do the following:
$("#soccer-button").click(function() {
$(this).toggleClass('us');
});
It will also solve the problem with necessity to set the initial background.
Here is the working JSFiddle demo.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With