My first question: Moving the mouse over the text inside the element (the text is placed in a separate div) works with a very quick repetition of the mouseenter, and it is necessary that it works only once, when entering the square block without reacting to the child elements. enter image description here

The code was:

$('.square').mouseover(function (e){ var color = colorGenerator(); (this).style.backgroundColor=color; $(this).children('.text').remove(); $('<div>').addClass('text').appendTo(this).text(color); }); 

I was advised to add this:

 $('.square').mouseenter(function (e){ if(!$(e.target).is('.text')){ // тут код, который должен быть выполнен единожды } } 

This solved the first problem, but now the color is determined only once and does not change when re-pointing. How to make the color change, but the condition remains? Why is the code in the body of the condition executed only once?

    1 answer 1

    The events are not 2, but 4. Two of them work on the children, but two do not.

    However, by subscribing to an event, you also subscribe to the ascent of events from nested elements. To process only on a specific element, you need to check event.target .

     $("section").on('mouseenter mouseleave mouseover mouseout', function (event) { if (event.target === event.currentTarget) { console.log(event.type) } }) 
     section, div { padding: 2em; border: 1px solid; } 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <section><div></div></section> 

    And jQuery also has a hover function for a subscription:

     $("section").hover(function (event) { console.log("+") }, function (event) { console.log("-") }) 
     section, div { padding: 2em; border: 1px solid; } 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <section><div></div></section>