DaveDaBest
DaveDaBest

Reputation: 9

Menu manage hover and click events

I have a menu that I want to add hover and click events to.

$('a').hover(function(){
    $(this).css('background', 'red');
}, function(){
    $(this).css('background', '');
});

$('a').click(function(){
    $(this).css('background', 'green');
});

Here is the demo: https://jsfiddle.net/u2dn68bg/18/

How can I stop my hover event from overriding the click event? i.e. if I have already clicked an element the hover event should not get triggered for that clicked element.

Upvotes: 0

Views: 279

Answers (2)

agrm
agrm

Reputation: 3852

Toggle a CSS class when the element is clicked. When you hover, only change the background if the element do not have that certain class.

$('a').hover(function(){
    !$(this).hasClass('clicked') && $(this).css('background', 'red');
}, function(){
    !$(this).hasClass('clicked') && $(this).css('background', '');
});

$('a').click(function(){
    $(this).css('background', 'green').toggleClass('clicked');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="list-inline menu list-unstyled">
  <li><a href="#">Section 1</a></li>
  <li><a href="#">Section 2</a></li>
  <li><a href="#">Section 3</a></li>
</ul>

Upvotes: 0

epascarello
epascarello

Reputation: 207557

Use CSS rules and toggle a class.

$("a").on("click", function (e) {
  e.preventDefault();
  $(this).toggleClass("active");
})
a.active, a.active:hover {
  background-color: green;
}

a:hover {
  background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="#">One</a>
<a href="#">Two</a>
<a href="#">Three</a>
<a href="#">Four</a>

based on your comment to not use CSS which is a bad design pattern....

$("a").on("click", function (e) {
  e.preventDefault();
  let color = ''
  if (!this.dataset.active) {
    this.dataset.active = 1
    color = 'green'    
  } else {
    delete this.dataset.active
  }
  this.style.backgroundColor = color;
}).on("mouseenter mouseleave", function (e) {
  if (this.dataset.active) return
  const color = e.type === "mouseenter" ? "red" : ""
  this.style.backgroundColor = color;
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="#">One</a>
<a href="#">Two</a>
<a href="#">Three</a>
<a href="#">Four</a>

Upvotes: 1

Related Questions