1
but a tutorial using modern js concepts.
DOM elements can have various events on them, that can then be used to run blocks of code once an event occurs in the page. Events can also be added to the Window object as well as the Document Object by using the AddEventListener() method or the various element events. The window and document object can run functions once the selected event occurs, like onLoad and DOM Content Loaded events in JavaScript. This exercise will provide an example of how to use these events.
```html
Javascript, interaction with events
Javascript 1
```
**the apps.js**
```js
window.onload = init;
document.addEventListener('DOMContentLoaded',init3);
function init3(){
const div = document.querySelector('div');
div.style.backgroundColor = '#ddd';
const h1 = document.createElement('h1');
h1.textContext = 'James Hetfield';
div.append(h1);
div.addEventListener('click',click1, {
once: true
});
h1.addEventListener('click',click2);
h1.addEventListener('click', click3);
}
function init2(){
const div = document.querySelector('div');
div.style.backgroundColor = '#ddd';
const h1 = document.createElement('h1');
h1.textContent = 'James Hetfield';
div.append(h1);
div.onclick = click1;
h1.onclick = click2;
}
function click1(e){
console.log('DIV');
}
function click2(e){
console.log('H1');
}
function click3(e){
e.target.removeEventListener('click',click2);
console.log('Event #3');
}
function init1(){
console.log('doc');
const div = document.querySelector('div');
const h1 = document.createElement('h1');
h1.textContext = 'James Hetfield';
h1.onclick = () => {
console.log('h1 #2');
}
h1.addEventListener('click',(e) => {
console.log('h1 #1');
})
h1.onclick = () => {
console.log('h1 #3');
}
h1.addEventListener('click',(e) => {
console.log('h1 #4');
})
h1.addEventListener('click',(e) => {
console.log('h1 #5');
})
div.append(h1);
console.log(div);
}
function init(){
console.log('window');
}
```
like it? then leave your comment to boost the post. thanksYou must log in or register to comment.