Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery mouseenter() and mouseleave() not working properly

I have two simple script html:

<html>
<body>
<style>
.myBtn{
    display: none
}
.myBtnReg{
    display: block
}
</style>
<button class="myBtnReg" id="btn1" >Click Me!</button>
<script src="jquery-1.11.2.min.js"></script>
<script src="js.js"></script>
</body>
</html>

and javascript:

$(function(){
    $("button").mouseenter(function(){
        $(this).attr("class", "myBtn");
    });
    $("button").mouseleave(function(){
        $(this).attr("class", "myBtnReg");
    });
});

I'm trying to make an effect where the button changes class when ever the mouse enters and change it back when the mouse leaves, the code above doesn't seem to work properly, when I put my mouse over the button it flickers, so I assume I changes class constantly for some reason.

like image 268
John Smith Avatar asked Jan 21 '26 06:01

John Smith


1 Answers

You can put button inside div and then toggleClass of button when you hover over div (you also need to set fixed height on div)

$('div').hover(function() {
  $(this).find('button').toggleClass('myBtn');
});
div {
  height: 50px;
}
.myBtn {
  display: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <button class="myBtnReg" id="btn1">Click Me!</button>
</div>
like image 174
Nenad Vracar Avatar answered Jan 23 '26 18:01

Nenad Vracar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!