StackOverflow comment's html anchor such as "http://SO/...#comment41994753_26699358"

166 Views Asked by At

I found SO's comment can be anchored and difficult for me to understand the implement. The following link is an example anchoring a comment:

http://SO/questions/26696064/slug/26699358?noredirect=1#comment41994753_26699358

From my understanding about html, comment41994753_26699358 after # must be existed in the html page, but I did not find the id or name in it. When I read the source code I only find the relative source code:

<div id="comments-26699358" class="comments ">
        <table>
            <tbody data-remaining-comments-count="0" data-canpost="true" data-cansee="false" data-comments-unavailable="false" data-addlink-disabled="false">
               <tr id="comment-41994753" class="comment ">

This snippet only tells me two relative and separated ids id="comment-41994753" and id="comments-26699358", the final anchor comment41994753_26699358 is generated from them? Or this is relative to the framework SO used?

2

There are 2 best solutions below

3
On BEST ANSWER

It's no browser behavior, the orange background color and its scroll into view happens with JavaScript.

The code is in this file: http://cdn.sstatic.net/Js/full.en.js
The non-minified version: http://dev.stackoverflow.com/content/js/full.js

The important functions are onHashChange_HighlightDestination and doHighlight:

onHashChange_HighlightDestination:
It parses the hash argument, e. g. #comment49509148_30726127 and calls the highlight method afterwards.

// answers have the form 'lies-like/58534#58534'; comments are 'lies-like/58534#comment60949_58534'
var match = decodeURI(url).match(/#(\d+|comment(\d+)_(\d+))/i);
if (!match) return; // moderator viewing a flagged question, e.g. 'lies-like#question'

if (match[2])
    highlightComment(match[2], match[3]);
else
    highlightAnswer(match[1]);

doHighlight: This method finally highlights it (orange background) and scrolls the comment/answer into view with the function scrollIntoView.

var doHighlight = function (jEle) {
    var originalColor = backgroundColor;
    jEle
        .css({ backgroundColor: highlightColor })
        .animate({ backgroundColor: originalColor }, 2000, 'linear', function () { $(this).css('background-color', ''); });

    if (jEle.is('.comment'))
        jEle[0].scrollIntoView(true);
};
2
On

The answer lies in the onHashChange_HighlightDestination function in the javascript code, which is called from the init method, which fires on every request.

As you can see in the developer edition of the javascript code, it tries to extract the post id and comment id from the request hash:

var match = decodeURI(url).match(/#(\d+|comment(\d+)_(\d+))/i);

From there it calls highlightComment, which does the scrollIntoView and CSS highlighting.