lejimmie
lejimmie

Reputation: 388

Adding only a single instance of a class

I'm trying to add a class to an element using jQuery. If the user clicks on an element it adds a class, which I can do, but I want only 1 instance of that class to be active so if the user clicks on something else that class is then removed from the previous element and added to the current one.

https://jsfiddle.net/gsuxjce2/3/

<div class="row">
  <div class="col">
    <div class="box">

    </div>
  </div>
  <div class="col">
    <div class="box">

    </div>
  </div>
  <div class="col">
    <div class="box">

    </div>
  </div>
  <div class="col">
    <div class="box">

    </div>
  </div>
</div>

.col {
  width: 25%;
  float: left;
}

.box {
  width: 50px;
  height: 50px;
  background-color: red;
  cursor: pointer;
}

.added {
  background-color: blue;
}

 $('.box').click(function() {
        $(this).toggleClass('added');

    if ( $(this).hasClass('added'); ) {
                    $(this).removeClass('added');
    } else {
            $(this).toggleClass('added');
    }

 });

Upvotes: 0

Views: 101

Answers (3)

Emil S. J&#248;rgensen
Emil S. J&#248;rgensen

Reputation: 6366

Just add this to the start of you click event:

jQuery(".added").each(function(i,el){
    jQuery(el).removeClass("added")
});

This removes all instances of the class, so that when you add one new, then that will be unique.

Upvotes: 1

j08691
j08691

Reputation: 208032

Remove the .added class from all .box elements first, then just add it to the one clicked on with this:

 $('.box').click(function() {
     $('.box').removeClass('added');
     $(this).addClass('added');
 });

 $('.box').click(function() {
   $('.box').removeClass('added');
   $(this).addClass('added');
 });
.col {
  width: 25%;
  float: left;
}
.box {
  width: 50px;
  height: 50px;
  background-color: red;
  cursor: pointer;
}
.added {
  background-color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="row">
  <div class="col">
    <div class="box">

    </div>
  </div>
  <div class="col">
    <div class="box">

    </div>
  </div>
  <div class="col">
    <div class="box">

    </div>
  </div>
  <div class="col">
    <div class="box">

    </div>
  </div>
</div>

Upvotes: 3

Rodrigo Gra&#231;a
Rodrigo Gra&#231;a

Reputation: 2175

$('.added').removeClass('added');

inside your click event before everything.

Upvotes: 2

Related Questions