Home > Enterprise >  How to add html code based on the screen sizes using Javascript?
How to add html code based on the screen sizes using Javascript?

Time:03-20

I want to make add some code to the HTML dom according to the screen sizes. I want to totally remove the code when the screen size is something instead of still having the code and doing display: none. How can I do it?

<div id="main">
  <h1>One</h1>
</div>
const main = document.getElementById('main');

if(window.innerWidth <= 400) {
       main.innerHTML = '<h2>Added By js</h2>';
 }
 else {
 main.innerHTML = '';
 }

CodePudding user response:

Simply use the @media screen of css, I think you need to do this:

h1{
   display: block;
  }
 h2{
   display: none;
  }

@media screen (max-width: 400px) {
 h1{
   display: none;
  }
 h2{
   display: block;
  }
 }

doing this you tell the browser to set display:none of the h1 when the screen width is over 400px, you can do it too with height

CodePudding user response:

If you want to do it with javascript, all you're missing are the events that will trigger your code

function yourFunction() {
    const main = document.getElementById('main');

    if(window.innerWidth <= 400) {
       main.innerHTML = '<h2>Added By js</h2>';
    } else {
    main.innerHTML = '';
    }
}

window.onload = yourFunction;
window.onresize = yourFunction;
  • Related