Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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";
 }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading