Brian
Brian

Reputation: 2829

Intercept display change on hover?

I have some elements that, upon hover, toggle the display (none/block) of a child ul. Unfortunately, I can't transition a fade via CSS with display. Using opacity won't work either since the hover area expands onto the opacity: 0 ul, and a combo of both (transition opacity, but still toggle display) doesn't seem to work.

Is there a way to intercept the display change via Javascript, and have it fade between block and none? Are there alternate suggestions (I tried a height: 0/auto toggle too, didn't work right)? I'd prefer an intercept method than a pure JS method, in case JS is disabled or something.

Upvotes: 1

Views: 579

Answers (1)

fncomp
fncomp

Reputation: 6198

If I understand you correctly. Assuming something like: <div class="nav-container"><ul></ul></div>.

You can listen for hover on the parent, since it contains the child:

var parent      = document.getElementsByClassName('nav-container')[0];
var connect     = function (element, event, callback) {/* I think you */};
var disconnect  = function (handle) {                  /* can find */};
var addClass = function (element, className) {      /* these elsewhere. */};
var removeClass = function (element, className) {      /* ... */};
var hoverHandle = connect(parent, 'hover', function (event) {
    addClass(parent, 'hovered');
    if (blurHandle) {
        disconnect(blurHandle);
    }
});
var blurHandle = = connect(parent, 'blur', function (event) {
    removeClass(parent, 'hovered');
    if (hoverHandle) {
        disconnect(hoverHandle);
    }
});  

Then in the CSS:

.nav-container > ul {
    display: none;
    /* do fade out */
} 
.nav-container.hovered > ul {
    display: block;
    /* do fade in */
}

If you're using jQuery 1.7, then this'll become:

var navContainers = $('.nav-container');
navContainers.on('hover', function () {
     $(this).toggleClass('hovered');
});
navContainers.on('blur', function () {
    $(this).toggleClass('hovered');
});

Upvotes: 1

Related Questions