If you're seeing this message, it means we're having trouble loading external resources on our website.

If you're behind a web filter, please make sure that the domains *.kastatic.org and *.kasandbox.org are unblocked.

Main content

Summary: DOM events

Adding event listeners

To make sure that the browser calls a particular function when an event happens on an element, you must use document.addEventListener:
var buttonEl = document.getElementById("clicker");
var onButtonClick = function() {
    console.log("Oh golly gosh, you clicked me");
};
buttonEl.addEventListener("click", onButtonClick);
You can pass many valid strings as the first argument, see the event types article.
If you want information about the event that happened, you can look at the event object that the browser passes to your callback function:
var faceEl = document.getElementById("face");
var onFaceClick = function(e) {
    console.log("You clicked " + e.clientX + " , " + e.clientY);
};
faceEl.addEventListener("click", onFaceClick);
There are many properties on the event object, you can see a full list here.
If you are overriding click behavior on a link or submit behavior on a form, you may want to call event.preventDefault() to prevent the browser's default behavior.

Removing event listeners

If you no longer need a particular event listener, you can remove it using removeEventListener:
var faceEl = document.getElementById("face");
var onFaceClick = function(e) {
    console.log("You clicked " + e.clientX + " , " + e.clientY);
};
faceEl.addEventListener("click", onFaceClick);
// later...
faceEl.removeEventListener("click", onFaceClick);

Want to join the conversation?

  • piceratops ultimate style avatar for user Shantanu Kamat
    What programming languages do you know, Pamela?
    Do you know if Khan Academy will teach jQuery or C++ any time soon.
    (34 votes)
    Default Khan Academy avatar avatar for user
  • aqualine ultimate style avatar for user Yvonne Nillissen
    "There are many properties on the event object, you can see a a full list here." thought I would see a list that includes clientX and clientY here. What is this list and what am I missing?
    (11 votes)
    Default Khan Academy avatar avatar for user
    • leafers ultimate style avatar for user Ricky Buchanan
      The linked web page only lists the properties that ALL types of events have. The list up the top is specific types of events - if you go to check out "MouseEvent" you'll find the clientX and clientY properties there.

      It wouldn't make sense to have a clientX and clientY on a event to tell you the page had loaded, that there had been an error, or the previous window had been closed, for example - they only show up for events that it makes sense for.
      (12 votes)
  • purple pi purple style avatar for user LC
    I'm stuck in the Pet The Cat challenge, where click on cat-pic causing you see "meow"
    What logic is missing?
    var cat = document.getElementById("cat-pic")
    var chat = document.getElementById("cat-chat")
    var onCatClick = function(){
    chat.textContent = "meeow";
    cat.addEventListener("click", onCatClick);
    };
    Sometimes resolving a problem requires help from others....Thanks in advance!
    (3 votes)
    Default Khan Academy avatar avatar for user
  • aqualine ultimate style avatar for user Renaeus VII
    A general HTML/JS question:

    I have a variable, 'counter = 600'. I also have four buttons. I can change the value of 'counter' to 500, 600, 650, and 700 by clicking the buttons.

    I want the current value of 'counter' to be displayed on my webpage. I used 'document.write' to display it, however, when I click the buttons, although 'counter' is set to the new value, the displayed number does not. I believe it is because the 'document.write' is only called once and does not check to see if 'counter' has changed. Is there anything I can do to get the 'document.write' to update to the new value?
    (4 votes)
    Default Khan Academy avatar avatar for user
  • starky tree style avatar for user I.T.Beauregard
    Is anyone else finding that the "Onwards" button isn't popping up on the "Processing forms with events" and "Preventing default behavior of events" once you finish the videos? I'm watching the videos straight through. I enjoy seeing my progress recorded and I'm feeling frustrated that my achievements won't record.
    (3 votes)
    Default Khan Academy avatar avatar for user
  • blobby green style avatar for user Logan Mullennex
    Very big question, very confusing problem. Would love some help on this one!

    I want to make it easy to call any id from a large selection with only a few commands. Here's what I have so far.

    I am making an array of objects for my computer build. Each part has a name, a div, a button, and an input, all of which have their own id. This way I can treat each part as it's own "button/input/text box" combo. Here's my (kind of large) array of objects:

    var partBoxIds = [

    {name: "CPU", div: "cpu-div", button: "cpu-button", input: "cpu-input"},

    {name: "Motherboard", div: "motherboard-div", button: "motherboard-button", input: "motherboard-input"},

    {name: "RAM", div: "ram-div", button: "ram-button", input: "ram-input"},

    {name: "Graphics Card", div: "gpu-div", button: "gpu-button", input: "gpu-input"},

    {name: "Storage SSD/HDD", div: "ssd-div", button: "ssd-button", input: "ssd-input"},

    {name: "Power Supply", div: "power-div", button: "power-button", input: "power-input"},

    {name: "Cooling System", div: "cold-div", button: "cold-button", input: "cold-input"},

    {name: "Computer Case", div: "case-div", button: "case-button", input: "case-input"},

    {name: "Tips/things to know", div: "tips-div", button: "tips-button", input: "tips-input"}
    ];

    I wanted to create 3 variables for each part that stores the specific element (div, button, and input). I also want the variable name to be some variation of the part name as well (similar to the id's).

    I created a constructor function that allows me to input the array index and propertyName.

    var elementFinder = function(index, propertyName){
    this.index = index;
    this.propertyName = propertyName;
    };

    Then I made a prototype that finds the id of the given properties.

    elementFinder.prototype.find = function(){
    document.getElementById(partBoxIds[index].propertyName);
    };

    Now, for the question.

    Is it possible to use a nested for loop to create all the variables for me in such a way that they have distinguished and predictable names, as well as changing this.index and this.propertyName values without running into trouble?

    I have tried this out

    for (var i = 0; i < 9; i ++){
    for (var j = 1; j < 4; j++){
    var partBoxes[i].name = new elementFinder(i, j);
    console.log(partBoxIds[i].names);
    }
    };

    I know it would try to create three variables with the same name if it actually worked, but it won't let me make a square bracket [] inside a variable name. Is it even possible to make something like this work?
    (3 votes)
    Default Khan Academy avatar avatar for user
  • piceratops sapling style avatar for user nlambert19
    i had a problem with mad libs challenge it said i needed to use longer words? why do i have to use longer word to progress through the challenge
    (1 vote)
    Default Khan Academy avatar avatar for user
  • spunky sam blue style avatar for user Can't leave empty
    I still don't understand much.
    What should I do?
    (1 vote)
    Default Khan Academy avatar avatar for user
  • primosaur tree style avatar for user Masha
    How can I use class names instead of ids to apply the event listener to multiple elements? For example, I want to make something similar to the Cat Clicker challenge but with many images, so that text appears each time one of the images is hovered on.
    (1 vote)
    Default Khan Academy avatar avatar for user
  • leaf yellow style avatar for user thepahntomninja
    How would I make a button go to another page?
    (1 vote)
    Default Khan Academy avatar avatar for user