Reputation: 739
I have the following jQuery code to add a class to "p" tags within an "li" when you hover over them... but how can i make this more interesting by adding a transition effect rather than just a straight switch?
code:
$(document).ready(function() {
$('li').hover(function() {
$('p', this).toggleClass('hovered');
});
});
Upvotes: 1
Views: 1236
Reputation: 9202
var clone = $("<p>");
$('div').hover(
function() {
clone.remove();
clone = $("p", this).clone();
$("p", this).after(clone);
clone
.hide()
.css({
position: "absolute",
top: $("p", this).offset().top,
left: $("p", this).offset().left,
width: $("p", this).width(),
height: $("p", this).height(),
"z-index": 2
})
.addClass("hovered")
.fadeIn();
},
function() {
clone
.fadeOut("normal", function() {
$(this).remove();
});
}
);
Upvotes: 1
Reputation: 22007
Check the animate function, you can animate the transition between two classes.
Edit: sorry, wrong method. What you're looking for is the switchClass method.
Here's a demo of the switchClass. It's useful if you have two classes, and want to switch from one to the other. If you just want to add/remove a single class, see Wouter J's answer.
Update: It seems you'll need two classes for this to work. Also note that switchClass requires jQuery UI to work. Here's an example:
HTML:
<li>
<p class="regular">Test</p>
</li>
CSS:
p.regular { color:red }
p.hovered { color:blue }
JavaScript:
$(document).ready(function() {
$('li').hover(function() {
$('p', this).switchClass('regular','hovered', 2000);
},function() {
$('p', this).switchClass('hovered','regular', 2000);
});
});
Upvotes: 1
Reputation: 18568
try this, you can even add
more effect
by adding options
in fedeIn
and fadeOut
$(document).ready(function() {
$('li').hover(function() {
$('p', this).fadeIn(function(){
$(this).addClass('hovered');
});
},function(){
$('p', this).fadeOut(function(){
$(this).removeClass('hovered');
});
});
});
Upvotes: 0
Reputation: 41934
You are using jQuery UI, so you can use .toggleClass( class, duration )
, where duration is the duration of the fade:
$(document).ready(function() {
$('li').hover(function() {
$('p', this).toggleClass('hovered', 1000); // 1000ms = 1s
});
});
Upvotes: 1