Search code examples
javascriptvue.jscomments

How to implement Medium-style commenting interface in VueJS


I really like the commenting interface employed by Medium, allowing users to highlight a portion of an article and comment on that specific part.

I would like to implement a similar commenting facility in a VueJS app.

I found this package which does something similar: http://aroc.github.io/side-comments-demo/, but I want to try to find something that has been updated more recently. Also, it requires jquery, which I don't currently use and I would like to avoid adding that dependency if possible.

I would love to know if anyone has seen anything that could help.


Solution

  • I have created a sample at https://codesandbox.io/s/medium-style-text-select-comment-box-h5o9r

    Here I am adding the comments component to the root component such that it is available globally. On component mount() hook, I am attaching a mouseup method to the window object where any selections done are checked using

    if (window.getSelection() && !window.getSelection().isCollapsed) {
        //execute only with the getSelection() method is available 
        //and the current selection is not collapsed
    }
    

    Once we do have a selection, the position on the page is calculated using the selection position and its dimensions and the floating comments component is positioned accordingly.

    We can get the selected text using

    window.getSelection().toString();
    

    I would advise you to go through the sandbox as there are a lot of things going on which are not in this answer.