I want to switch multiple colors in a page like theme change. I successfully changed text color, text background color, shapes color, button color etc. But I also want to change hover color.
This is the html code:-
<ul class="color-changer"> <li><a href="#" id="red">RED</a></li> <li><a href="#" id="green">GREEN</a></li> <li><a href="#" id="blue">BLUE</a></li> </ul>
This code works:-
<script> $('#red').click(function () { $('.sidebar button').css({ 'background-color': 'red' }); $('.text-color').css({ 'background-color': 'red' }); $('.shape-left').css({ 'background-color': 'red' }); }); </script>
But this dont work:-
<script> $('#red').click(function () { $('.sidebar button:hover').css({ 'background-color': 'red' }); }); </script>
Please help me. I dont know how to solve it.
Answer
Here is a solution using CSS variables changed through Javascript. I’ll recommend you read the documentation to better understand what is happening here.
let themes = { red: { '--sidebar-bg': '#FFAEBE', '--sidebar-a-color': '#88001B', '--sidebar-a-hover-color': '#FF0033', }, green: { '--sidebar-bg': '#BBFFAE', '--sidebar-a-color': '#148800', '--sidebar-a-hover-color': '#3DFF00', }, blue: { '--sidebar-bg': '#AEEFFF', '--sidebar-a-color': '#006E88', '--sidebar-a-hover-color': '#00CEFF', }, }; $('.color-changer').on('click', 'a', (e) => { e.preventDefault(); let theme = $(e.target).data('theme'); setSidebarTheme(theme); }); function setSidebarTheme(theme) { let sidebar = $('#sidebar')[0]; // Get the raw Element, not jQuery for(let [prop, value] of Object.entries(themes[theme])) { // set value to the CSS variable sidebar.style.setProperty(prop, value); } } // initial theme setSidebarTheme('blue');
#sidebar { padding: 20px; } #sidebar { background: var(--sidebar-bg); } #sidebar a { color: var(--sidebar-a-color); } #sidebar a:hover { color: var(--sidebar-a-hover-color); }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="sidebar"> <ul class="color-changer"> <li><a href="#" data-theme="red">RED</a></li> <li><a href="#" data-theme="green">GREEN</a></li> <li><a href="#" data-theme="blue">BLUE</a></li> </ul> </div>