Thursday, 27 February 2014

Elements appear when mouse hovers above them - CSS and jQuery

I'm going to share that with you, because it took me surprisingly long time to figure out.

I wanted to have an element, that shows up only, when mouse moves over the element. Just like this:
My first idea was to use "hide()" and "show()" methods on elements themselves. Unfortunately, when elements were hidden, they had no size (or actually size was 0), so you could not hover over them to show them.

Second idea, was to use CSS, and change visibility in ":hover" style. That worked partially - the <div> element had <i> child. Only child would be visible (after all, it's cascading style sheets, it does not go up).

My final idea, was to contain my elements in larger <div> element. The DIV has fixed size and position, and display: block. Child elements are initially hidden. Then I bind "hover()" event to the parent div, that finds children, and displays them. And then hides, when mouse leaves.

So, this is the markup:
<div class="show">
    <div class="mouseover"><i class="fa fa-something"></i></div>
    <div class="mouseover"><i class="fa fa-something-else"></i> </div>
</div>

And this is the script:
$(function(){
    $('.show').hover(
    function() {
        $(this).find('.mouseover').fadeIn();
    },
    function() {
        $(this).find('.mouseover').fadeOut();
    });
});

No comments:

Post a Comment