0

Got a variable that should have a value assigned to it based on window width. Width conditional statement works (checked with console.log). Adding class works as well if variable is declared and assigned a value outside the conditional statement. But nothing works if variable is inside that if statement. What am i missing?

    if ($(window).width() < 960) {
        var stickywidth = 200;
    } else {
        var stickywidth = 500;
    }
    $(window).scroll(function() {
        if ($(this).scrollTop() === stickywidth) { 
            $('.sticky').addClass('opensticky');
        }
    });
Jodast
  • 1,279
  • 2
  • 18
  • 33
Samij
  • 81
  • 7

1 Answers1

-1

I used to not to use the var inside the if statement .. so I believe that always something wrong will happen with the Scope .. so (if me) I'll define var stickywidth = 0 outside the if statement then update the variable inside the if statement without var or I use it with a ternary operator:

var stickywidth = $(window).width() < 960 ? 200 : 500;
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
Mohamed-Yousef
  • 23,946
  • 3
  • 19
  • 28
  • Consider explaining what the issue was in OP's attempt, to which this is a solution. – Tyler Roper Feb 21 '19 at 00:41
  • Yep. That worked. What was wrong with my code, though? – Samij Feb 21 '19 at 00:43
  • @Samij I used to not to use the `var` inside the if statement .. so I believe that always something wrong will happen with this .. so (if me) I'll define `var stickywidth = 0` outside the if statement then update the variable inside the if statement without `var` or I use it something like my answer above – Mohamed-Yousef Feb 21 '19 at 00:47
  • i see. Thanks!! – Samij Feb 21 '19 at 00:50