Question

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/

Was it helpful?

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

OTHER TIPS

First: Unless you need to support IE7 and earier, this is a case where you really should just use :hover in your CSS:

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

.frame .test {
    opacity: 0;
}

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

But if you want to do it in JavaScript, the problem with the code is that you're using $el for the element in one place, but el in other places. You need to be consistent. You should have been seeing errors in the JavaScript console. You also don't need the mEnt variable, nor do you need to use == true when testing conditions.

So:

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

The variable is $el but the removeClass method is being called on 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');
    }
});

JS Fiddle: http://jsfiddle.net/EmE7p/3/

Use this:

$(".frame").hover(
  function () {
    //here mouse enter
  },
  function () {
    //here mouse leave
  }
);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top