Search code examples
jqueryopacityremoveclassmouseenter

jQuery, issue with removeClass


I have the css:

.frame{
    height:200px;
    width:200px;
    border-style:solid;
    border-width:3px;
}

.test2{
    opacity:0;
}

and I have the html

<div class="frame">
<span class="test test2">qwerty</span>
</div>

When the mouse is over .frame I want to remove the class .test2 to .test, and when the mouse is leave.frame I want to add .test2 to .test. So my jQuery code is:

$(document).on('mouseenter mouseleave', '.frame', function( e ) {
    var $el=$(this),
    mEnt  = e.type == "mouseenter";
    if(mEnt == true){
        el.find('.test').removeClass('test2');
    }else{
        el.find('.test').addClass('test2');
    }
});

But it doesn't work, .test2 doesn't want to remove from .test. here a jsfiddle: http://jsfiddle.net/malamine_kebe/EmE7p/


Solution

  • You forgot a $ in el, should be $el

    $(document).on('mouseenter mouseleave', '.frame', function (e) {
        var $el = $(this),
            mEnt = e.type == "mouseenter";
        if (mEnt == true) {
            $el.find('.test').removeClass('test2');
        } else {
            $el.find('.test').addClass('test2');
        }
    });
    

    Demo here

    The best solution for this can be plain CSS (and no jQuery needed), like this:

    .test {
        opacity:0;
    }
    .frame:hover .test {
        opacity:1;
    }
    

    Demo here