Jordan
Jordan

Reputation: 23

Force element state hover in function of another hovered element / jQuery

I saw many things about the state hover and jQuery but nothing about my issue. I want to force a class to become :hover when another class is :hover. Difficult to explain so here my code:

$(document).mousemove(function() {    
if($('.h').is(':hover')){ 
    $('.h .btn-1e').trigger('mousover');
}
});

The fact is that second class hover is a bit complicated and I can't make it by addClass / removeClass (the hover include :after things, animations etc ..)

Thanks for the help and sorry about my english!

Upvotes: 2

Views: 2742

Answers (2)

Sim
Sim

Reputation: 3317

I would do it in that way:

Define your own new hover class (i know you wrote, that you hover css is complicated but of course you can replace your hover with a hover class, here you can also add :after ...):

.class1,
.class2 {
    width: 40px;
    height: 40px;
    margin: 30px;
    background-color: gray;
}
/* your element has an additional hover class */
.class1.hover,
.class2.hover {
    background-color: red;
}

Now set this hover class in this hover event function with jquery:

$(".class1, .class2").hover(function() {
    //mouseenter
    $(this).addClass("hover");
}, function(){
    //mouseleave
    $(this).removeClass("hover");
});

And now you can say, that all class2 elements should become the hover state (that is your hover class) when the mouse hovers a class1 element:

$(".class1").mouseenter(function() {
    //on hover class1 force hover state to class2
    $(".class2").mouseenter();
}).mouseleave(function() {
    //remove it on mouseleave
    $(".class2").mouseleave();
});

I've made you a jsfiddle to play with: https://jsfiddle.net/0txLn21c/1/

For more information you can read the API:

https://api.jquery.com/hover/

https://api.jquery.com/mouseover/

I hope, this could help you and i don't know your code, but i think it isn't impossible to use a hover class in your case. For example you can give your hover class an :after element or an animation to:

.class1.hover:after {
    /* content, animations ... */
}

Upvotes: 1

BadHorsie
BadHorsie

Reputation: 14544

I usually trigger events like this:

$(document).mousemove(function() {    
    if($('.h').is(':hover')){ 
        $('.h .btn-1e').mouseover();
    }
});

Have you tried that?

Upvotes: 0

Related Questions