'Triggering function when clicking generated objects javascript

I have this code to generate random objects in a specific canvas i want to make those objects clickable so if i click on one of the objects i trigger a function im not really good with javascript so i need some help here is the code

function spawnRandomObject() {

    var t ;



    if (Math.random() < 0.50) {
        t = "red";
    } else {
        t = "yellow";
    }

    var object = {
        type: t,
        x: Math.random() * (canvas.width - 30) + 15,
        y: spawnLineY,
    }

    objects.push(object);
}```


Solution 1:[1]

To add an event listener you should have a HTML element like so:

<div id="clickable-object">Click this Object</div>

Then in your script file you assign that element to a variable and attach an event listener to it.

let object = document.getElementById('clickable-object');

object.addEventListener('click', function() {
    console.log('This object has been clicked');
}

In order for your javascript to be able to interact with the html you need to include your js file in the html file.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Maxim Vladimirovich