JSFiddle - React, Tailwind, and code Playground
HTML
<button id="highlight_trigger">Highlight</button>
<span id="to_highlight">This text is what I want to highlight</span>
CSS
#to_highlight {
display: inline-block;
position: relative;
}
#to_highlight.highlighted, .highlight_box {
background-color: yellow;
}
.highlight_box {
display: block;
position: absolute;
top: 0; bottom: 0; left: 0;
z-index: -1;
}
JavaScript
$('#highlight_trigger').on('click', function() {
var toHighlight = $('#to_highlight');
if(toHighlight.hasClass('highlighted')) {
highlightAnimation(toHighlight, false, 500);
} else {
highlightAnimation(toHighlight, true, 500);
}
});
function highlightAnimation($elem, show, duration) {
var startPos;
var endPos;
if(show) {
startPos = '100%';
endPos = '0%';
} else {
startPos = '0%';
endPos = '100%';
$elem.removeClass('highlighted');
}
var highlight = $('<div />').addClass('highlight_box').css('right', startPos);
$elem.append(highlight);
highlight.animate({right: endPos}, duration, function() {
highlight.remove();
if(show) {
$elem.addClass('highlighted');
}
});
}