user1896653
user1896653

Reputation: 3327

How to remove active class by mouse click

I've made two box which background will be changed at hover and active state. Here is my work: http://jsfiddle.net/3Vbz8/

At there, when I click "one" it'll set to it's active state(Green Background). That's fine. When I click "Two", it'll set to active state and "one" will return to it's previous state(Grey Background). That's also fine to me.

But, I want when "one" is set to active state, at that time, if I click on "One", it'll return back to it's normal state(grey background) too. Similar event should be happen for "Two" too. How can I make this?

My applied script:

$('.toggle').click(function(){
   $('.toggle').removeClass("active");
   $(this).toggleClass("active");
});

...........UPDATE...........

Krishna helped me with this: http://jsfiddle.net/3Vbz8/1/

$('.toggle').click(function(){
   $('.toggle').not(this).removeClass("active");
   $(this).toggleClass("active");
});

I've noticed a issue which should be updated for my project. That issue is: if "one" is on "active" state, at that time, if any user click on "One", it'll return back to it's original state. But, if user don't remove his/her mouse pointer from that button, that button seemed on green background too. That's for hover color. So, if any user click again and again on a button he/she won't understand that's state is changed or not unless he/she moved his/her pointer.

so, I need(when mouse pointer isn't moving by user): if anyone click on "One" button, it turn's into "Green background". If user click on "One" again, it'll turn to "Grey Background" (for understanding that change user don't have to move his/her mouse pointer). In short hover color should be inactive if user click on a button again and again without moving his/her mouse pointer

Upvotes: 2

Views: 2663

Answers (1)

Venkata Krishna
Venkata Krishna

Reputation: 15112

Use not(this) Documentation

http://jsfiddle.net/3Vbz8/1/

$('.toggle').click(function(){
   $('.toggle').not(this).removeClass("active");
   $(this).toggleClass("active");
});

Edit:

I liked @Roko C.Buljan's touch to the CSS to differentiate hover vs click(in comments)

http://jsfiddle.net/3Vbz8/8

.toggle:hover {
    background: #888;
}

.toggle.active{
    background: green;
}

Upvotes: 7

Related Questions