Reputation: 59
I need to create click handlers for several HTML buttons that control an image gallery. Each of the buttons in the HTML receive a class that indicates which function to perform - such as step forward or step backward. I also need to create these handlers for multiple galleries on the same web page.
This is the "hard coded" version. Is it possible to create a dynamic function(s) to replicate this working example below?
$('.gallery0_stepForward').on('click', function() {
gallery_changeImage(0, 1); // step gallery 0 forward 1 image
gallery_stopAutoTimer(0); // stop the automatic slide show
});
I have attempted something like this:
for (i=0;i<5; i++){ // 5 galleries in this example
var target = ".gallery" + i + "_stepForward";
var fnName = "stepForward" + i;
function setFunc ( fnName ) {
this[ fnName ] = function() {
console.log('hello ' + fnName);
gallery_changeImage(i, 1);
gallery_stopAutoTimer(i);
};
}
$(target).on('click', fnName);
}
The system of attaching classes to the HTML must remain. The function "gallery_changeImage(val,val)" must remain as there are multiple lines of code in that function. Thank you.
Upvotes: 0
Views: 39
Reputation: 53536
It is hard to tell exactly what you are doing, with so little code, but I would suggest attaching an event to the parent container, listening to clicks on your images, and using data-*
attributes on your elements to control behaviour. For example :
<div class="image-gallery" data-gallery-index="0">
<img src="...">
<img src="...">
<!-- more images -->
</div>
<div class="image-gallery" data-gallery-index="1">
<img src="...">
<img src="...">
<!-- more images -->
</div>
$(function () {
$('.image-gallery').on('click', 'img', function () {
// the `this` keyword is the clicked <img> element
var imgGalleryIndex = $(this).closest('.image-gallery').data('gallery-index');
// step gallery imgGalleryIndex forward 1 image
gallery_changeImage(imgGalleryIndex, 1);
// stop the automatic slide show
gallery_stopAutoTimer(0);
});
});
Using this technique, you donn't need to add click handlers directly to images and it will handle click on any children of your gallery containers as JS events bubble and this is a jQuery feature.
Upvotes: 2