Django - Javascript eventListener executes immediately before any event

Hi everyone,

Struggling with this. Would appreciate any help!

I’m trying to get a basic JavaScript function working. When the html canvas is clicked, an alert should appear saying “clicked”. However, the function executes immediately upon the page loading, and before any event like mouse clicking. It also doesn’t work with clicking.

At the moment I have written the script inside the html file for simplicity.

{% extends 'genie/base.html' %}
{% load static %}

{% block content %}

<div class="d1">

        <!-- Write image before loading into canvas -->
        <img style='display: none;' src="{% static 'genie/example-array.jpg' %}" id="myArray"/>

        <!-- Make canvas -->
        <canvas class="d2" width="316px" height="384px" id="dens-canvas">

        <!-- Load image to canvas -->
            var c = document.getElementById("dens-canvas");
            var ctx = c.getContext("2d");
            var img = document.getElementById("myArray");
            window.onload = function() {
                ctx.drawImage(img, 0, 0, 316, 384);
        <!-- Execute function upon click -->
            var c = document.getElementById("dens-canvas");
            c.addEventListener("click", alert("click"));

{% endblock %}

Many thanks,
Sad Man

You’re actually calling the function here rather than registering a function name. You need to do something like (untested):

function do_alert(){
c.addEventListener("click", do_alert);

Note: You could also define it as an inline function definition:

c.addEventListener("click", function(){ alert("Click"); });
1 Like

Hi KenWhitesell, that looks like the problem. Thank you so much for your help. I don’t know how I’d get by without these forums and people like you. Cheers! I’ll test this later when I can