简体   繁体   中英

How to fire hover for anchor tag through jquery?

I have a link. It hover has some background effects.

I want to fire this hover through jquery.

You can fire the javascript hover ( mouseover of mouseenter or mousemove or something, depending on the js lib), but you can't fire the CSS :hover state with Javascript.

You can only use jQuery to fire the event IF jQuery was used to attach the event.

Use JQuery hover() wrapped in document.ready , so that it automatically fires up when a hover happens over the link

$(document).ready(function() {
      $("#YourLinkId").hover(functionToHandleWhenMouseEnters, 
                             functionToHandleWhenMouseLeaves);
});

function functionToHandleWhenMouseEnters() {
     $(this).css({background : red});
}

function functionToHandleWhenMouseLeaves() {
     $(this).css({background: white});
}

Edit:

I am note very sure if this is what you wanted, but as per David's comment, it might not be it. If you want to programatically fire (trigger) a hover, then you should use jQuery trigger()

$("#YourLinkId").trigger("mouseover");

I'm not sure, but I don't believe you can fire the :hover state for a CSS element. I would suggest you handle the hover events for the element and add/remove a special class for your element, for example:

CSS:

#myElement.myClass { }

jQuery:

$("#myElement").hover(
    function(){
        //mouse in
        $(this).addClass("myClass");
    }, function(){
        $(this).removeClass("myClass");
    });
$('#hrefID').trigger('mouseover'); //triggers hover
//your 'hover' code runs....
$('#hrefID').trigger('mouseout'); //removes hover
//your 'mouse out' portion of hover code runs here...

see this link on jQuery Trigger()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM