I'm trying to use JavaScript class architecture in combination with addEventListener
such that I can define a series of class methods once, which will be applied to all appropriate HTML and/or CSS objects. Below is an example with ONLY one circle, which should toggles red or blue when clicked. Unfortunately, as is, the class does architecture is unable to properly communicate with the DOM.
I've chosen to write the script in-line just to explore the basic concept more easily rather than juggling around multiple files for purposes of question cohesion (I do realize that in actuality, I'd likely use separate HTML and JS files.)
I'd like to code as is to be edited such that the circle changes color when clicked. (Also, the code DID function when class architecture was not used. I can add that if it's useful.)
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.circle {
height: 50px;
width: 50px;
background-color: #555;
border-radius: 50%;
}
</style>
</head>
<body>
<h2>Circle CSS</h2>
<div class="circle"></div>
<script>
class GameObject{
constructor(shape){
this.shape = shape;
this.clicks = 0;
};
clickEvent(){
this.shape.addEventListener('click',function(){
this.clicks += 1
if (this.clicks % 2 == 1){
this.shape.style.backgroundColor = 'red';
}else{
this.shape.style.backgroundColor = 'blue';
}
})
};
};
let shape = document.querySelector('.circle')
let s = new GameObject(shape);
console.log(s);
</script>
</body>
</html>
Also, the following questions/answers went above my head, though they are related: Javascript Class & EventListener Dealing with Scope in Object methods containing 'this' keyword called by Event Listeners
Edit: I took advice from comment and added clickEvent()
into this constructor. However, the following error was triggered:
Uncaught TypeError: Cannot read property 'style' of undefined
at HTMLDivElement.<anonymous> (circle.html:31)