I successfully created a Javascript function to display a modal on button click, but I realized that I would have to manually repeat the code 56 times. Instead, I attempted to write a loop to automate this process, but unfortunately, the new function is not functioning as intended and I am unsure of the reason behind it.
The initial working function:
var target = document.getElementById('show1');
var currentOpacity = 0;
$(document).ready(function () {
$("#hide1").click(function () {
$("#details1").hide();
target.style.opacity = currentOpacity + 1;
});
$("#show1").click(function () {
$("#details1").show();
target.style.opacity = currentOpacity - 1;
});
});
Instead of repeating the above code block an additional 56 times:
var target = document.getElementById('show1');
var currentOpacity = 0;
$(document).ready(function () {
$("#hide1").click(function () {
$("#details1").hide();
target.style.opacity = currentOpacity + 1;
});
$("#show1").click(function () {
$("#details1").show();
target.style.opacity = currentOpacity - 1;
});
});
var target2 = document.getElementById('show2');
$(document).ready(function () {
$("#hide2").click(function () {
$("#details2").hide();
target2.style.opacity = currentOpacity + 1;
});
$("#show2").click(function () {
$("#details2").show();
target2.style.opacity = currentOpacity - 1;
});
});
would be laborious, so I tried using a loop:
const elements = [];
for (let i = 1; i <= 56; i++) {
$(document).ready(function () {
document.getElementById('hide'+i).addEventListener('click',function ()
{
document.getElementById('details'+i).hide();
document.getElementById('show'+i).style.opacity = currentOpacity + 1; });
document.getElementById('show'+i).addEventListener('click',function () {
document.getElementById('details'+i).show();
document.getElementById('show'+i).style.opacity = currentOpacity - 1; });
});
}
However, the loop approach is not yielding the expected results. Can anyone provide insight into why this might be happening?