hellomello
hellomello

Reputation: 8597

jquery toggle class between divs

If I have two div elements where users are to choose between two options.

I'd like to show that the user has clicked on it, so by that when user clicks on an element, the class adds some styling.

Right now I only have the basics down. The user can only choose one of the two elements. So if user already clicks on one element, there's styling. If user decides to click on the other element, the previous click is removed, and then it adds the style on the new click.

  $(".ind").on("click", ->
    $(this).toggleClass("selected")
  );

Hopefully someone can guide me, Thanks!

Upvotes: 0

Views: 4574

Answers (4)

user3156287
user3156287

Reputation: 11

Needed this for a project, and discovered that if you click the already selected item, it just removes the class all together.

So added this, hope someone can use it.

$(".view-type .type").click(function () {
        if (!$(this).hasClass("checked")) {
            $(this).addClass("checked").siblings(".type").removeClass("checked");
        }
    });

Upvotes: 1

valerio0999
valerio0999

Reputation: 12138

here's my example http://jsfiddle.net/omegaiori/wbcTr/

$(".ind").click (function() {
    $(this).toggleClass('selected').siblings().removeClass('selected');
});

Upvotes: 1

Mithun Satheesh
Mithun Satheesh

Reputation: 27845

$(".ind").on "click", ->
    $(this).siblings(".ind").removeClass("selected")
    $(this).toggleClass("selected")

Upvotes: 2

Eli
Eli

Reputation: 14827

Give both div a same class:

<div class="ind targetDiv">This is div 1</div>

<div class="targetDiv">This is div 2</div>

Then you can use jQuery:

$(".targetDiv").on("click", function() {
    $(this).toggleClass('selected').siblings().removeClass('selected');
});

Demo

Upvotes: 5

Related Questions