Run javascript without calling in html

Asked

Viewed 47 times

0

Hello

I need to change the background color of a div, I’m trying but it doesn’t work which may be wrong ?

My code:

window.onresize = function() {
  var w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
  if (w < 800) {
    getElementById("top").style.background-color = "#FFFFFF";
  }
};

Thank you

  • When you want to manipulate some element of the DOM(Document Object Model) you first need to access it right? In case the document, ie, Document.getElementById(...

  • 1

    In addition to the @Leandrade comment, you need to change the style.background-color for style.backgroundColor

  • Thank you so much for your help.

3 answers

1


There are 2 errors in your code:

  • Before getElementById should have document.
  • background-color cannot have special characters like CSS, always use camelCase. Example: backgroundColor

And finally, your code will look like this:

window.onresize = function() {
  var w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
  if (w < 800) {
    document.getElementById("top").style.backgroundColor = "#FFFFFF";
  }
};

I hope I’ve helped.

  • Thank you so much for your help.

0

Try the following

<div id="top" style="height: 50px; width: 50px; background-color:red"></div>
<script>
    window.onresize = function() {
        const top = document.getElementById('top');
        const red = '#ff0000';
        const green = '#4CAF50';        
        var w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
        top.style.backgroundColor = w <= 800 ? red: green;
        /*
        if (w <= 800)
            top.style.backgroundColor = "#4CAF50";
        else if (w > 501)
            top.style.backgroundColor = "#ff0000";
        */
    };
</script>

0

  1. wrong getElementById correct document.getElementById
  2. wrong background-color correct backgroundColor

    function sizeOfThings(){
      var windowWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;;

     alert('Width  =  '+windowWidth+ " é menor que 800, portanto vai ficar azul");
      
      document.getElementById('top').innerHTML = "Width = "+ windowWidth;

      if (windowWidth < 800) {
        document.getElementById('top').style.backgroundColor = "blue"
      }

    };
    
sizeOfThings();
    <h1 id="top" style="background-color: #FF0000">cor inicial deste titulo é vermelho</h1>

  • Thank you so much for your help.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.