Hisfantor
Hisfantor

Reputation: 127

how to toggle css via jquery with the .css function

the function is triggered via a button so I thought every time you push it will check x set the background accordingly and put x in the other state so the next push gives the other result

I just saw that I can use the .css in an .toggle but I'm still curious why my solution wont work

var x = 0;

function toggledark(x){
    if (x == 0) {
        $('body').css({'background-color': 'red'});
        x+=1;
        return x;
    }
    else {
        $('body').css({'background-color': 'black'});
        x-=1;
        return x;
    }
}

I thought it will toggle but I only get black and it stays this way

Upvotes: 0

Views: 52

Answers (2)

Mohamed-Yousef
Mohamed-Yousef

Reputation: 24001

no need for x as integer unless you have another actions to do .. But while you using red and black you can use it like this

var color = 'red';   // default background color
function toggledark(){
   color = (color == 'red') ? 'black' : 'red';
   $('body').css({'background-color': color });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button onclick="toggledark()">Toggle</button>

AND if you have another actions to do and you must use if statement for it you can use it like

var color = 'red';   // default background color
function toggledark(){
   color = (color == 'red') ? 'black' : 'red';
   $('body').css({'background-color': color });
   if(color == 'red'){
      console.log('Red Theme');
   }
   if(color == 'black'){
      console.log('Black Theme');
   }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button onclick="toggledark()">Toggle</button>

Upvotes: 1

Patrik Alexits
Patrik Alexits

Reputation: 997

NOTE: I don't think this is a good solution, I would do it with classes, but I'll provide the code for your question if you want to do it this way

Here is the working code: http://jsfiddle.net/8ygrebp2/3/

I would do it like that since you are using Jquery:

HTML:

<button class="toggle">
Click me
</button>

JQuery:

var x = 0;

$('body').on('click', '.toggle', function(){
    if(x == 0){
        $('body').css('background-color', 'black');
    x+=1;
  } else {
    $('body').css('background-color', 'red');
    x-=1;
  }
});

Upvotes: 0

Related Questions