Calling something once when there are multiple instances on a page


I’m creating an accordion which has a CSS class of .accordion which I’m targeting. The code works fine, however the issue is that if more than once accordion is on the page, it triggers the click event twice or more depending on the number of accordions. Is there a way in which I can only trigger the click once on the item I’ve clicked on only? Here’s the code

I’m guessing it would need an each loop to count how many instances of the accordion are on the page, put them into an array and assign the the values. I’m a bit unsure of how to do this, so any help would be appreciated.

Thanks in advance.

Easiest way would be to simply determine the element that was clicked on from within the event listener and to process against that specific one regardless of any class or id attached to it.

Are you able to write an example of this, as I’m not too sure exactly how you mean?

see for how to test what element in a page triggered an event.

See for a live example of how this can work - it shows an 8x8 board where the clicked on square changes colour but where there is only one event listener attached to the entire 8x8.

Is that true?

Bear with me I’m learning myself but surely even though you are adding events to more than one item there will only be one click event when that item is clicked? Perhaps @felgall can confirm.

I also assume that you could instead add the click event to a parent (or the body) and then check to see if the element that was clicked was your accordion.


var accordion = (function() {
    var init = function() {

    var toggleAccordion = function(e) {
		 if (( === "DT" && $('dl').hasClass('accordion')){

    return {
      init: init


Bear in mind I’m using this as a learning exercise also :smile:

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.