Jason Chen Jason Chen - 3 months ago 11
Javascript Question

add variables to a JavaScript event call?

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

HTML

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


JS

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


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

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

JSFiddle
https://jsfiddle.net/7cLu9uah/

Answer

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>
</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>

Comments