setAttribute with Global Attributes

Hey guys, i want to create a function to hide and show a button when the tab gets small but don’t works with the method setAttribute.

let wh = window.innerHeight;
let ww = window.innerWidth;

re = wh + ww;

document.getElementById("messenger").innerHTML = re;

if(re <= 1000)
    document.getElementById("button").setAttribute  = "hidden";

Is it likely that it’s only when the page loads that the code runs?

I don’t see any kind of event or interval in which that code runs. You will need one of those so that the code can run after the page loads.

I suggest using a setInterval of about 250 milliseconds so that the effect is responsive without affecting the browser performance.

I use this in the head tag of my web page

<script defer src="script.js"></script>

I confirm my code run on my web page with this

document.getElementById("messenger").innerHTML = re;

Showing the sum of the height and width of the tab. So, how i can get set the hidden value on my button?

When it’s a class name that you’re dealing with, use the classList API. For example:

// use the classList API to remove and add classes

This is my button in my web page

 <button id="button"><img src="images/list.png"></img></button>

I don’t use OOP or any framework. It’s only raw web page with html, css and i tryng to put some javascript code in it.

So you could do:

const button = document.getElementById("button");

Or as a one-liner:


to add the class hidden to the button element.

You could then use CSS to control its presentation:

.hidden {
  display: none;
1 Like

Thanks a lot!

1 Like

Or just use:


I know that it’s tempting to directly edit the style properties, but that’s usually a bad practice as it leads to reliability problems later on down the line.

I disagree :grinning:

I’m not in the mood to educate on issues about:

  • Separation of Concerns
  • Don’t Repeat Yourself
  • Caching
  • Version control

Just know that the concerns are there.

1 Like

FYI (after the fact)…

The <img> element is not a container. As such, it does not expect a closing tag (or an XHTML closing slash).

<img src="images/list.png"></img>

should be

<img src="images/list.png">

Depending on usage, it may require the “alt” attribute and possibly “width” and “height” attributes. You might want to check it out in your favorite HTML reference.