1+ // ******************************
2+ // Events on Multiple Elements ******************************
3+ // Example 1
4+ console . log ( 'Events on Multiple Elements' )
5+ console . log ( '\n' )
6+
7+ const colors = [
8+ 'red' ,
9+ 'orange' ,
10+ 'yellow' ,
11+ 'green' ,
12+ 'blue' ,
13+ 'purple' ,
14+ 'indigo' ,
15+ 'violet' ,
16+ ]
17+
18+ // Using functions
19+
20+ // const printColor = function (box) {
21+ // console.log('CLICKED A BOX')
22+ // console.log(box.style.backgroundColor)
23+ // }
24+
25+ // const container = document.querySelector('#boxes')
26+
27+ // for (let color of colors) {
28+ // const box = document.createElement('div')
29+ // box.style.backgroundColor = color
30+ // box.classList.add('box')
31+ // container.appendChild(box)
32+ // box.addEventListener('click', function() {
33+ // printColor(box)
34+ // })
35+ // }
36+
37+ // Using THIS keywordq
38+ const changeColor = function ( ) {
39+ const h1 = document . querySelector ( 'h1' )
40+ h1 . style . color = this . style . backgroundColor
41+ console . log ( this )
42+ console . log ( this . style . backgroundColor )
43+ }
44+
45+ const container = document . querySelector ( '#boxes' )
46+
47+ for ( let color of colors ) {
48+ const box = document . createElement ( 'div' )
49+ box . style . backgroundColor = color
50+ box . classList . add ( 'box' )
51+ container . appendChild ( box )
52+ box . addEventListener ( 'click' , changeColor )
53+ }
54+
55+ const h2 = document . querySelector ( 'h2' )
56+ h2 . addEventListener ( 'mouseover' , function ( ) {
57+ console . log ( h2 . innerText ) ;
58+ } )
0 commit comments