samedi 2 mai 2015

jQuery will only execute 'if' of if/else statement on click

I'm very new at jQuery and have just been playing around with different things to try to get more comfortable. I have hit an issue here and haven't had luck fixing it despite looking for answers for a very long time.

I'm finding that the if/else statement will only execute the 'if'. So on the click, the square turns black, but afterwards it doesn't seem to accept any more clicks to change back to blue.

I found a lot of suggestions were to try .on('click', function(){ instead but that didn't change anything. I also tried another way I saw someone writing the css (({'background-color':'blue'})) but that didn't help either.

I know this is probably a really simple answer but, as mentioned, I'm new at this. I'd really appreciate any help at all.

Thank you.

$(document).ready(function(){
$('button').click(function () {
    if ($('.square').css('background-color', 'blue')) {
    $('.square').css('background-color', 'black');
    } else {
        $('.square').css('background-color', 'blue');
    }
});
});

& css

.square {
width: 100px;
height: 100px;
margin: 50px auto; 
background-color: blue;
}

& html

<div class="square"></div>
<button>click</button>

Aucun commentaire:

Enregistrer un commentaire