Reputation: 163
I can't get the attr function to change the class and keep it until the next click. It also won't use the new mouseenter and mouseout functions. Any ideas what I am doing wrong?
<a href="" id="play" class="pause"><div id="playctrl"><img id="pausectrl" class="play" src="images/play1.png" ></div></a>
$('.pause').click(function(){
$('#pausectrl').attr({
src: 'images/pause1.png',
class: 'paused'
});
return false;
});
$('.play').mouseenter(function(){
$(this).attr('src','images/play2.png');
}).mouseout(function(){
$(this).attr('src','images/play1.png');
});
$('.paused').mouseenter(function(){
$(this).attr('src','images/pause2.png');
}).mouseout(function(){
$(this).attr('src','images/pause1.png');
});
Here is a link to a sample of the page. MMA Slideshow controls sample
Upvotes: 2
Views: 472
Reputation: 1752
You're setting the src on the wrong tag, use the following code instead:
$("img.play", $(this)).attr('src', 'thenewimage.png');
The part '$(this)' is the start position where jQuery is trying to find a image with the class 'play'. This is in my opinion a efficient solution..
the complete js code:
$('.play').mouseenter(function(){
$("img.play", $(this)).attr('src','images/play2.png');
}).mouseout(function(){
$("img.play", $(this)).attr('src','images/play1.png');
});
The HTML stays the same..
$('.paused').mouseenter(function(){
$("img.play", $(this)).attr('src','images/pause2.png');
}).mouseout(function(){
$("img.play", $(this)).attr('src','images/pause1.png');
});
`
Upvotes: 1
Reputation: 17703
For the second part:
$('.paused').mouseenter(function(){
$(this).attr('src','images/pause2.png');
}).mouseout(function(){
$(this).attr('src','images/pause1.png');
});
You would be better off setting a class name with jQuery and using CSS and image sprites for the image replacement.
Something like:
.paused {background: url(/images/paused.png) 0 0 no-repeat;}
.paused:hover {background-position: 0 15px;} /* Or whatever the position in the sprite */
Upvotes: 1
Reputation: 6032
When you say:
It also won't use the new mouseenter and mouseout functions
I am guessing that it is because when your code runs, your objects don't have the class yet so they aren't bound to the eventhandlers. You could use the live function to bind your event correctly.
$('.pause').click(function(){
$('#pausectrl').attr({
src: 'images/pause1.png',
class: 'paused'
});
return false;
});
$('.play').live("mouseenter", function() {
$(this).attr('src','images/play2.png');
});
$('.play').live("mouseout", function(){
$(this).attr('src','images/play1.png');
});
$('.paused').live("mousenter", function() {
$(this).attr('src','images/pause2.png');
});
$('.paused').live("mouseout", function(){
$(this).attr('src','images/pause1.png');
});
Upvotes: 2
Reputation: 3234
You're setting src
on the link. You want to do this instead:
$(this).find('img').attr('src', 'myimage.png');
Upvotes: 4