Search code examples
javascripthighlight

Highlight text temporarily


I'm trying to create an internal link to scroll to bottom highlight a tag. When I try the code above it doesn't highlight, I have to refresh the page to make it work.

<p>Fındık eski Çin yazmalarında anlaşıldığına göre yaklaşık 5.000
    yıllık bir geçmişi olan Avrupa'nın mistik
    <sup><a href="#mistisizm">[1]</a></sup> ve orta çağlardan, Romalılardan...

<script>
function highlight(elemId){
  var elem = $(elemId);
  elem.css("backgroundColor", "#ffffff"); // hack for Safari
  elem.animate({ backgroundColor: '#ffffaa' }, 1500);
  setTimeout(function(){$(elemId).animate({ backgroundColor: "#ffffff" }, 3000)},1000);
}

if (document.location.hash) {
  highlight(document.location.hash);
}
$('a[href*=#]').click(function() {
  var elemId = '#' + $(this).attr('href').split('#')[1];
  highlight(elemId);
});
</script>

How can I make this snippet work without reloading the page?


Solution

  • You have multiple issues here. Your css selector attribute name needs to be in quotes. Without it the code gives

    Uncaught Error: Syntax error, unrecognized expression: a[href*=#"]


    Second, when you select an element with JQuery, it returns list of elements, but `animate` has to be called implicitly for single elements, so fixed code looks like this:
    <script>
        function highlight(elemId){
            let elem = $(elemId);
            elem.css("backgroundColor", "#ffffff"); // hack for Safari
            elem[0]?.animate({ backgroundColor: '#ffffaa' }, 1500);
            setTimeout(function(){elem[0]?.animate({ backgroundColor: "#ffffff" }, 3000)},1000);
        }
    
        if (document.location.hash) {
            highlight(document.location.hash);
        }
        $('a[href*="#"]').click(function() {
            let elemId = '#' + $(this).attr('href').split('#')[1];
            highlight(elemId);
        });
    </script>
    

    Also, no need to use var. Use let or const. And in the setTimeout there is no need to select the element by ID again. Just take the elem.
    FYI - the ?. makes sure not to call the function if the element with ID doesn't exist. That is called optional chaining