Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS :hover - How to get lower DIVs to :hover as well?

Tags:

jquery

css

Here is an example. I'm looking to get the row and the column the cursor is over to display the :hover attributes. Is there a way to do this without requiring javascript? If not is there a simple way in jQuery to do this for any number of rows/cols?

like image 421
Justin808 Avatar asked Jan 30 '26 05:01

Justin808


2 Answers

Not with css, as with css only one element is hovered (from overlapping non-nested elements).

jQuery can help but it is not trivial..

A crude implementation would be to

  • add .row and .col classes to the elements (as appropriate)
  • bind a custom event to those, whose handler check to see if the mouse coords are inside their box and set/unset the hover state
  • while the mouse moves inside the container of the rows and cols (you should wrap them in one), create an event (of the custom type we bound to the rows and cols) and fire it globally

html

<div id="container">
    <div id="row1" class="row"></div>
    <div id="row2" class="row"></div>
    <div id="col1" class="col"></div>
    <div id="col2" class="col"></div>
</div>

javascript

$('.col, .row').bind('intersect',function(e){
    var $me = $(this);
    var pos = $me.offset();
    var size = {w:$me.width(), h:$me.height()};

    if ( e.pageX > pos.left && e.pageY > pos.top && e.pageX < pos.left + size.w && e.pageY < pos.top + size.h )
    {
        $me.addClass('hover');
    }
    else if ($me.is('.hover'))
    {
        $me.removeClass('hover');
    }
});

$('#container').mousemove(function(e){
    var evt = jQuery.Event('intersect');
    evt.pageX = e.pageX;
    evt.pageY = e.pageY;
    $.event.trigger(evt);
});

demo: http://jsfiddle.net/gaby/7V8AN/

like image 70
Gabriele Petrioli Avatar answered Jan 31 '26 19:01

Gabriele Petrioli


If you're using a table, you can normally just do something like this:

tr:hover > td {
    background-color: yellow;
}

…but if you have elements that aren't nested, only one of them will be considered :hovered. You'd have to use JavaScript to propagate the hover state to other elements that are positioned underneath.

like image 40
bradley.ayers Avatar answered Jan 31 '26 17:01

bradley.ayers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!