In this javascript code below there are two icons. fa-circle-pause
and fa-circle-play
.
When a user clicks the play icon in any one of the rows in the table, it is updated with the icon fa-circle-pause
. I have been able to do that for the single rows.
But I am not able to update the rest of the rows in the table with the icon fa-circle-play
.
How can I do that using just the javascript?
const data = [{
Name: 'Chapter 1',
TrackId: 1
}, {
Name: 'Chapter 2',
TrackId: '2',
}, , {
Name: 'Chapter 3',
TrackId: '3',
}, , {
Name: 'Chapter 4',
TrackId: '4',
}]; // any json data or array of objects
const tableData = data.map(function(value) {
return (
`<tr>
<th scope="row">
<span data-track-id='${value.TrackId}' class="play-button btn">
<i class="fa-solid fa-circle-play"></i>
</span>
</th>
<td>${value.Name}</td>
</tr>`
);
}).join('');
const tabelBody = document.querySelector("#tableBody");
tableBody.innerHTML = tableData;
const pauseIconClassName = 'fa-circle-pause'
const playIconClassName = 'fa-circle-play'
const btns = document.querySelectorAll('.play-button')
function onChange(event) {
// get the button elememt from the event
const buttonElement = event.currentTarget.querySelector('i');
const isPlayButton = buttonElement.classList.contains(playIconClassName)
if (isPlayButton) {
buttonElement.classList.remove(playIconClassName)
buttonElement.classList.add(pauseIconClassName)
} else {
buttonElement.classList.remove(pauseIconClassName)
buttonElement.classList.add(playIconClassName)
}
}
btns.forEach(btn => {
btn.addEventListener('click', onChange)
})
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" rel="stylesheet" />
<table border="2">
<thead class="thead-dark">
<tr>
<th scope="col">#</th>
<th scope="col">Track</th>
</tr>
</thead>
<tbody id="tableBody">
</tbody>
</table>
from Toggle icon class across all the rows in the table
No comments:
Post a Comment