Search code examples
javascriptjquerycssmouseentermouseleave

jQuery Trigger mouseenter on a element without actually real mouse entering element


I have a web page with elements that when mouse hover over element, text appears inside the element. I want to generate the "Mouse hover"/"mouseenter" to show the text even without the mouse actually hover over the element. Code for example:

HTML

<div> 
    <span id="hover_to_show_text">Hover here to show hidden text</span>
    <span id="hidden_text" style="display:none">Hidden text</span>
</div>    

JS

$( "#hover_to_show_text" ).mouseenter(function() {
   $( #hidden_text ).show();
});
 $( "#hover_to_show_text" ).mouseleave(function() {
   $( #hidden_text ).hide();
});

I want to generate the "mouseenter" that's triggers the "$( "#hover_to_show_text" ).mouseenter(function() {" in jQuery, and leave to "mouseenter" there for a N seconds.

I tried (separately):

$("#hover_to_show_text").hover();
$("#hover_to_show_text").trigger('mouseover');
$("#hover_to_show_text").trigger('mouseenter');

Didn't work. Is there a way to do it?

Thanks.


Solution

  • Should work. The events are triggered almost immediately. So you might not have seen the difference.

    Encase the tiggering of mouseleave inside a setTimeout to see the difference.

    $( "#hover_to_show_text" ).mouseenter(function() {
       $('#hidden_text').show();
    });
     $( "#hover_to_show_text" ).mouseleave(function() {
       $('#hidden_text').hide();
    });
    
    $("#hover_to_show_text").trigger('mouseover');
    
    setTimeout(function() {
        $("#hover_to_show_text").trigger('mouseleave');
    }, 1500);
    

    Check Fiddle

    Update

    // Just triggering the click event will not work if no
    // click handler is provided.
    // So create one first
    $("#btn").on('click', function () {
    
        // trigger the mouse enter event 
        $("#hover_to_show_text").trigger('mouseenter');
    
        setTimeout(function () {
            $("#hover_to_show_text").trigger('mouseleave');
        }, 1500);
    
    });
    

    Update Fiddle