Search code examples
jquerytoggleclass

Can I consolidate these two jQuery on() events with a toggle()?


There has got to be a way to do these in one toggleClass():

$('div').on("mouseenter", ".myButton", function(){
        $(this).addClass('rollOver');
    });
$('div').on("mouseleave", ".myButton", function(){
        $(this).removeClass('rollOver');
    }); 

...but it's within an on() because the myButton is created dynamically.


Solution

  •     $('div').on("mouseenter mouseleave", ".myButton", function(){
            $(this).toggleClass('rollOver');
        });