Skip to content
Advertisement

In Javascript, how do I write one function that will effect multiple buttons, each with their own separate arrays?

I am currently setting up an application with three separate buttons, each which is supposed to randomly select an element from an array specific to that button. I’ve successfully coded it with individual functions for each button, but I was wondering if there is a way to condense it into a single function that can apply to all three buttons.

This is my current Javascript:

JavaScript

And the connected HTML:

JavaScript

Advertisement

Answer

JavaScript
JavaScript

Ok so a few things changed.

  • I extracted the lists of urls out to a map, that can use the id of the button to lookup what urls to use
  • The markup for the buttons and balls changed to have common classes for finds and lookups
  • When a click happens, we get the urls by the button id
  • We then get a random index like was done before
  • We get the random assoicated url for that index
  • We find the ball that is associated with the button contextually by the parent column class
  • And finally we change the ball’s url
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement