I am a student and very new to JS. I need to display new advert images on the page each time the users re visits the page. I was thinking of storing the img src path in an array go from there. I have got it working but the code isnt very efficient. Can anyone let me know how I could improve my code and what would be a better way of doing this? Thanks.
var content = document.getElementById("advert-content");
//storing the ads img src into an array
var adverts = ["Assets/pineapple.jpg", "Assets/conf.jpg", "Assets/balloonsad.jpg"];
function getRand() {
return Math.floor(Math.random() * Math.floor(3));
}
function setAd(){
//check if the localstorage add exists and
if (localStorage.ad == 0){
content.setAttribute("src", adverts[1]);
}
else if (localStorage.ad == 1) {
content.setAttribute("src", adverts[2]);
}
else if (localStorage.ad == 2) {
content.setAttribute("src", adverts[0]);
}
}
function update(){
// if nothing is stored in the local storage display the first advert image
if (!localStorage.ad){
content.setAttribute("src", adverts[0]);
}
else {
setAd();
let randnum = getRand();
//get a different number than the one stored inside the local storage
while (randnum == localStorage.ad) {
randnum = getRand();
}
// update the image with a different number
localStorage.ad = adverts.indexOf(adverts[randnum]);
}
}
//call function
update();
<section id = "adverts">
<img id="advert-content"/>
</section>