Hello!

Tell me, please, using Javascript to make it so that when a mouse hits a certain area, does the callback function work?

JQuery has mouseenter/leave , everything is fine, but it works when movement begins. And if the mouse does not move, it will not work.

For example, I hover the mouse over div block number 1. I pressed the delete button for this block number 1 and block No. 2 took its place — the coordinates of the mouse cursor did not change. The callback function will not work if you use mouseenter/leave , because there was no mouse movement, but if I start a movement, it will work.

The task is to ensure that the callback function works in any case, if the mouse cursor is over a specific div block, whether there is movement or not.

Tell me how this can be implemented?

Thank!

    2 answers 2

    A big function came out ... I thought it would be less :)

     $(function(e) { var func = function(event) { var elem = 'div', p = {left: $(elem).offset().left, top: $(elem).offset().top, right: $(elem).offset().left + $(elem).outerWidth(), bottom: $(elem).offset().top + $(elem).outerHeight()}; if(event.clientX >= p.left && event.clientX <= p.right && event.clientY >= p.top && event.clientY <= p.bottom){ $(elem).html(1); }else{ $(elem).html(0); }; }; $(window).mousemove(function(event) { func(event); e = event; }); setInterval(function() { func(e); }, 300); //Для проверки: $(document).on('click', 'div.num1', function() { $(this).remove(); $('body').append('<div class="num2">0</div>'); }); $(document).on('click', 'div.num2', function() { $(this).remove(); $('body').append('<div class="num1">0</div>'); }); }); 
     div {width:200px;height:200px;} .num1 {background-color: red} .num2 {background-color: green} 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="num1">0</div> 

    • thanks for the answer! And what if there is not one picture on the page, but, for example, 20? Is this function resource intensive? - Pavel
    • @Pavel, in theory, no. But I would redo it a bit and make it easier to use - Yuri

    In jQuery, this can be done with .hover () For example:

     $("#myelement").hover(function(e){ console.debug("works!"); //Ваш код }); 

    https://api.jquery.com/hover/

    • the function is triggered at the moment the mouse cursor coordinates are changed. And if the coordinates do not change, it does not work. - Pavel