Gene M Gene M - 6 months ago 27
Javascript Question

Remove button class on parent div hover

I have several divs on a page with the same class that contain some buttons that are disabled by default. The goal is to highlight one of the divs on hover and to remove the 'disabled' class from the button.

I have been able to do it on ALL of the divs, but can't seem to get it working for only the element being hovered over. Tried $(this).find without luck.

<div class="large-12 columns">
<div class="box">
<button class="button disabled expanded">Button</button>
</div>
</div>

<div class="large-12 columns">
<div class="box">
<button class="button disabled expanded">Button</button>
</div>
</div>


Script:

$('.box').hover(
function() {
$('.box .button').removeClass('disabled');
},
function() {
$('.box .button').addClass('disabled');
}
);


Here I have it working on both elements but want to hover / remove disable class on individual box: FIDDLE

Answer

Use this to refer the hovered element and get element based on the context.

$('.box').hover(
  function() {
    $('.button', this).removeClass('disabled');
  },
  function() {
    $('.button', this).addClass('disabled');
  }
);


$('.box').hover(
      function() {
        $('.button', this).removeClass('disabled');
      },
      function() {
        $('.button', this).addClass('disabled');
      }
    );
.box {
    margin: 0 0 1rem 0;
    padding: 1rem;
    border-radius: 0;
    position: relative; 
    overflow: hidden;
    border:1px solid #EFEFF4;
    font-size: 0.9rem;
    line-height: 1.3rem;
}

.box:hover {
    border-color:#59c07b;
    -webkit-transition: all 250ms ease;
    -moz-transition: all 250ms ease;
    -ms-transition: all 250ms ease;
    -o-transition: all 250ms ease;
    transition: all 250ms ease;

}
.disabled{background:white}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="large-12 columns">
      <div class="box">
            <button class="button disabled expanded">Button</button>
      </div>
    </div>

    <div class="large-12 columns">
      <div class="box">
            <button class="button disabled expanded">Button</button>
      </div>
    </div>