Reputation: 834
Im trying to swap the image if #filters is visible, but its not working, no errors in console...
$(document).ready(function(){
$("#filter-options :checkbox").click(function(){
$("#product-list li").hide();
$("#filter-options :checkbox:checked").each(function(){
$("." + $(this).val()).fadeIn();
});
if($('#filter-options :checkbox').filter(':checked').length < 1){
$("#product-list li").fadeIn();
}
});
$('.col').on('click', function(){
$('#filters').slideToggle(200);
if($('#filters').is(':visible')){
$('.col').attr('src','http://www.asus.com/media/images/close_round.png');
}
else{
$('.col').attr('src','http://www.asus.com/media/images/open_round.png');
}
})
});
http://jsfiddle.net/594yj9uL/9/
Upvotes: 1
Views: 60
Reputation: 3305
Working example in **FIDDLE**
Mainly idea is put condition into slideToggle callback function
if($('#filter-options :checkbox').filter(':checked').length < 1){
$("#product-list li").fadeIn();
}
$('.col').on('click', function(){
var self = $(this);
$('#filters').slideToggle(200, function(){
if($('#filters').is(':visible')){
self.attr('src','http://www.asus.com/media/images/close_round.png');
} else {
self.attr('src','http://www.asus.com/media/images/open_round.png');
}
});
});
Upvotes: 1
Reputation: 40038
The problem is this line:
$('#filters').slideToggle(200);
Because it takes 200ms for the element to be hidden, the remaining code executes and finds the element still visible.
If you wrap the next bit in a setTimeout
, you will solve the problem.
$('.col').on('click', function(){
$('#filters').slideToggle(200);
setTimeout(function(){
alert( $('#filters').is(':visible') );
if($('#filters').is(':visible')){
$('.col').attr('src','http://www.asus.com/media/images/close_round.png');
}else{
$('.col').attr('src','http://www.asus.com/media/images/open_round.png');
}
},500);
});
Upvotes: 1
Reputation: 388316
It is because of the slideToggle(), in case of slideToggle()
, you need to check the visibility and the end of the animation using the complete callback option
$('.col').on('click', function () {
$('#filters').slideToggle(200, function(){
console.log($(this).is(':visible'))
if ($(this).is(':visible')) {
$('.col').attr('src', 'http://www.asus.com/media/images/close_round.png');
} else {
$('.col').attr('src', 'http://www.asus.com/media/images/open_round.png');
}
});
})
Demo: Fiddle
Upvotes: 2