Passing a parameter to an anonymous self-invoking function

I have the need to show different information depending on which link has been pressed (a list of clients as it happens). I have it working for 2017 and I could repeat the function for every other year but is it possible to pass the year as a parameter to an anonymous self-invoking function so I only have the function code once?

Edit: Of course, there may be a better way of achieving what I’m after…

I have a codepen at:

Instead of iterating over those spans, you might store the target which should be shown in a data attribute (say data-show="#c2017" etc.), and bind only one event listener to the parent element. Then you can check if the has such a data attribute, and show the corresponding div, like e.g.

<p id="clients">Clients:<br>
  <span id="p2017" data-show="#c2017">2017</span> | 
  <span id="p2016" data-show="#c2016">2016</span> | 
  <span id="p2015" data-show="#c2015">2015</span> | 
  <span id="p2014" data-show="#c2014">2014</span> | 
  <span id="p2013" data-show="#c2013">2013</span> | 
  <span id="p2012" data-show="#c2012">2012</span>
  .addEventListener('click', function (event) {
    const target =
    if (!target.matches('[data-show]')) return

    hideAll() // sets all div's to display: none
      .display = 'block'


Ah cool! Many thanks @m3g4p0p. I didn’t think of using a data attribute. Nice job! :slight_smile:

1 Like

I have updated my Codepen and have made the links appear like a href links. It works fine but I want to make one addition, to change the colour of a “link” when it is effectively active.

The line I have added is clearly not what I want but it proves part of the concept. Instead of getElementById('c2016x') I want to select the element with the same id as the data-show value but without the # and with x on the end - and this is where I am flummoxed. :upside_down:

But we already have a reference to the clicked element. :-)

  .color = 'blue';
1 Like

As simple as that! Cool. Thanks again @m3g4p0p

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