Click here to Skip to main content
15,910,981 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
So far my coding is working only adding the class when mouseenter but never remove the active class when mouseenter other element.

What I have tried:

Check out my coding below :

JavaScript
$(document).ready(function() {
  $("#1, #2, #3").mouseenter(function() {
	$(this).removeClass("active")
	$("#" + this.id).addClass("active");
  });
});

.active {
		background: #fff;
	}


HTML
<pre><ul>
  <li><a class="active" id="1">number 1</a></li>
  <li><a id="2">number 2</a></li>
  <li><a id="3">number 3</a></li>
</ul>


CSS

Posted
Updated 24-Feb-17 7:35am

1 solution

Update the script to remove class form all elements before adding

JavaScript
$(document).ready(function() {

  $("#1, #2, #3").mouseenter(function() {
    $("#1, #2, #3").removeClass();
    $("#" + this.id).addClass("active");
  });
  
});


Here is an example: Edit fiddle - JSFiddle[^]
 
Share this answer
 
v3
Comments
dell-gl62m 24-Feb-17 13:43pm    
Thank you for your reply but this isn't what I need. I wanted to make the class stay active even after mouseleave until mouseenter to other element then only the class active switch. How to do that?
Bryian Tan 24-Feb-17 13:47pm    
Odd :) anyway, then you are close, I think this should do the trick

$("#1, #2, #3").mouseenter(function() {
$("#1, #2, #3").removeClass();
$("#" + this.id).addClass("active");
});
dell-gl62m 24-Feb-17 14:01pm    
Nailed it! It's working. Thank you :D
Bryian Tan 24-Feb-17 14:06pm    
You're welcome. I updated the solution with latest code and a new link to the sample code.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900