Bardelman
Bardelman

Reputation: 2298

Jquery removeClass doesn't work when trying to simulate an active button with a DIV

Since i'm not good in CSS, I'm trying to simulate a pressed button behaviour (:active i think..) by adding a CSS "glow" class to a DIV with jquery addClass and then remove it after a little delay

this is how i write the code :

  $( ".cpUpbtnsclass" ).on('click', function() {

        console.log($( this ).attr('id')+" is clicked and a class will be added ! ");

           $( this ).addClass( "glow");

        setTimeout(function(){
            $( this ).removeClass( "glow");
        },300);
    });

and this is the class i want to add :

.glow {
box-shadow: 0px 0px 15px 5px rgba(255, 255, 190, .75);
}

i see the glow effect added with addClass but then i don't see it disappearing after 300 ms.

Upvotes: 0

Views: 196

Answers (3)

kapil_dev
kapil_dev

Reputation: 86

$(function(){
    $(document).on('click', '.cpUpbtnsclass', function(){
        console.log($( this ).attr('id')+" is clicked and a class will be added ! ");
           $('.cpUpbtnsclass').addClass( "glow");
        setTimeout(function(){
            $('.cpUpbtnsclass').removeClass( "glow");
        },300);
    })
})

Demo here http://jsfiddle.net/N5Kk6/

Upvotes: 1

Try

$(".cpUpbtnsclass").on('click', function () {
    var this1 = $(this); //cache your selector 
    this1.addClass("glow"); 
    setTimeout(function () {
        this1.removeClass("glow"); //use cached selector 
    }, 300);
});


The timeout creates a new scope so your $(this) is not element you think inside setTimeout

Upvotes: 2

adeneo
adeneo

Reputation: 318302

The timeout creates a new scope where this is no longer the element :

$( ".cpUpbtnsclass" ).on('click', function() {
    var self = this;

    $( this ).addClass( "glow");

    setTimeout(function(){
        $( self ).removeClass( "glow");
    },300);
});

Upvotes: 2

Related Questions