Need help with a for-loop. I have something like this which I want to simplify:
// clicking btn_100
$('.btn_100').click(function(e) {
// reset all IMG to version -a.gif..
$(".img_100").attr('src','img-100-a.gif');
$(".img_099").attr('src','img-099-a.gif');
$(".img_098").attr('src','img-098-a.gif');
// set IMG_100 ver -b.gif..
$(".img_100").attr('src','img-100-b.gif');
});
// clicking btn_099
$('.btn_099').click(function(e) {
// reset all IMG to version -a.gif..
$(".img_100").attr('src','img-100-a.gif');
$(".img_099").attr('src','img-099-a.gif');
$(".img_098").attr('src','img-098-a.gif');
// set IMG_100 ver -b.gif..
$(".img_099").attr('src','img-099-b.gif');
});
// and so on..
like this maybe:
for(a=1; a<=100; a ) {
// create fns for all btns
$(".btn_" a).click(function() {
// reset all IMG to version -a.gif..
for(i=1; i<=100; i ) {
$(".img_" i).attr("src","image-" i "-a.gif");
};
// reset btn-TXT
$(".btn_" a).text("Play animation");
$(this).text("Pause animation");
// set specific IMG to version -b.gif..
$(".img_" a).attr("src","image-" a "-b.gif");
});
};
-a updates fine, -b doesn't. Is that related to the nested for loops? Do I have to pass a to the function? If I hardwire -b (e.g. -99-b), it works; so doesn't receive and iterate var a..!? Thx.
EDIT: need to toggle the BTN-state as well (Play/Stop); tried smth. using a var playing = false and a conditional if-loop.
CodePudding user response:
Give all of your buttons the same class but with an data-index
attribute indicating where number it relates to
<button class="btn" data-index="100">Button 100</button>
so you can just write this once
$('.btn').on("click", function() {
const index = $(this).data("index");
... some code ...
});
Next, give all of your images the same class, along with a data-index
attribute indicating it's "number"
<img src="whatever.jpg" class="img" data-index="100">
Then you just have to update all at once:
$('.btn').on("click", function() {
const btnIndex = $(this).data("index"); // index of the clicked button
$('.img').each((_,img) => {
const $img = $(img);
const imgIndex =$img.data("index");
const suffix = (btnIndex == imgIndex) ? "b" : "a"
$img.attr("src", `img-${imgIndex}-${suffix}.gif`);
})
});
Live example: