hiyo
hiyo

Reputation: 131

Something blocks addEventListener(type, handler) to work in DOM

I'm learning Vanilla JS and DOM, and I'm testing some codes in console. I have a question.

Step 1) Navigate to website "http://rehub.wpsoul.com" in chrome.

Step 2) Open a console.

Step 3) Write down below code in console.

var neww = window.open('/')
neww.addEventListener('click', function() {
    alert('hi');
})

This code is not working. However, if I change the event type from 'click' to 'scroll', it does work well.

What makes it hinder to work in DOM?

Whenever I tested this code, some websites does not work event type, 'load' like this website.

I've had a headache for this for a few days. I would like to know the reason and principle of DOM and JS.

I need your help, thanks! :)

Upvotes: 0

Views: 185

Answers (1)

Rakesh Rawat
Rakesh Rawat

Reputation: 327

As you are opening a new window and its DOM is not yet available or ready, the event is not getting bind. Please try following code:

var neww = window.open('/')
neww.addEventListener('load', function() {
    neww.document.body.addEventListener('click', function() {
        alert('hi');
    });
});

Upvotes: 1

Related Questions