I'm trying to implement an effect similar to the StackOverflow effect when you visit a post and the answer has an orange background that fades out. Example: How do I add a class to a given element?
My approach looks something like this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Highlight element based on URL hash example</title>
<style>
/*
Custom class to be applied to our element.
*/
.focused {
padding: 5px;
border-radius: 30px;
box-shadow: 0px 0px 30px #9FC43E;
animation: fade-out-in 5s;
animation-fill-mode: forwards;
}
/*
Add keyframes to our fade out effect
*/
@keyframes fade-out-in {
0% {
border-radius: 30px;
box-shadow: 0px 0px 30px #9FC43E;
}
100% {
border-radius: 0px;
box-shadow: 0px 0px 0px transparent;
}
}
</style>
</head>
<body>
<section style="max-width: 768px">
<div id="target">
This element will be highlighted on load.
</div>
</section>
<script>
// Highlight the target based on the URL
var anchor_id = window.location.href.split('#');
var target = document.getElementById(anchor_id['1']);
target.className += ' focused';
</script>
</body>
</html>
This works for the first visit, but if the user clicks on a new anchor on the same page, or changes the URL fragment in the address bar, the class remains on the old element.
I'm looking for a way to move it every time the URL changes like that.
Thanks in advance.