I have two buttons, when the user clicks on them, it is underlined. However, I would like .underline to be animated / slide horizontally to the button the button is pressed on.
Demo: https://jsfiddle.net/ds1wr736/11/
As now, under the button appears and disappears when the button is pressed. How can I animate this to smoothly slide (change x values) onto a selected button without hacks and jQuery?
function switchTab(tab) { if (tab === 1) { document.getElementById("tab2").classList.add("underline"); document.getElementById("tab1").classList.remove("underline"); } else if (tab === 2) { document.getElementById("tab1").classList.add("underline"); document.getElementById("tab2").classList.remove("underline"); } }
.bar { background-color: gray; padding: 20px; } .underline { border-bottom: 5px solid red; } button { width: 100px; height: 50px; background-color: white; } button:focus { outline: none; }
<div class="bar"> <button id='tab1' class="underline" onclick='switchTab(2)'>Tab 1</button> <button id='tab2' onclick='switchTab(1)'>Tab 2</button> </div>
source share