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
  • 27,060
  • 21
  • 118
  • 148
  • 3
    Why not just use a [CSS media query](https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries)? – Pointy Oct 27 '18 at 14:51
  • because i ant to add a java script also –  Oct 27 '18 at 14:57
  • Depends on where and when you call that code. Please provide a [mcve] along with a properly detailed problem description and explanation of expected behavior. See [ask] – charlietfl Oct 27 '18 at 14:59
  • 1
    Also why change id , seems like an odd concept? – charlietfl Oct 27 '18 at 15:00
  • @charlietfl i want to add js code and change the layout ( to make an drop down menu for mobile view ) –  Oct 27 '18 at 15:13
  • What does that have to do with changing an ID? And where is the rest of the code? – charlietfl Oct 27 '18 at 15:14
  • @charlietfl https://ahmadahmadahmad.000webhostapp.com/ –  Oct 27 '18 at 15:19
  • Possible duplicate of [Why does jQuery or a DOM method such as getElementById not find the element?](https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) – Kael Watts-Deuchar Oct 27 '18 at 17:28
  • @KaelWatts-Deuchar thanks that helped alot :) –  Oct 27 '18 at 17:42

2 Answers2

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
  • 31,608
  • 5
  • 29
  • 42
0

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
  • 908
  • 2
  • 13
  • 24