Jason Chen Jason Chen - 8 months ago 37
Javascript Question

add variables to a JavaScript event call?

I am wondering if it is possible to do something like so:


<div id="myspace" class="thing"></div>
<div id="mytable" class="thing"></div>


document.getElementById('my'+this).on('click', function(){
document.getElementById(this).innerHTML = 'Chosen';

The logic is that there are two boxes, first being
, second being
. Upon clicking one of either, the box's innerHTML will read

Basically, I would like to see if I can avoid having to write multiple click events and/or if statements.



You can do this with delegated event handling by attaching a common event handler to a parent and then operate on the clicked on item from the one click handler.

document.getElementById("container").addEventListener('click', function(e) {
    e.target.innerHTML = 'Chosen';
.thing {width: 100px; height: 20px; background:red; margin: 10px;}
<div id="container">
<div id="myspace" class="thing"></div>
<div id="mytable" class="thing"></div>

Also, in your code, you were trying to use .on() on a DOM element. That does not work. Perhaps you were confusing plain Javascript with jQuery which does have a .on() method.

And, document.getElementById() takes a string which should match the id of the element you are trying to find. Your code ocument.getElementById('my'+this) is not a proper usage.

DOM manipulations like this are often simpler using the jQuery library and you seem to be attempting to use some jQuery syntax with .on(). Here's what you could do in jQuery:

$(".thing").on("click", function() {
    this.innerHTML = "chosen";
.thing {width: 100px; height: 20px; background:red; margin: 10px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="myspace" class="thing"></div>
<div id="mytable" class="thing"></div>