Somename Somename -4 years ago 102
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(){
$(".myclass").on("mouseout", function(){

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


Answer Source

Try with this snippet.

$("body").on("mouseover mouseout", 'div.myclass', function(){
    $(this).toggleClass("glyphicon-grain glyphicon-qrcode");
  color: green;
  color: blue;  
<script src=""></script>
<div class="top-buffer myclass glyphicon glyphicon-grain">Div with toggle class</div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download