sjos
sjos

Reputation: 53

If/else statement checking opacity, and adding class but not removing class

The below function checks the opacity of the header (which fades out on scroll) and if it is less than 1 turns off pointer-events(clickability) by adding the class headerclickoff. For some reason it wont remove it! Any idea what's wrong with my code?

function headerclickoff(){
  var opacity = $("header").css("opacity");
if ( opacity <= 1) {
    console.log("working");
  $("header").addClass("headerclickoff");
} else {
  $("header").removeClass("headerclickoff");
};
};

Upvotes: 0

Views: 815

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

The opacity values varies from 0...1 so your condition will always be true.

So I think you need to add the class if opacity is less than 1, not less than or equal to

function headerclickoff() {
    var opacity = $("header").css("opacity");
    if (opacity < 1) {
        console.log("working");
        $("header").addClass("headerclickoff");
    } else {
        $("header").removeClass("headerclickoff");
    }
}

You can also use toggleClass

function headerclickoff() {
    var opacity = $("header").css("opacity");
    console.log('opacity', opacity);
    $("header").toggleClass("headerclickoff", opacity < 1);
}

Demo: Fiddle

Upvotes: 3

Related Questions