AMGitsKriss
AMGitsKriss

Reputation: 55

Abstracting the mouse click listener in Javascript

So far I have something like the following, where each button on a page is given a unique ID (one, two, three, etc):

$(document).ready(function(){
    $("#one").click(doThing);
    $("#two").click(doThing);
    $("#three").click(doThing);
    $("#four").click(doThing);
});

function doThing(){
    $("#textbox").prepend("<p>Clicked " + this.id + "</p>");
}

Is there a way to condense down the growing list of click listeners, so I don't have to repeat myself for each button, while still returning the appropriate ID?

Upvotes: 1

Views: 32

Answers (1)

Ruan Mendes
Ruan Mendes

Reputation: 92274

You could add a class to all the elements that will have the click applied to.

$(document).ready(function(){
    $(".do-thing-el").click(function(){
         $("#textbox").prepend("<p>Clicked " + this.id + "</p>");
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="do-thing-el" id="one">Something</p>
<p class="do-thing-el" id="two">Else</p>
<p class="do-thing-el" id="three">Goes</p>
<p class="do-thing-el" id="four">Here</p>
<hr />
<div id="textbox"> <div>

Upvotes: 3

Related Questions