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:
var altConcert = [
"Concert 1",
"Concert 2",
"Concert 3",
"Concert 4",
"Concert 5",
"Concert 6"
];
var imgConcert = [
"https://via.placeholder.com/101/000000",
"https://via.placeholder.com/102/000000",
"https://via.placeholder.com/103/000000",
"https://via.placeholder.com/104/000000",
"https://via.placeholder.com/105/000000",
"https://via.placeholder.com/106/000000"
];
var altSport = [
"Sport 1",
"Sport 2",
"Sport 3",
"Sport 4",
"Sport 5",
"Sport 6"
];
var imgSport = [
"https://via.placeholder.com/101/0000FF",
"https://via.placeholder.com/102/0000FF",
"https://via.placeholder.com/103/0000FF",
"https://via.placeholder.com/104/0000FF",
"https://via.placeholder.com/105/0000FF",
"https://via.placeholder.com/106/0000FF"
];
var count = 0;
$(".load-more-concerts").click(function() {
//Load the next 3 images
for (i = 0; i < 3; i++) {
$("#extraConcert").append(
'<div">' +
'<h3>'+altConcert[count]+'</h3>' +
'<img src="'+imgConcert[count]+'" alt="'+altConcert[count]+'"/>' +
'</div>');
count++;
}
//Scroll to the top (+100px) of the newly loaded images
$('<div id="new-concert-div'+count+'"> </div>').appendTo('#extraConcert');
$('body, html').animate({ scrollTop: $('#new-concert-div'+count+'').offset().top - 100}, 1000);
//Remove the "View More" button when out of images
if (count >= imgConcert.length) {
$(".view-more-concerts").css("display", "none");
return;
}
});
#Concerts { float: left; padding-right: 100px; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="Concerts">
<div id="extraConcert">
<div id="new-concert-div1"> </div>
</div>
<div class="load-more-concerts">
<button class="view-more-concerts">View More Concerts</button>
</div>
</div>
<div id="Sports">
<div id="extraSports">
<div id="new-sports-div1"> </div>
</div>
<div class="load-more-sports">
<button class="view-more-sports">View More Sports</button>
</div>
</div>
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.