Html code:
<div class="box green">I'm green!</div>
<div class="box blue">I'm blue!</div>
<div class="box orange">I'm orange!</div>
CSS code here:
.green { background-color: green; }
.blue { background-color: dodgerblue; }
.orange { background-color: orangered; }
JavaScript code here using object literal syntax : // want to apply same effect to box2 and box3
var box1 = {
color: 'Green',
number: 1,
clickMe: function () {
var green = document.querySelector('.green');
var self = this;
green.addEventListener('click', function () {
var str = 'This is box number ' + self.number + ' and it is ' + self.color;
alert(str);
});
}
}
box1.clickMe();
If you wish to use a constructor you can use a
class. You can use a constructor like so (see snippet), where it accepts acolorand anumber.You then need to modify your function within the
addEventListenerto be an arrow function (() => {}) so it references the correctthiswhen called.Lastly, when creating your boxes you need to provide a
colorand anumberas defined by the constructor (var myBox = new Box(COLOR, NUMBER)):