JasonDavis
JasonDavis

Reputation: 48933

Change a CSS selectors child on hover in jQuery

With this basic jQuery code below, how would I make the on mousout change the item back to display:none?

Also can this be improved?

Any help please

$(".image").hover(function() {
      $(this).children(".image p").css({ display: 'inline' });
});

On the jQuery docs site I saw this: $(selector).hover(handlerIn, handlerOut) but I don't understand how to apply it here.

Upvotes: 1

Views: 329

Answers (4)

shredder
shredder

Reputation: 401

You don't need 2 functions if you test the event:

$(".image").hover(function(e) {
      $(this).children("p").toggle(e.type === 'mouseenter');
});

Here's a demo: http://jsfiddle.net/U5QGU/

I also simplified the selector because you don't need:

.image p

Because you already know that its parent has .image

You could also do this instead of toggle:

$(".image").hover(function(e) {
      $(this).children("p")[e.type === 'mouseenter' ? 'show' : 'hide']();
});

http://jsfiddle.net/U5QGU/1/

Upvotes: 2

mikepurvis
mikepurvis

Reputation: 1628

An alternative to using children is to provide selector context:

$(".image").hover(function() {
    $("p", this).css({ display:'visible' });
}, function() {
    $("p", this).css({ display:'none' });
});

To use a single function as suggested by shredder:

$(".image").hover(function(e) {
    var d = (e.type === 'mouseenter') ? 'visible' : 'none';
    $("p", this).css({ display: d });
});

Upvotes: 1

James Billings
James Billings

Reputation: 448

ThiefMaster is correct also but this is exactly as you asked for it:

$(".image").hover(function() {
      $(this).children(".image p").css({display:'inline'});
}, function() {
      $(this).children(".image p").css({display:'none'});
});

Upvotes: 1

ThiefMaster
ThiefMaster

Reputation: 318488

$(".image").hover(function() {
      $(this).children(".image p").show();
}, function() {
      $(this).children(".image p").hide();
});

But why not use pure CSS for it?

.image:hover .image p { display:inline; }

Upvotes: 4

Related Questions