Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I run a JavaScript function with any click on the page?

Right now I'm using <body onload="function">, which changes some text on the page based on which element is focused on. It works fine, but I need my site to run the function every time the focus changes (or, even better, every time any part of the page is clicked).

Currently the code looks like this:

<body onload="changeText()">
<script>
function changeText(){
     function here;
}
</script>
<p>This is where text changes based on the function</p>

Thanks!

like image 742
sway Avatar asked Dec 27 '22 16:12

sway


2 Answers

window.onclick = function () {
  //do some stuff
  document.body.style.backgroundColor = "red";
}
<p>text text text</p>
<button>it does not matters if you press me or any where else</button>
like image 44
Yuval.R Avatar answered Dec 29 '22 08:12

Yuval.R


You can attach onclick event on document. jsfiddle

​document.onclick = function(){
 // your code
 //alert("clicked");
}​

If you want change on focus then use

window.onfocus = function(){

   // your code
     //alert("focus");
}
like image 69
Anoop Avatar answered Dec 29 '22 08:12

Anoop