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

10,840

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

Share:
10,840
BenB
Author by

BenB

Web Developer.

Updated on June 07, 2022

Comments

  • BenB
    BenB about 2 years

    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.

  • Sushanth --
    Sushanth -- almost 9 years
    @batz What do you mean by a third element.
  • BenB
    BenB almost 9 years
    I mean the a otherr button for example will trigger it. Like this: jsfiddle.net/Loof31rq/1
  • Sushanth --
    Sushanth -- almost 9 years
    @batz Check Update comment.