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.
The onclick attribute is part of the Event Attributes, and can be used on any HTML elements.
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).
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With