black
black

Reputation: 723

How to get changes without refreshing browser?

When I resize browser and refresh page if div width greater than browser width the div is displayed none. How to make it without refreshing page. For example when I resize browser and if div width grater than browser width it will automatically without refreshing page displayed none.

var body = document.querySelector('body');
var div = document.querySelector('div');

if (div.scrollWidth > body.clientWidth) {
  div.style.display = 'none';
}
body {
  margin: 0px;
  padding: 0px;
  box-sizing: border-box;
}

div {
  width: 350px;
  height: 60px;
  background-color: lightgray;
}
<body>
  <div> </div>
  <script src="main.js"></script>
</body>

Thanks.

Upvotes: 0

Views: 103

Answers (3)

Yusuf
Yusuf

Reputation: 352

This is not the right way to do it but you can listen to resize event to recheck your conditions.

let body = document.querySelector('body');
var div = document.querySelector('div');

if (div.scrollWidth > body.clientWidth) {
  div.style.display = 'none';
}

window.addEventListener("resize", function() {
  if (div.scrollWidth > body.clientWidth) {
    div.style.display = 'none';
  }else div.style.display = '';
});
body {
  margin: 0px;
  padding: 0px;
  box-sizing: border-box;
}

div {
  width: 350px;
  height: 60px;
  background-color: lightgray;
}
<body>
  <div> </div>
  <script src="main.js"></script>
</body>

For this kind a responsive conditions best way to go is with css media queries. You can find more information here: https://www.w3schools.com/css/css_rwd_mediaqueries.asp

Upvotes: 1

shubham jain
shubham jain

Reputation: 84

You can use media query for such requirement. Include below code in css.

@media only screen and (max-width: 600px) {
body {
    display: none;
}

}

Upvotes: 0

Jilu
Jilu

Reputation: 197

Why don't you use CSS media rules ? Media rules can apply different style on different sizes of screen.

For example:

@media screen and (max-width: 600px) {
  div.example {
    display: none;
  }
}

docs for more informations about @media rules: https://www.w3schools.com/cssref/css3_pr_mediaquery.asp

Upvotes: 0

Related Questions