user13409786
user13409786

Reputation:

JQuery toggle doesn't work on change when I try to set css

I have a toggle button that works only once. This is the portion of script:

$('#toggle').change(function(){

    var mode= $(this).prop('unchecked');

    if(mode = true) {

      $('.container').css('display','block'); 
      $('.container').hide().delay(500).fadeIn(1000); 
      $('#map').css('filter','grayscale(100%)');

    } else {

      $('.container').css('display','none'); 
      $('.container').delay(500).fadeOut(1000); 
      $('#map').css('filter','grayscale(0%)');

    }

});

The first part of If condition is fired, not the Else part. I don't understand why. Some help?

Upvotes: 0

Views: 154

Answers (2)

BlairAllDay
BlairAllDay

Reputation: 1

A couple issues here. @AidOnline01 mentioned the first two.

  1. Property unchecked doesn't exist, use checked instead.
  2. if (mode = true) statement assigns mode a value instead of evaluating equality. Use if (mode == true)
  3. Fade out function doesn't wait for animation to complete before assigning. Use a callback to call $('.container').css('display','none');

I've made a JSFiddle to demonstrate: https://jsfiddle.net/g3y27o5L/4/

Upvotes: 0

AidOnline01
AidOnline01

Reputation: 737

There are two errors in you code. 1) There is no such property as :unchecked, you should use :checked property 2) You have written if(mode = true) not if(mode == true), so you didn't check equality, you assign new value

There is right code:

$('#toggle').change(function(){

var mode= $(this).prop('checked');
console.log(mode);

if(mode == true) {

  $('.container').css('display','block'); 
  $('.container').hide().delay(500).fadeIn(1000); 
  $('#map').css('filter','grayscale(100%)');

} else {

  $('.container').css('display','none'); 
  $('.container').delay(500).fadeOut(1000); 
  $('#map').css('filter','grayscale(0%)');

}

});

Upvotes: 1

Related Questions