+ 1

I am trying to use js to change dynamiclly the color of circle, many ways and i have failed

var a = document.getElementById("#c1"); var b = document.getElementById("#c2"); var c = document.getElementById("#c3"); a.style.fill='#FF0' function traffic(){ document.getElementById("#c1").style(fill).value = red; } setInterval(traffic, 3000); https://code.sololearn.com/WqL0Kc17f1wK/?ref=app

25th Jan 2019, 6:53 AM
Ahmad Ali
Ahmad Ali - avatar
4 Antworten
+ 1
For getElementById, you must not use a hash (#), so just write it like this... var a = document.getElementById("c1"); Also, sometimes the JavaScript on SoloLearn loads faster than the HTML elements -- so, the code runs but it can't find any elements. To fix it, surround your code with this... window.onload = function(){ //your code here } Those fixes will make the top circle yellow. I don't know what your traffic function is trying to do. If you want help with the animation, just ask.
25th Jan 2019, 7:26 AM
James
James - avatar
+ 3
it's working, thank you so much
25th Jan 2019, 3:45 PM
Ahmad Ali
Ahmad Ali - avatar
+ 2
James thank you very much. if you can check the code now. i want it like the real traffic light so it will the top circle will be red for 3s then switched off and the second one be orange for 3s and so on for ever. can you give me your observations?
25th Jan 2019, 12:59 PM
Ahmad Ali
Ahmad Ali - avatar
+ 1
You could write it like this... function traffic1(){ c.style.fill = "grey"; a.style.fill = "red"; setTimeout(traffic2, 3000); } function traffic2(){ a.style.fill = "grey"; b.style.fill = "orange"; setTimeout(traffic3, 3000); } function traffic3(){ b.style.fill = "grey"; c.style.fill = "green"; setTimeout(traffic1, 3000); } traffic1();
25th Jan 2019, 1:06 PM
James
James - avatar