R. StackUser
R. StackUser

Reputation: 2065

JQuery - trigger hover over separate element

Simple question - how do I make an element appear to be hovered when I trigger it from another element?

Example jsfiddle: http://jsfiddle.net/xpvt214o/391305/

Body:

<span class="itemA"></span>
<button>
TriggerAHover
</button>

Js:

   $(document).ready(function(){
    $('button').on("click", function(){
      $('.itemA').trigger('mouseover');
    })
    });

Css:

   .itemA {
     display:block;
            background: blue;
            width: 40px;
            height: 40px;
        }

        .itemA:hover {
            background: red;
        }

This fiddle creates a blue background span. On hover, the span changes red.
I want the span to also change to a hovered state on click of the button. I've tried .trigger('mouseover'), .trigger('mouseenter'), and .trigger('hover'), but they do not change the span element to its hovered state.

Upvotes: 2

Views: 206

Answers (2)

David
David

Reputation: 99

Like what Jorgedl said I think it would be better to switch the class.

$(document).ready(function(){
  $('button').click(function() {
     $('.itemA').toggleClass('itemA hovered');
  });
});

CSS:

  .hovered {
        display:block;
        background: red;
        width: 40px;
        height: 40px;
    }

Upvotes: 0

Jorgedl
Jorgedl

Reputation: 157

mouseover or mouseenter will just trigger .on("mouseenter") or .on("mouseover") functions. css hover is only activated by the pointer

Why dont you just add a class on click that has the same style as :hover?

Upvotes: 3

Related Questions