Search code examples
jquerymouseentermouseoutparagraphbold

jQuery mouseenter on paragraph with bold text


I have a paragraph with a bold text inside

<p style="class1"><b>Some text</b> some other text</p>

and jQuery listeners for the mouseenter and the mouseout events of the class1 elements

$('class1').mouseenter(function(){
    $(this).addClass("highlight");
});

$('class1').mouseout(function(){
    $(this).removeClass("highlight");
});

where the highlight class is a style to simulate the classic HTML selection.

.highlight{
   background-color: blue;
   color: white !important
}

(I didn't used style1:hover cause i want to simulate programmatically also selection with arrows, but this is not really important now)

So, I have some paragraphs like this:

Some text some other text

Some text some other text

Some text some other text

Now, my problem is that when the mouse cursor passes from the bold text to the normal text (or viceversa), mouseout event triggers, loosing my fake selection but staying in the same paragraph. How can I avoid this behavior?


Solution

  • You have to use mouseleave event instead of mouseout..

    $('.class1').mouseenter(function(){
        $(this).addClass("highlight");
    });
    
    $('.class1').mouseleave(function(){
        $(this).removeClass("highlight");
    });
    

    This will solve your problem..:)