JSFiddle - React, Tailwind, and code Playground
HTML
<div id="changeBGOne" style="height: 20vh; background:orangered;margin-bottom:10vh;">
</div>
<button id="triggerBGOne" data-changeBG >TriggerOne</button>
<div id="changeBGTwo" style="height: 20vh; background:pink;margin-bottom:10vh;">
</div>
<button id="triggerBGTwo" data-changeBG >TriggerOne</button>
JavaScript
class changeBGColor {
constructor({ targetBG , triggerEl }) {
this.changeBGElem = document.getElementById(targetBG);
this.triggerElem = document.getElementById(triggerEl);
this.addEventListeners();
//this.onClick = this.onClick.bind(this);
//this.onClick.bind(this);
}
addEventListeners() {
/*
#DIFFICULTY , what is the difference between the below two ?
why in the 2nd case the value of `this` is the button;
*/
// this.triggerElem.addEventListener( 'click' , (ev) => {
// this.onClick(ev);
// });
/*
#DIFFICULTY , why does the below line not work inspite of
this.onClick = this.onClick.bind(this)
in the constructor.
*/
this.triggerElem.addEventListener( 'click' , this.onClick.bind(this) );
}
changeBG() {
const bgChangeBgElem = this.changeBGElem;
bgChangeBgElem.classList.toggle('myclassName');
}
onClick(ev) {
console.log(this);
if( ev.target.hasAttribute('data-changeBG') ) {
this.changeBG();
}
}
}
new changeBGColor({
targetBG : 'changeBGOne',
triggerEl : 'triggerBGOne'
});
new changeBGColor({
targetBG : 'changeBGTwo',
triggerEl : 'triggerBGTwo'
});