He Developers,
I want to know your opinion about how to wright this code better.
If you click on button star3 it will turend as a yellow star stars underneath are also yellow. The star above star3 is just grey.
Thats what i got and what i need but i want to know how i can be more efficient in my code..
var star = document.getElementById("star-0");
var star1 = document.getElementById("star-1");
var star2 = document.getElementById("star-2");
var star3 = document.getElementById("star-3");
var star4 = document.getElementById("star-4");
var img = 'url(img/star.png)';
var img2 = 'url(img/star2.png)';
star4.addEventListener('click', function(){
star.style.backgroundImage = img2;
star1.style.backgroundImage = img2;
star2.style.backgroundImage = img2;
star3.style.backgroundImage = img2;
star4.style.backgroundImage = img2;
});
star3.addEventListener('click', function(){
star.style.backgroundImage = img2;
star1.style.backgroundImage = img2;
star2.style.backgroundImage = img2;
star3.style.backgroundImage = img2;
star4.style.backgroundImage = img;
});
star2.addEventListener('click', function(){
star.style.backgroundImage = img2;
star1.style.backgroundImage = img2;
star2.style.backgroundImage = img2;
star3.style.backgroundImage = img;
star4.style.backgroundImage = img;
});
star1.addEventListener('click', function(){
star.style.backgroundImage = img2;
star1.style.backgroundImage = img2;
star2.style.backgroundImage = img;
star3.style.backgroundImage = img;
star4.style.backgroundImage = img;
});
star.addEventListener('click', function(){
star.style.backgroundImage = img2;
star1.style.backgroundImage = img;
star2.style.backgroundImage = img;
star3.style.backgroundImage = img;
star4.style.backgroundImage = img;
});
Seems like you are trying to implement rating stars. If you insist on only using JS not using any smarts or meta-data in HTML. Here is the function I would simplify it to: