Priyanshi
Priyanshi

Reputation: 5

DOM Manipulation Click Mouse Event

I was trying to change the color of the background of the web page with a mouse click, below are the lines for the same:

let bodyvar = document.querySelector('body');

bodyvar.addEventListener("click",generate);

function generate(){
    bodyvar.style.backgroundColor = "red";
}

When I test individual lines in console it is selecting the body and the function and everything works correctly individually but not on the actual page.

I have just started leaning JS so am not sure what am missing here, will I also need to consider the co-ordinates that the mouse clicks on?

Upvotes: 0

Views: 41

Answers (1)

BadPiggie
BadPiggie

Reputation: 6384

I suspect that the <body></body> is empty. Add some content, or define the width and height.

let bodyvar = document.querySelector('body');
bodyvar.style.minWidth = "100vw";
bodyvar.style.minHeight = "100vh";

bodyvar.addEventListener("click",generate);

function generate(){
    bodyvar.style.backgroundColor = "red";
}

Alternatively, I can use <HTML> instead of <body>.

let bodyvar = document.querySelector('html');

 bodyvar.addEventListener("click",generate);

 function generate(){
     bodyvar.style.backgroundColor = "red";
 }

Upvotes: 1

Related Questions