Reputation: 111
I have a problem with jQuery.
I have the following code which is inside a $(document).ready(function() {...})
$("#one_div").hide();
$('#button').click(function(){
if (this.src == 'img/img1.png'){
this.src = 'img/img2.png';
}
else {
this.src = 'img/img1.png';
}
$("#one_div").slideToggle(800);
});
#button
is the ID of an image. one_div
is the ID of a div.
Actually, clicking on the image toggles the div, but the problem is that the image is swapped only once, from img1
to img2
, and never switched back. What I did I do wrong?
Upvotes: 2
Views: 882
Reputation: 6217
Put the code inside of a $(window).load(function() { ... });
instead to be sure the images are loaded before toggling them.
$(document).ready(function() {
$("#one_div").hide();
});
$(window).load(function() {
$('#button').click(function(){
if ($(this).attr('src') == 'img/img1.png'){
$(this).attr('src', 'img/img2.png');
}
else {
$(this).attr('src', 'img/img1.png');
}
$("#one_div").slideToggle(800);
});
});
Upvotes: 0
Reputation: 555
Try this:
$('#button').click(function(){
var el = document.getElementById('button');
if (el.src == 'img/img1.png'){
el.src = 'img/img2.png';
}
else {
el.src = 'img/img1.png';
}
$("#one_div").slideToggle(800);
});
I think that this has returned a JQUERY object not a DOM object that you can manipulate using .src
Upvotes: 0
Reputation: 190
why don't you toggle the image using a class? Code is untested, but it should become something like this:
$("#one_div").hide();
$('#button').click(function(){
this.toggleClass('active');
if (this.hasClass('active')){
this.src = 'img/img2.png';
} else {
this.src = 'img/img1.png';
}
$("#one_div").slideToggle(800);
});
Upvotes: 0