Check variable true with if statement

if-statement, javascript, jquery, jquery-plugins

Solution

At the point where you do the if test:

if(flag==true)

...`flag` will always be false, because you set it to `false` just before that. The only place it gets set to `true` is inside the `mouseenter` handler that you bind there but that handler function doesn't get called at that point.

Let me add some comments to the beginning of your code to try to make that clearer:

$(val1).mouseleave(function () {
    flag = false;                                  // set flag to false
    $(val3 + "," + val4).mouseenter(function () {  // bind a mouseenter
        flag = true;                               // that won't be called immediately
        //alert(flag);                             // so won't change flag yet
    });
    if (flag == true) {                            // flag is still false

It doesn't make sense to bind a `mouseenter` handler from inside the `mouseleave` handler, because that means every time the mouseleave occurs you bind an additional `mouseenter` handler to the same elements.

I can't really suggest a specific solution because you haven't explained what effect you are trying to achieve. (But I'd probably start by moving that `mouseenter` code somewhere else.)

Problem

Here is my code: ``` $(val1).mouseleave(function () { flag = false; $(val3 + "," + val4).mouseenter(function () { flag = true; //alert(flag); }); if (flag == true) { //alert("if"+flag); $(".big" + i + j + "boxer").show(); $(".big" + i + "box").show(); $(".big" + i + "box").append('<div class="opacity" style="background-color:rgba(00,00,00,0.77);position:absolute;top:0;right:0;left:0;bottom:0;"></div>') $(".small" + i + "box").append('<div class="opacity" style="background-color:rgba(00,00,00,0.77);position:absolute;top:0;right:0;left:0;bottom:0;"></div>') } else { //alert("else"+flag); $('.opacity').remove(); $(val2).hide(); $(val3).show(); } }); ``` It's not meeting `flag = true` condition. If I `alert` within `$(val1).mouseleave(function(){});`, it shows that `flag = true`; but when I alert it outside of `$(val1).mouseleave(function(){});`, it shows `flag = false`. Well, let me explain: I have 4 blocks `val1,val2,val3` and `val4`. When the users leave `val1` and enter the `val3` or `val4` block, I want to `set/add opacity class` ... if they `do not enter` into `val3/val4` but go into `val2 or another block` block then I want to remove opacity class.

Original source