Radical_Activity
Radical_Activity

Reputation: 2738

How to make the whole page clickable without using any cover elements with Javascript?

With Javascript, I'm looking for a way to make the whole page to redirect the user to another, no matter where they click on the page, and no matter if that element already has a click event listener. I want to redirect them no matter what.

Also, I do not want to use a cover element with fixed style and make them click on that, if possible.

Here's what I've tried so far:

function clickBody()
{
    window.location.href = 'http://google.com';
}

document.body.addEventListener("click", clickBody);

It works great, except the fact that it's not redirecting if the user clicks on the anchor tags.

Is there any solution to make this happen?

Upvotes: 0

Views: 42

Answers (2)

Eugene Tsakh
Eugene Tsakh

Reputation: 2879

Add true as the last arg to addEventListener (it means that it's capture event and should be handled before regular events) and stop event propagation and prevent default in your handler to prevent redirect on links click:

function clickBody(e) {
  e.preventDefault();
  e.stopPropagation();
  window.location.href = 'http://google.com';
}

document.body.addEventListener("click", clickBody, true);

Upvotes: 1

dgeare
dgeare

Reputation: 2658

You will want to use the capturing phase of the event lifecycle. From MDN

In the capturing phase:

The browser checks to see if the element's outer-most ancestor () has an onclick event handler registered on it in the capturing phase, and runs it if so. Then it moves on to the next element inside and does the same thing, then the next one, and so on until it reaches the element that was actually clicked on.

In the bubbling phase, the exact opposite occurs:

The browser checks to see if the element that was actually clicked on has an onclick event handler registered on it in the bubbling phase, and runs it if so. Then it moves on to the next immediate ancestor element and does the same thing, then the next one, and so on until it reaches the element.

function clickBody()
{
    window.location.href = 'http://google.com';
}

document.body.addEventListener("click", clickBody, true);

The third parameter here designates the event as capturing. https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

In all likelihood, the javascript should execute fast enough to beat out the default action for the link. But you may want to add event.preventDefault() just to be on the safe side.

Upvotes: 1

Related Questions