funkyc123
funkyc123

Reputation: 13

Toggle won't stay open

I have images (.rv_button) that are acting as buttons to toggle the div's below (#reveal). I want to hover over the button to open the div but right now I can't get the div to stay open. Can someone help me with this?

jQuery(document).ready(function() {
  // Hide the div
  jQuery('#reveal').hide();
  jQuery('.rv_button').on('mouseenter mouseleave', function(e) {
    e.preventDefault();
    jQuery("#reveal").fadeToggle()(slow, swing, callback);
    jQuery('.rv_button').toggleClass('open');
  });
});

Upvotes: 1

Views: 300

Answers (1)

thingEvery
thingEvery

Reputation: 3434

Rather than using toggleClass(), on mousenter, remove the open class from all of the buttons and add it to e.target or $(this). And on mouseout just remove it from all the buttons.

Also, remove (slow, swing, callback) or use them as arguments in fadeToggle().

e.g.

jQuery("#reveal").fadeToggle('slow');

And to keep the div to stay open, just wrap the buttons and div in a container and listen for the mouseout event on it instead of the buttons themselves.

$(document).ready(function() {
  // Hide the div
  $('#reveal').hide();
  $('.rv_button').on('mouseenter', function(e) {
    e.preventDefault();
    $('.rv_button').removeClass('open');
    $(e.target).addClass('open');
    $("#reveal").fadeIn();
  });
  $('.container').on('mouseleave', function(e) {
    e.preventDefault();
    $('.rv_button').removeClass('open');
    $("#reveal").fadeOut();
  });
});
.container {
  width: 400px;
}

#reveal {
  width: 400px;
  height: 400px;
  background-color: beige;
  text-align: center;
  font-size: 2em;
}

.rv_button {
  padding: 1em;
  background-color: brown;
  width: 400px;
  box-sizing: border-box;
}

.open {
  background-color: orange;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="container">
  <div class="rv_button">Button 1</div>
  <div class="rv_button">Button 2</div>
  <div class="rv_button">Button 3</div>
  <div id="reveal">Reveal</div>
</div>

Upvotes: 1

Related Questions