I have had two problems so far, setting delays for each of the images and the adresses of the images can sometimes be a different adress than what i wanted.
I am making this on a django template, so I have this as my array:
var data = ["{% static 'kp1.png' %}", "{% static 'kp2.png' %}", "{% static 'kp3.png' %}", "{% static 'kp4.png' %}", "{% static 'kp5.png' %}", "{% static 'kp6.png' %}", "{% static 'kp7.png' %}", "{% static 'kp8.png' %}", "{% static 'kp9.png' %}", "{% static 'kp10.png' %}", "{% static 'kp11.png' %}", "{% static 'kp12.png' %}", "{% static 'kp13.png' %}", "{% static 'kp14.png' %}", "{% static 'kp15.png' %}", "{% static 'kp16.png' %}", "{% static 'kp17.png' %}", "{% static 'kp18.png' %}", "{% static 'kp19.png' %}", "{% static 'kp20.png' %}", "{% static 'kp21.png' %}", "{% static 'kp22.png' %}", "{% static 'kp23.png' %}", "{% static 'kp24.png' %}"]
Here is my html image and button
<img src="https://lh3.googleusercontent.com/a/AGNmyxb_rW-rOVKfMwOH50Wy10CcnROIFLMmjfEcvwGU8g=k-s48" id="kp_img">
<button id="kp_button" onclick="kp_animation()">click me</button>
And if this is what my javascript looks like
function kp_animation(){
for(x in data){
setTimout(() => {
document.getElementById("kp_img").src = "kp" + x + ".png";
},1000)
}
}
The adress i am trying to acsess is http://website/static/kpX.png
But if i am in this domain http://website/domain1/domain2 then it gives me this: http://website/domain1/domain2/static/kpX.png
What is also happening is i am getting the first delay than it jumps to kp24.png and doesn’t do any of the other delays
I would really apreciate it if someone could help
3
Answers
you need to add the delays else all setTimeout be executed almost at the same time and also without making x a local variable for each setTimeout, x will refer to the last value always so a self invoking function would help.
Additionally, make sure the image urls allow CORS to be loaded in a different site.
Not sure how to help you with getting the paths to your images (someone with a fresh memory on Django might help here), but related to your button and the interval – …use setInterval instead of setTimeout.
Also, to loop your images back to the beginning, don’t forget about the modulo operator
%
– it’ll help you to reset the iterating images index back to0
Also, don’t use HTML inline
on*
Event handlers. Use addEventListener() instead.Use async/await for Promise to achieve :