views:

170

answers:

5

I just saw a demo that had this jquery code to show and hide a dive on hover, can't this be done with just regualr css though? And if you can do it with css is there any advantage of doing it with javascript?

$('.comment').hover(function() {
  $(this).children('.delete').show();
}, function() {
  $(this).children('.delete').hide();
});
+6  A: 

You can do this with CSS but IE6 only supports the :hover pseudo-class on anchor tags (A), so it's not as common.

nullptr
True, but the :hover may be able to be used on the `a` tag in this situation, but we don't know at this point because the asker did not include any markup.
Josh Stodola
+12  A: 

CSS hover works fine with anchor tags, but IE6 does not recognize hover events on things like li tags.

If you were using an anchor tag, however, you could achieve the same effect in CSS:

a.comment       .delete { display: none; }
a.comment:hover .delete { display: block; }
Jody
+1 Nice first answer :) I edited it and changed to IE6 because 7 and 8 do support `:hover` on elements other than `a`
Josh Stodola
...and yesterday a comment was directing a question like this to doctype.com!
Here Be Wolves
A: 

Jody is correct. Check out the docs for the CSS Display property.

JohnE
A: 

There is more functionality that the .hover will do. If you provide it more than 2 functions it will cycle through all the functions. Example

$('.comment').hover(
    function(){$(this).children('.delete.first').show()},
    function(){$(this).children('.delete.first').hide()},
    function(){$(this).children('.delete.second').show()},
    function(){$(this).children('.delete.second').hide()}
    );

That would show one set of children the first time they hover, then hide, and the next time show a different set of children.

The hover function also works over multiple elements, and only fires if the mouse has left all the elements (not just when it leaves one and moves to another)

Lathan
A: 

I dynamically create something like this on the server side. I'm sure there is a more efficient/prettier way but this usually serves my needs. Basically hides all the divs and un-hides the one that needs to be shown (passed as arg in function from onClick event).

function toggleTab(id)
{
    document.getElementById('divEnrollment').style.display='none';    
    document.getElementById('divSearch').style.display='none';
    document.getElementById('divMeeting').style.display='none';
    document.getElementById('divBenefit').style.display='none';
    document.getElementById('div' + id).style.display='block';

    document.getElementById('spnEnrollment').style.color='blue';    
    document.getElementById('spnSearch').style.color='blue';
    document.getElementById('spnMeeting').style.color='blue';
    document.getElementById('spnBenefit').style.color='blue';
    document.getElementById('spn'+id).style.color = 'red';
}
J.Hendrix