简体   繁体   中英

onresize event listener to change color of html body

I have to use an event listener to change the body to a random color on the resize of the window. What I have currently does not change the color. I am getting no console errors so Im not sure what the issue is. I was given the function the generates the random color.

HTML

<body id="body11">
    <div>
        <p>requirement 11</p>
    </div>
</body>

Javascript

<head>
    <script>
        document.addEventListener("DOMContentLoaded", function() {
            window.addEventListener("onresize", bodyColor)
            function bodyColor(){
                document.getElementById("body11").style.backgroundColor =
                '#'+Math.floor(Math.random()*16777215).toString(16);
            }
        }); 
    </script>
</head>

here what I thought my code was saying....

add an event listener to the document that upon DOMContentLoaded would call the the function to add an eventlistener to the window such that on resize it would call the function to change the background color of the body to a random color.

I also tried to put the script at the bottom of body and do away with the DOMContentLoaded aspect, but that resulted in the same results.

I get no console errors, and I have to use an eventlistener as this is for a homework objective.

where did I go wrong?

You should be listening for an event named "resize", not "onresize".

The reason you're not getting any console output is that the event itself isn't getting fired.

This -

window.addEventListener("resize", function(e){
  // your body color change code
});

should work

I'm pretty sure that I'm in your class! I did something a little simpler for mine by cutting out the first part of your code:

function colorMe() {

        window.addEventListener("resize", function(){
            document.getElementById("body11").style.backgroundColor =
            '#'+Math.floor(Math.random()*16777215).toString(16);
        });
    }

hope that helps!

I'm also in your class it seems. I did the following simpler code BUT it only works if the script is in the HTML document and not the external js file:

    <script>window.addEventListener("resize", function(){
            document.getElementById("body11").style.backgroundColor =
            '#'+Math.floor(Math.random()*16777215).toString(16);

});

PS As a side note to those classmates here, how did you code req #1 -- my code works in a couple of browsers but is a complete no-show in Firefox!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM