Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
151
rated 0 times [  158] [ 7]  / answers: 1 / hits: 5953  / 4 Years ago, mon, september 14, 2020, 12:00:00

I want to do a star rating control but I can't seem to find a way to select all previous siblings on hover. Does such thing even exist or do I have to use javascript?




span {
display:inline-block;
width: 32px;
height: 32px;
background-color:#eee;
}

span:hover {
background-color:red;
}

<span></span>
<span></span>
<span></span>
<span></span>
<span></span>




More From » css

 Answers
3



// obtain all spans from DOM
const spans = document.querySelectorAll('span');
// set a variable at global scope as indicator
let flag = false;

// add event listener to each span
spans.forEach((sp, j)=>{
sp.addEventListener('click', ()=>{
// if clicked, then not dismissing the background colour after mouse leave
flag = true;
// reassign all spans back to original grey
spans.forEach(dsp=>{
dsp.style.backgroundColor = '#eee';
});
// assign bg to red of the spans from 0 to clicked index
Array.from(new Array(j+1), (x, i) => i).forEach(ind=>{
spans[ind].style.backgroundColor = 'red';
});
});
// redo if mouse enters
sp.addEventListener('mouseenter', ()=>{
flag = false;
});
// if any span is hovered
sp.addEventListener('mouseover', ()=>{
// reassign all spans back to original grey
spans.forEach(dsp=>{
dsp.style.backgroundColor = '#eee';
});
// assign bg to red of the spans from 0 to clicked index
Array.from(new Array(j+1), (x, i) => i).forEach(ind=>{
spans[ind].style.backgroundColor = 'red';
});
});
// in moseleave, only save the background colour if click happened
sp.addEventListener('mouseleave', ()=>{
if(!flag){
spans.forEach(dsp=>{
dsp.style.backgroundColor = '#eee';
});
}
});
});

span {
display:inline-block;
width: 32px;
height: 32px;
background-color:#eee;
}

span:hover {
background-color:red;
opacity: 0.8;
cursor: pointer;
}

<span></span>
<span></span>
<span></span>
<span></span>
<span></span>




[#2688] Wednesday, September 9, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
chase

Total Points: 78
Total Questions: 106
Total Answers: 93

Location: Comoros
Member since Tue, Mar 14, 2023
1 Year ago
chase questions
;