I'm trying out a dark mode in my app where there is a table with data. For some reason I have to set the table row background hover color with Javascript. Now there is only one background hover color for both dark and light mode. For example, if my background hover effect is set to red with Javascript for the light mode, then it is red for dark mode also, which looks horrible. If I put the mouseout
and mouseover
events inside the if statements
in switchTheme
function, it doesn't work.
What I want is to set the background hover color to be different according to the mode I am on. If I'm on light mode, I'll have say, red/white hover background color and when I'm on dark mode, it will automatically change to say, blue/green.
This is the snippet:
const toggleSwitch = document.querySelector('#dark-mode-button input[type="checkbox"]');
function switchTheme(e) {
if (e.target.checked) {
document.documentElement.setAttribute('data-theme', 'dark');
}else {
document.documentElement.setAttribute('data-theme', 'light');
}
}
toggleSwitch.addEventListener('change', switchTheme, false);
$("body").on("mouseover", "table tr", function() {
$(this).css("background", "red");
});
$("body").on("mouseout", "table tr", function() {
$(this).css("background", "#fff");
});
:root {
--primary-color: #495057;
--bg-color-primary: #F5F5F5;
}
body{
background-color: var(--bg-color-primary);
}
[data-theme="dark"] {
--primary-color: #8899A6;
--bg-color-primary: #15202B;
}
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
background-color: #fff;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="dark-mode-button">
<input id="chck" type="checkbox">Dark Mode
<label for="chck" class="check-trail">
<span class="check-handler"></span>
</label>
</div>
<table class="table">
<thead>
<tr>
<th>Header 1</th>
<th>Header 2</th>
<th>Header 3</th>
</tr>
</thead>
<tbody>
<tr>
<td>Alfreds Futterkiste</td>
<td>Maria Anders</td>
<td>Germany</td>
</tr>
<tr>
<td>Centro comercial Moctezuma</td>
<td>Francisco Chang</td>
<td>Mexico</td>
</tr>
<tr>
<td>Island Trading</td>
<td>Helen Bennett</td>
<td>UK</td>
</tr>
<tr>
<td>Laughing Bacchus Winecellars</td>
<td>Yoshi Tannamuri</td>
<td>Canada</td>
</tr>
<tr>
<td>Magazzini Alimentari Riuniti</td>
<td>Giovanni Rovelli</td>
<td>Italy</td>
</tr>
</tbody>
</table>