john
john

Reputation: 834

Cant swap image on click if div is visible

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

Answers (3)

Lumi Lu
Lumi Lu

Reputation: 3305

Working example in **FIDDLE**

Mainly idea is put condition into slideToggle callback function

Javascript

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

cssyphus
cssyphus

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);
});

jsFiddle Demo

Upvotes: 1

Arun P Johny
Arun P Johny

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

Related Questions