Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS Toggle Button incorrect logic

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;
    }
    });
like image 481
Reid Barber Avatar asked May 18 '26 20:05

Reid Barber


1 Answers

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.

like image 194
Yeldar Kurmangaliyev Avatar answered May 20 '26 10:05

Yeldar Kurmangaliyev