user3342341
user3342341

Reputation: 7

jquery/javascript - how to "undo" a click event using if statement?

The below code takes into account different tags and turns the background red if the tag is clicked on. I want to code it so that if it is clicked on again, it changes back from red and 'deletes' the background, or at least set it to null. I have tried an if statement to no avail. I know that I can just make another click event that changes the background to white, but this is for experimental purposes and i was wondering if this CAN be done with if statements. thanks to ya.

<script>
    $(document).ready(function() {
        $("p, h1").click(function() {
            $(this).css("background-color", "red");
            if ($(this).css("background-color", "red")) {
                $(this).css("background-color", "null");
            }
        });
    });
</script>

Upvotes: 0

Views: 221

Answers (3)

Bic
Bic

Reputation: 3134

This is easily done using CSS, and is a bit more straight forward. If you create a CSS class for the click, then you can just toggle it on/off each time the item is clicked:

CSS

p, h1 {
    background-color: none;
}

p.red, p.h1 {
    background-color: red;
}

JavaScript:

$('p, h1').click(function() {
    $(this).toggleClass('red');
});

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

First you need to use the getter version of .css() like

if($(this).css("background-color") == "red"){

but it still won't work because, the css getter will return a rgb format value and will return non consistent values across browsers.

So the solution is to use a css based solution using toggleClass()

.red {
    background-color: red;
}

then

$(document).ready(function() {

   $("p, h1").click(function() {

      $(this).toggleClass("red");

   });

});

Demo: Fiddle

Upvotes: 3

Joseph Silber
Joseph Silber

Reputation: 219936

$('p, h1').click(function() {

    var $this    = $(this);
    var altColor = $this.data('altColor');

    $this.css('background-color', altColor ? '' : 'red');

    $this.data('altColor', ! altColor);
});

This answers your question, but you should really be using a CSS class for this.

Upvotes: 2

Related Questions