简体   繁体   中英

Execute Jscript only at certain width without jQuery

Okay so with much attempt to no prevail, I have been trying to change the order of the below divs using the following JScript command (without jQuery) only when the window is at a certain width; particularly 1024px and below . The JScript used is successful in executing and subsequently changing the order of the divs, however it occurs at all widths.

I wish for box-3 to be above box-1 when the window width is equal to or less than 1024px (without using jQuery).

<html>
 <body>
  <div class="box-1"></div>
  <div class="box-2"></div>
  <div class="box-3"></div>
  <div class="box-4"></div>
 </body>
</html>

<script type="text/javascript">
 var content = document.querySelector('.box-3');
 var parent = content.parentNode;
 parent.insertBefore(content, parent.firstChild);
</script>

Thanks in advance!

Edit: Question is different from "Execute function based on screen size" (Authored by Jim) because solutions given to Jim included - and accepted - jQuery, whereas this question is purely for vanilla Javascript

Alright, so you were on the right track using window.onresize .

A suggested edit and a good point :

If you want the reorder to happen before the window is resized, make sure you check the size of window when the page is opened by using window.onload . To make everything more concise you can put your reorder code into a function, let's say myResizeFunction() and then do something like this

var needsReset = false;
window.onresize = function() {
    if( this.innerWidth <= 1024 ) {
        myResizeFunction();
    } else {
        if( needsReset ) {
            //UNDO THE REORDER OR
            //WHATEVER CODE YOU WANT IF SCREEN IS LARGER THAN TARGET SIZE
        }
    }
}
window.onload = function() {
    if( this.innerWidth <= 1024 ) {
        myResizeFunction();
    }
    //NO ELSE BLOCK NEEDED BECAUSE
    //IF SCREEN SIZE ISN'T IN TARGET RANGE WE HAVE NOTHING TO UNDO
}
function myResizeFunction() {
    //NOW YOUR REORDER CODE LIVES HERE
    //SET needsReset TO true BECAUSE WE'VE CHANGED THE ORDER OF ELEMENTS
    needsReset = true;
}

I'm on a mobile so I can't test how the DOM is changing but try parent.lastChild instead.

If you're removing the .box-3 and then inserting it in front of .box-1 (I believe this is what is happening) then doing a insertBefore on the parent.lastChild should put box 3 back in its original spot

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM