0

I have made a jquery script that relies on variables for viewport width and viewport height. This is the script with the viewportwidth and viewportheight variables, stored in its own document:

var viewportwidth,viewportheight;"undefined"!=typeof window.innerWidth?(viewportwidth=window.innerWidth,viewportheight=window.innerHeight):"undefined"!=typeof document.documentElement&&"undefined"!=typeof document.documentElement.clientWidth&&0!=document.documentElement.clientWidth?(viewportwidth=document.documentElement.clientWidth,viewportheight=document.documentElement.clientHeight):(viewportwidth=document.getElementsByTagName("body")[0].clientWidth,viewportheight=document.getElementsByTagName("body")[0].clientHeight);

Here is the script:

function kjør() {
    if ((viewportwidth / viewportheight) >= 1.33) {
            $('#redline').appendTo('body');
        $('#sitewrap').on('scroll', function(e) {
            if ($(this).scrollTop() > (viewportheight / 100 * 40)) {
                $('body').addClass('fix');
                $('#headerwrap').appendTo('body');
            } else {
                $('body').removeClass('fix');
                $('#headerwrap').appendTo('header');
            }
        $("#logo-top").css("opacity", 1 - $(this).scrollTop() / (viewportheight / 100 * 30));
        });
    } else {
        $('#headerwrap').appendTo('body');
        $('#redline').prependTo('#headerwrap');
        $('body').removeClass('fix');
    };
};
$(function() {
    kjør();
    $(window).resize(kjør());
});

As you can se at the bottom. I have tried making it so that the script will update once window is resized. This doesnt work, however. The script will still use the viewportwidth and viewportheight that were established on pageload. How can I make the script reevaluate viewport height and viewport width on window resize?

student42
  • 161
  • 1
  • 2
  • 9
  • 1
    You're assigning the *result* of the `kjør()` function to the resize handler. You need to give it the function *reference* instead: `$(window).resize(kjør);` – Rory McCrossan Mar 01 '17 at 13:46
  • Not exact duplicate but its answer will solve the problem – Rajesh Mar 01 '17 at 14:01

1 Answers1

1

Your problem is the line bellow:

 $(window).resize(kjør());

Change it to:

 $(window).resize(kjør);

When you use the sintax function_name() you are referencing the return value of the function, not the function itselfs.

Romulo
  • 4,896
  • 2
  • 19
  • 28