Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS: How to fake a :hover state?

Tags:

jquery

css

enter image description here

Here, I have several divs. When mouse hover them, there would be a transition effect. (like the left-inner corner)

I want to fake a hover at first. For example, make the left-outer corner div in :hover state at first, without user's actual hover action. And then, when user really hovers over other divs, the fake hover state cancelled.

For HTML & CSS:

    <div class="story" id="target">
      <!--content-->
    </div>
    <div class="story">
      <!--content-->
    </div>
    <div class="story">
      <!--content-->
    </div> 

.story{
  background: none repeat scroll 0 0 #2A2A2A;
  &:hover{
    transition: all 0.25s ease-in-out 0s;
    background: none repeat scroll 0 0 lighten(#2A2A2A, 20%);
  }
}

What I want to do:

At start, the div#target is forced into :hover state(So it has a different background). Later, when the user starts to use his mouse and hover to other divs, other divs changes into :hover state, and the div#target go back to normal state.

It's pretty much like a autofocus when we using input field

UPDATES: I want to trigger hover state of an element as soon as someone enters this page.

jQuery: Automatically trigger hover

like image 416
cqcn1991 Avatar asked Dec 25 '13 14:12

cqcn1991


1 Answers

You can add a class declaration to your :hover CSS rule like this:

.story:hover,
.story.hover {
    transition: all 0.25s ease-in-out 0s;
    background: none repeat scroll 0 0 lighten(#2A2A2A, 20%);
}

And now you can use JS to add classes to the .story elements to mimic the hover effect:

$(document).on("ready", function () {
    $(".story").eq(0).addClass('hover');
});

This will add the hover effect to the first .story element on document-ready.

Here is a demo: http://jsfiddle.net/fKupb/

I suggest using this method because it plays nice with CSS. If you have an event handler setup for mouseenter and mouseleave then you can use JS to trigger those event handlers using jQuery's .trigger() function: $(".story").eq(0).trigger('mouseenter');

like image 116
Jasper Avatar answered Oct 02 '22 21:10

Jasper