I am working on a svelte application and I want to implement row highlighting when a user clicks on it. Here is an example code snippet that demonstrates this functionality:
<div id="A" class="car-even">A</div>
<div id="B" class="car-odd">B</div>
<style>
.car-even {
color: #008800;
cursor: pointer;
}
.car-odd {
color: red;
cursor: pointer;
}
.car-selected {
color: blue;
background-color: #ffffaa;
cursor: pointer;
}
</style>
<script>
row = document.getElementById('A')
row.className = 'car-selected '
</script>
However, I encountered an issue with updating the className correctly in svelte. Can you help me identify what is wrong?
App.svelte
<script>
import Car from './cars.svelte'
let car = ''
$: console.log('Car', car)
</script>
<Car bind:selected_car={car}/>
Cars.svelte
<script>
let cars = ['Audi', 'BMW', 'Hillman', 'Hyundai', 'Jaguar']
export let selected_car = ''
let car_class = ['car-even', 'car-odd']
function carClicked(car) {
selected_car = car
let car_row = document.getElementById(car)
car_row.className = 'car-selected'
}
</script>
{#each cars as car, index (car)}
<div id={car} class="{car_class[index % 2]}" on:click={() => carClicked(car)}>{car}</div>
{/each}
<style>
.car-even {
color: #008800;
cursor: pointer;
}
.car-odd {
color: #000088;
cursor: pointer;
}
.car-selected {
background-color: #ffffaa;
cursor: pointer;
}
</style>