user3442787
user3442787

Reputation: 15

Jquery Listen for click event and class change

I'm trying to listen for the click/toggle event (class change) when a user clicks on the a button created using an a tag:

<a href="#" class="ccc-toggle-shadow"></a>

The process goes like this:

If the user clicks on the link, a class, toggled, is added to the tag, the button changes color to red:

<a href="#" class="ccc-toggle-shadow toggled"></a>

and If the user clicks on the link again, the class, toggled, is removed, the button changes color to green:

<a href="#" class="ccc-toggle-shadow"></a>

Here is what I have so far to listen to the changes:

So basically when a user clicks on the button, the toggle class is added to the button class automatically. I want to capture the event when the new class has been added. Once it sees that the button has the new class, toggled, do something.

var a = $("a.ccc-toggle-shadow");  

a.on("click", function(e) {
    e.preventDefault();
    var b = $(this);

    if (b.hasClass('toggled')) {
        console.log('activated');  //test in console
    } else {
        console.log('deactivated'); // test in console
    }
    return false;
});

I can't seem to get it to work. Can someone please assist me?

Upvotes: 1

Views: 2666

Answers (3)

user3442787
user3442787

Reputation: 15

Solution: Since I was using a plugin, I had to wait for the plugin to be loaded in order to listen to the event. I had to use jQuery(window).load(function(){});

Upvotes: 0

Kiran
Kiran

Reputation: 20313

use .toggleClass() to add/remove one or more classes to html elements:

$("a.ccc-toggle-shadow").click(function(e) {
    e.preventDefault();
    $(this).toggleClass('toggled');
});

DEMO

Upvotes: 0

Felix
Felix

Reputation: 38112

You can use .toggleClass() instead:

Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument.

$("a.ccc-toggle-shadow").on('click', function(e) {
    e.preventDefault();
    $(this).toggleClass('toggled');
});

Fiddle Demo

Upvotes: 1

Related Questions