0

I'm writing an if/else statement which I've simplified to the fiddle link below. Basically I check for the value of a CSS attribute, and if it's one specific value then I want one thing to happen, and if it's a different value (nonspecific, just any other value), then I want another thing to happen.

$(document).ready(function (){
if($(".header-wrapper").css("height") == "100px"){
    alert("true");
}
else{
    alert("false");
}
$(".below").click(function(){
    $(".header-wrapper").css("height", "200px");
});
});

But for some reason my code checks the CSS value once and doesn't do anything if the CSS value changes, and I want to trigger this event every time the CSS value changes to and from the specific value. Thanks for the help in advance.

https://jsfiddle.net/hyfpw92w/

user47143
  • 65
  • 2
  • 9

3 Answers3

0

You need to put the IF/ELSE in a function. Then call that function when you want it to run on the change in height.

Like so:

function myFunction(){
        if($(".header-wrapper").height() == 100){
            console.log("true");
        } else {
            console.log("false");
        };
    };

then when you want to use it you can do myFunction();

o_O
  • 5,527
  • 12
  • 52
  • 90
0

You can put the check inside a function like so:

$(document).ready(function (){
  $(".below").click(function(){
    $(".header-wrapper").css("height", "200px");
    ifElse();
  });
});
function ifElse() {
  if($(".header-wrapper").css("height") == "100px"){
    alert("true");
  }
  else{
    alert("false");
  }
}
Matt O'Connell
  • 287
  • 3
  • 14
0

The problem with your code is that document.ready() only happens once, so the provided function can only be called once. instead, you'll need to attach an event listener to an element (perhaps the one that is changing the css) so that it can be called multiple times. You can read more about event listeners here. You could also look at a similar question posed about listening to style changes here

// attach this event to the specific element which is changing
// the css instead

document
  .addEventListener('click', function(){
     if($(".header-wrapper").css("height") == "100px"){
        alert("true");
      }
      alert("false");
  });
Community
  • 1
  • 1
Jonah Williams
  • 20,499
  • 6
  • 65
  • 53