gabew23 gabew23 - 11 days ago 5
HTML Question

How to toggle classes on a single div?

noob question here: I have the following html code, how to toggle between ".active" and ".inactive" in jquerry for only one placeholder while hovering. for example: If I hover over the first div both of them become active, I want to have ".active" only over the one I'm hovering. I know It's kind of spaghetti code but I'm a little stuck, hope you understood what I wanted to say.

<div class="wrapper">
<div class="inactive">
<div class="col-md-6 col-xs-12 placeholder ">
<a href="http://codepen.io/gabew3/full/YpKGwr/">
<img src="http://i.imgur.com/A92WrwJ.jpg" alt="" class="img-responsive">
</a>
<p class="text-center">A tribute page dedicated to Agatha Christie</p>
</div>
</div>
</div>
<div class="wrapper">
<div class="inactive">
<div class="col-md-6 col-xs-12 placeholder ">
<a href="#">
<img src="http://i.imgur.com/5P1UTjv.jpg" alt="" class="img-responsive">
</a>
<p class="text-center">Placeholder</p>
</div>
</div>
</div>

Answer

You can use jQuery's .hover() method alongwith .toggleClass().

$('.wrapper').hover(function() {
  $(this).toggleClass('active inactive');
});

Note: Please note that one div in your structure is excess. You can have active and inactive classes on div.wrapper.

$('.wrapper').hover(function() {
  $(this).toggleClass('active inactive');
});
.inactive {
  opacity: 0.5
}

.active {
  opacity: 1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<div class="wrapper inactive">
  <div class="col-md-6 col-xs-12 placeholder  ">
    <a href="http://codepen.io/gabew3/full/YpKGwr/">
      <img src="http://i.imgur.com/A92WrwJ.jpg" alt="" class="img-responsive">
    </a>
    <p class="text-center">A tribute page dedicated to Agatha Christie</p>
  </div>
</div>
<div class="wrapper inactive">
  <div class="col-md-6 col-xs-12 placeholder ">
    <a href="#">
      <img src="http://i.imgur.com/5P1UTjv.jpg" alt="" class="img-responsive">
    </a>
    <p class="text-center">Placeholder</p>
  </div>
</div>

Comments