0

I'm playing around with Javascript and created a class. On initializing the class, I add a button to a certain div and then add an event listener to that button for when it's clicked. What is happening though is that the function gets fired when the page loads, and not when the button is clicked. Here is my code:

    function Photobank(){
        this.photos;
        this.addPhotoButton;
    }

    Photobank.prototype.init = function(){
        var btn = document.createElement('button');
        btn.id = "photoupload";
        var t=document.createTextNode("ADD PHOTOS");
        btn.appendChild(t);
        this.addPhotoButton = btn;
        var pb = document.getElementById('photobank');
        pb.appendChild(this.addPhotoButton);
        this.addPhotoButton.addEventListener("click", this.launchMediaManager(), false);
    }

    Photobank.prototype.launchMediaManager = function(){
        alert("Launching Media Manager");
    }

Am I doing something noticeably wrong?

Manish Kr. Shukla
  • 4,447
  • 1
  • 20
  • 35
jordan
  • 9,570
  • 9
  • 43
  • 78
  • possible duplicate of [event listener in javascript not firing except for when the page is loaded](http://stackoverflow.com/questions/20970582/event-listener-in-javascript-not-firing-except-for-when-the-page-is-loaded) – Felix Kling Feb 06 '14 at 23:38
  • 2
    You'd surprised how often this is asked. – Felix Kling Feb 06 '14 at 23:42
  • @FelixKling Yeah, looks like that was my problem. Thanks for that link! – jordan Feb 06 '14 at 23:52
  • 1
    And in case you will run into problems with `this`: http://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-context-inside-a-callback ;) – Felix Kling Feb 07 '14 at 00:49

2 Answers2

12

You're calling the function rather than passing the function as an argument to addEventListener. Take the parentheses off the end of the function name:

this.addPhotoButton.addEventListener("click", this.launchMediaManager, false);
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • If you want to add arguments you can by binding them: `root.addEventListener('click', myPrettyHandler.bind(null, event, arg1, ... ));` From: https://stackoverflow.com/a/23024673/3804349 – Petri Feb 27 '19 at 05:56
2

It is because you are invoking the function and setting its result as the handler to the click event, instead set the function reference as the handler.

this.addPhotoButton.addEventListener("click", this.launchMediaManager, false);
PSL
  • 123,204
  • 21
  • 253
  • 243