7

I'm trying to send users to another page when click html body:

JavaScript c.js:

function clickBody(){
    window.location.href = '/';
}

HTML:

<!DOCTYPE html>
<html>

<head>
  <script src="c.js"></script>
</head>

<body onclick="clickBody();" />

</html>

I can run the function from console, but clicking the <body> is not working.

Xbox One
  • 307
  • 2
  • 13
user1234597
  • 81
  • 1
  • 1
  • 5

3 Answers3

22

The <body> element is empty. You have to either change its height in CSS, or put some text in it.

Also, using element.addEventListener() might be a good idea. See addEventListener vs onclick.

See code snippet:

function clickBody() {
    window.location.href = '/'
}
document.body.addEventListener("click", clickBody)
<!DOCTYPE html>
<html>
<head>
    <script src="c.js"></script>
</head>

<body>
  <p>Try clicking me.</p>
</body>  
</html>
Community
  • 1
  • 1
Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177
12

The <body> element has no height. Add something like the code below:

<!DOCTYPE html>
<html>

<head>
  <style>
    body {
      height: 500px;
    }
  </style>
  <script src="c.js"></script>
</head>

<body onclick="clickBody();/>  

</html>
Xbox One
  • 307
  • 2
  • 13
Shijin TR
  • 7,516
  • 10
  • 55
  • 122
3

I use window instead of document.body

window.onclick = () => {
console.log('Page clicked')
}
<h1>click anywhere on this page</h1>