Somename Somename - 3 months ago 12
jQuery Question

How to use toggle to shorten my code?

html is:

<div class="top-buffer myclass glyphicon glyphicon-grain"></div>


jQuery is :

$(".myclass").on("mouseover", function(){
$(this).removeClass("glyphicon-grain").addClass("glyphicon-qrcode");
});
$(".myclass").on("mouseout", function(){
$(this).removeClass("glyphicon-qrcode").addClass("glyphicon-grain");
});


The above works fine. How can I use toggle and make the code shorter?

Thanks.

Answer

Try with this snippet.

$("body").on("mouseover mouseout", 'div.myclass', function(){
    $(this).toggleClass("glyphicon-grain glyphicon-qrcode");
});
.glyphicon-grain
{
  color: green;
}
.glyphicon-qrcode
{
  color: blue;  
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="top-buffer myclass glyphicon glyphicon-grain">Div with toggle class</div>

Comments