If the cursor is over the .blue_block , then .red_block applies .active , if the cursor is away from .blue_block , then .active is deleted.

And everything seems to be working:

  1. Move your mouse over the blue block, the red turns green;
  2. Move the cursor away from the blue block and return red.

But the problem is that only when absent outside the blocks does the hover event work; move the cursor over the green block and the event does not work, if beyond it, it will work.

https://jsfiddle.net/3ya48b8q/1/

 var blue_block_h = 0; $('.blue_block').hover(function() { blue_block_h = 1; }, function() { blue_block_h = 0; }); $('body').hover(function() { if(!blue_block_h) { $('.red_block').removeClass('active'); } else { $('.red_block').addClass('active'); } }); 
 body { width: 350px; margin: 0 auto } .blue_block { background: blue; padding: 25px } .red_block { width: 100%; height: 200px; background: red } .red_block.active { background: green !important } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <html> <head></head> <body> <div class="blue_block">test</div> <div class="red_block"></div> </body> </html> 

What is the problem? To prescribe all the elements like this is not an option, there may be a lot of them:

 $('body, .red_block').hover(function() { ... }); 
  • one
    The event does not work when you take away from the blocks, but when you point at the body, it is very strange that you use the hover body. Why not enter all actions in hover blue? or if you need to make a dropdown then wrap everything in one block and without js - Artem Gorlachev

1 answer 1

Replace with this code (change body to blue_block ) - everything works

 var blue_block_h = 0; $('.blue_block').hover(function() { blue_block_h = 1; }, function() { blue_block_h = 0; }); $('.blue_block').hover(function() { if(!blue_block_h) { $('.red_block').removeClass('active'); } else { $('.red_block').addClass('active'); } });