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 a color
and a number
.
You then need to modify your function within the addEventListener
to be an arrow function (() => {}
) so it references the correct this
when called.
Lastly, when creating your boxes you need to provide a color
and a number
as defined by the constructor (var myBox = new Box(COLOR, NUMBER)
):
class Box {
constructor(color, number) {
this.color = color;
this.number = number;
}
clickMe() {
var elem = document.querySelector('.' + this.color);
elem.addEventListener('click', () => {
var str = 'This is box number ' + this.number + ' and it is ' + this.color;
alert(str);
});
}
}
var box1 = new Box('green', 1);
var box2 = new Box('blue', 2);
var box3 = new Box('orange', 3);
box1.clickMe();
box2.clickMe();
box3.clickMe();
.green { background-color: green; }
.blue { background-color: dodgerblue; }
.orange { background-color: orangered; }
<div class="box green">I'm green!</div>
<div class="box blue">I'm blue!</div>
<div class="box orange">I'm orange!</div>