JavaScript on resize and load, move element based on window width

2.2k views Asked by At

I'm trying to move an element to an off canvas menu if the window width is less than 768px wide.

So far I have this:

<script>
    window.onresize = move_sidebar(event);
    window.onload = move_sidebar(event);
    function move_sidebar(event) {
        if(window.outerWidth > 768) {
            return;
        } else {
            console.log('resized or loaded');
            document.getElementById('offcanvas-menu').appendChild(document.getElementById('sidebar-content'));
        }

    }
</script>

When the window loads it works fine, the console log is shown and the element is moved, however, when I resize the window the event doesn't fire.

Unless I do:

window.onresize = function(event) { console.log('resizing'); };

This then logs each time the window is resized, I'm unable to figure out why there's a difference between the two.

I also need to move the element back to its original place if the width is greater than 768px, as long as it only exists in the offcanvas-menu element.

Any ideas?


EDIT:

I ended up fixing this with the following code:

<script>
    window.onresize = move_sidebar;
    window.onload = move_sidebar;
    function move_sidebar(event) {
        ele = document.getElementById('sidebar-content');
        if(window.outerWidth > 768) {
            if(ele.parentNode.id == 'offcanvas-menu') {
                document.getElementById('sidebar').appendChild(document.getElementById('sidebar-content'));
            }
            return;
        } else {
            document.getElementById('offcanvas-menu').appendChild(ele);
        }

    }
</script>
1

There are 1 answers

2
iMoses On BEST ANSWER

You are passing as the event handler the result of you move_sidebar function after execution, instead of passing the function itself.

Your code should be:

window.onresize = move_sidebar;
window.onload   = move_sidebar;

The reason it works for you when the page loads is only because you have manually executed your function by mistake.