Home > Back-end >  How can I change element constantly based on window.innerWidth resize?
How can I change element constantly based on window.innerWidth resize?

Time:08-09

I want to change element dynamically according to window width. It should change to a new element when condition is met, as well as revert back to the original element when window is restored to its original size. Here's my code attached:

HTML

<div>
  <h1>My Name</h1>
</div>

JS

const parentDiv = document.querySelector('div');

console.log(window.innerWidth);
window.addEventListener('resize', () => {
  if(window.innerWidth <=1000){
      parentDiv.innerHTML = '<p>lorem Ipsum</p>'
    }
})

But here, after changing back the window size to a width of >1000px, the div tag still holds p tag instead of reverting back to the original h1 tag. Should I add another event listener for this specific task? Or is there any other method of window object by which we can achieve this?

CodePudding user response:

As suggested in the comments, simply add an else statement to revert back to the <h1>:

window.addEventListener('resize', () => {
  if(window.innerWidth <=1000){
    parentDiv.innerHTML = '<p>lorem Ipsum</p>'
  } else {
    parentDiv.innerHTML = '<h1>My Name</h1>'
  }
})

FYI, using CSS media queries is a lot more efficient than listening to the window resize event:

  • Related