0
var res=document.getElementById("panel");
    var wid = window.innerWidth;
if(wid <= 900){
    res.setAttribute("id", "panel2");
}

I want to change some styling depends on the size of the browser ( to make it more responsive ) , but what I have tried did not worked :(

see more :https://ahmadahmadahmad.000webhostapp.com/

Zoe stands with Ukraine
  • 25,310
  • 18
  • 114
  • 149
ahmad
  • 17
  • 1
  • 7

2 Answers2

1

Your javascript code only executes once when it is loaded.
To make the function being called when something happens, you need to attach it to an event listener.

In this case, you may want the panel changed when the screen is resized.
So, attached the function to window.onresize event listener.
The function will then be triggered when you resize the screen.

The code is as below. (I use body element as an example instead)

var res=document.querySelector("body");

window.onresize = function () {
  var wid = window.innerWidth;
  if(wid <= 900){
      res.setAttribute("style", "background-color: red;");
  }
}

You can drag the screen size to see if the background color changed when width under 900px.
Is this what you want to achieve?

Arel Lin
  • 848
  • 1
  • 10
  • 22
0

You will need to use the resize event

let res=document.getElementById("panel");
let wid = window.innerWidth;
if(wid <= 900){
    res.setAttribute("id", "panel2");
}


function Init(){
   wid = window.innerWidth;
if(wid <= 900){
    res.setAttribute("id", "panel2");
}else{res.setAttribute("id", "panel");}
}

setTimeout(function() {
  Init();
  addEventListener("resize", Init, false);
}, 15);
[id^="panel"]{
  width:100vw;
  height:100vh;
  background:green;
}

#panel2{background:blue;}
<div id="panel"></div>
enxaneta
  • 28,575
  • 5
  • 27
  • 37