I am a beginner with Javascript and I am still experimenting with how things work. My knowledge is very limited. Excuse me if I phrase something falsely.
I am trying to make a dynamic system in which the length of an array prints out an amount buttons accordingly. My issue lies on the buttons' function. I want each button to change the src of an image according to the array I made once clicked.
eg:
Here's how my code looks thus far:
HTML:
<img src="#" id="diplayimg">
<div class="charskins">
<p><span id="data_skins"></span></p>
</div>
JS:
//this is the default src the image is going to have
let diplayimgPath = 'imagedef.png';
//name = text displayed on the new button and url = the new src of the image
let skinsData = {
skins: [
{ name: 'Skin 0', url: 'image1.png' },
{ name: 'Skin 1', url: 'image2.png' }
//Note that there can be added as many arrays of objects as I like here
]
}
let defaultskin = '<button onclick="changeSkinDef()">Default</button>';
function changeSkinDef() {
document.getElementById("diplayimg").src = diplayimgPath;
}
if (document.getElementById("data_skins")) {
function changeSkinNew() {
skinspathFinal = '';
for (let i = 0; i < skinsData.skins.length; i++) {
let skinimg = document.getElementById("diplayimg");
skinimg.setAttribute("src", skinsData.skins[i].url);
skinspathFinal += skinimg;
}
return skinspathFinal;
}
function printSkins(){
let skinsFinal = '';
for (let i = 0; i < skinsData.skins.length; i++) {
skinsFinal += '<button onclick="changeSkinNew()">' + skinsData.skins[i].name + '</button>';
}
return defaultskin + skinsFinal;
}
document.getElementById("data_skins").innerHTML= printSkins();
}
The buttons are printed normally with their given "names". The new urls of the images are read correctly too, however the new buttons change the src of the image only to one specific url I have set in the objects' array.
eg:
I reckon the changeskinNew()
function is causing the problem, since all new buttons activate the same function once clicked, but I have no clue how I can make the functions dynamic as well.
Any suggestions on how I can make this work?
ps: I have tried using the forEach
and createElement
method to manually create the buttons, but it did not seem to work either.
it because when you iterate in loop in function changeSkinNew, you will always set src to value of the last element in array, you can just send value you want to set as src to changeSkinNew as parameter like this
function changeSkinNew(e) {
skinspathFinal = '';
let skinimg = document.getElementById("diplayimg");
skinimg.setAttribute("src", e);
skinspathFinal += skinimg;
return skinspathFinal;
}
function printSkins(){
let skinsFinal = '';
for (let i = 0; i < skinsData.skins.length; i++) {
skinsFinal += `<button onclick="changeSkinNew('${skinsData.skins[i].url}')">${skinsData.skins[i].name }</button>`;
}
return defaultskin + skinsFinal;
}