Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the onclick event on the body element not working?

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.

like image 352
user1234597 Avatar asked May 06 '16 14:05

user1234597


People also ask

Does Onclick work on any element?

The onclick attribute is part of the Event Attributes, and can be used on any HTML elements.

What HTML elements can have onclick?

All HTML elements can have an onclick attribute. See the HTML 5 specification for confirmation. (Of course, some elements are not rendered by default so you would have to alter their display properties with CSS before they can be clicked on to trigger the event handler).

Can we use onclick on anchor tag?

It is safe to click on that link with # href; the page does leave/reload url. Follow the above advice with caution, as HTML5 rules explicitly state that href="#" is supposed to navigate to the top of the page. You can simply add the href attibute without content, and get the click behaviour.


1 Answers

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>
like image 143
Michał Perłakowski Avatar answered Sep 28 '22 22:09

Michał Perłakowski