Skip to content
Advertisement

Dynamically select which array to run through funciton

I am trying to make a jQuery function dynamically decide which array gets run through it based on a button click. Ideally, this is how it would work:

  • User clicks one of the “View More …” buttons.
  • The program loads the next 3 images of that specific category (Sports, Concerts, etc.).

Below is a version of that function working, but, only for the Concerts section:

JavaScript
JavaScript
JavaScript

Is there a way that I could use the ID name (“Sports” or “Concerts”) of a div or perhaps pass the array as a parameter to the jQuery function? Or is there some other easier method to solving this that I am completely missing? I am confident I could get this to work if I just duplicated the function with different names, but I am trying to follow the DRY Principle.

Advertisement

Answer

You can use data html attributes to achieve what you are looking for.

And in your js file you can just get those data attributes and validate them as i did in the code below.

JavaScript
JavaScript
JavaScript

In my code im getting the data attribute that has been clicked in that case i’ve used data-target, data-alt and data-img.

  • data-target will the target using an id.
  • data-alt will be the alt array.
  • data-img will be the img array.

In javascript code i’ve used window to get the variables from the data-* string returned.

It starts to throw undefined when the count is bigger then the array length, but this can made with a validation like if(alt[count] !== undefined).

More information about data attributes can be found here: https://www.w3schools.com/tags/att_data-.asp

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement