w3father
w3father

Reputation: 569

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.

Upvotes: 0

Views: 9213

Answers (4)

Rudie
Rudie

Reputation: 53881

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.

Upvotes: 3

Mahesh Velaga
Mahesh Velaga

Reputation: 21971

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");

Upvotes: 2

BLSully
BLSully

Reputation: 5939

$('#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()

Upvotes: 1

mattsven
mattsven

Reputation: 23303

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");
    });

Upvotes: 1

Related Questions