aebabis
aebabis

Reputation: 3705

Triggering :hover Repaint on DOM change

I have UI control in a div. The entire div has a hover effect. If the user gets an error, an absolutely positioned div covers the control and asks how to proceed. The control is no longer hovered, but a repaint isn't triggered until the user moves the mouse. Is there a known way to solve this problem? I'm using Chrome

Here's a Fiddle: http://jsfiddle.net/acbabis/L655r/

HTML:

<div class="container">
    <div class="hoverable inner-div">
        <button class="clickme">Click Me</button><br/>
    </div>
</div>

JS:

$(function() {
    $('.clickme').one('click', function() {
        $('.hoverable').append(
            '<br/><div class="touch">Move the mouse here. Hold Still</div>');
    })

    $('.container').on('mouseenter', '.touch', function() {
        setTimeout(function() {
        $('.container').append(
            '<div class="cover inner-div"><br/><br/><br/>Move the mouse now</div>');
        }, 1000);
    });
});

CSS:

.container {
    width: 300px;
    height: 300px;
    margin: 0;
    padding: 0;
    position: relative;
}

.inner-div {
    width: 100%;
    height: 100%;
    padding: 50px 100px;
    text-align: center;
    box-sizing: border-box;
}

.hoverable {
    background-color: blue;
}

.hoverable:hover {
    background-color: green;
}

.cover {
    position: absolute;
    top: 0;
    left: 0;
    background-color: rgba(150, 150, 150, .5);
    padding: 150px 100px 50px 100px;
}

EDIT: I'm aware there are ways to solve this with JS, and I'm willing to use JS; but I'm curious if anyone can show me a CSS/HTML-only way to trigger a repaint. Of course, if I only get JS solutions, I'll accept the best one.

Upvotes: 2

Views: 466

Answers (1)

marionebl
marionebl

Reputation: 3382

The css way

You could add a css rule based on a sibling selector like this:

.cover + .hoverable  {
    background-color: blue;
 }

This assumes you prepend .cover to .container and you probably have to set z-indices on .cover and .hoverable.

Reflected in this fiddle: http://jsfiddle.net/L655r/8/

The js way

You could generally force a repaint on your .hoverable or the .clickme with this simple

jQuery plugin:

$(function() {
    $.fn.redraw = function() {
        var $this = $(this);
        $this.hide();

        setTimeout(function(){
            $this.show();
        },0);

        return $this;
    };
});

Usage:

$('.hoverable').redraw();

Fiddle:

http://jsfiddle.net/marionebl/L655r/5/

Upvotes: 1

Related Questions