1

Relocate element based on screen size

I need to place an element on a page based on the browser size. I cannot hide and show this element because it can only be once in the dom. Seems pretty straight forward but I'm stuck. It seems to be working partially. Do I need to do some sort of detach/attach? Sorry, it' been a while since i tinkered with plain JS.

srPos();
window.onresize = srPos();

function srPos() {
    var ww = window.innerWidth,
        sr = document.getElementById("gcs-box"),
        pp = document.getElementById("primary-panel"),
        sp = document.getElementById("secondary-panel");
    
    if (ww > 991) {
        sp.prepend(sr);
    } else {
        pp.prepend(sr);
    }        
}

What am I missing?

Submitted October 02nd 2021 by Admin

Answers
0

You are assigning the value returned by srPos rather than the function itself to the onresize property.

Remove the brackets:

srPos();
window.onresize = srPos; function srPos() { var ww = window.innerWidth, sr = document.getElementById("gcs-box"), pp = document.getElementById("primary-panel"), sp = document.getElementById("secondary-panel"); if (ww > 991) { sp.prepend(sr); } else { pp.prepend(sr); } }

Admin | 2 weeks ago



Relevant Questions