Bind rangy highlight to another element

501 views Asked by At

I'm trying to implement highlight-based comments similar to the ones on Medium.com where a users can highlight some text and associate a comment with that text. Using Rangy, I can use the elementProperties onclick callback to get the highlight id, which I can then use to toggle the associated comment and make it appear "active." What I can't figure out is how to do the opposite - click on the comment and add a class to the associated highlight element(s) to give them an "active" appearance.

Alternatively, is there a way to apply one highlight at a time based on the highlight id instead of using deserialize and applying all previous highlights? I guess I could parse the serialized comments and search for the id I'm looking for in the string, but I figured there must be a cleaner way that I can't find in the docs.

Any ideas?

1

There are 1 answers

0
dvanderb On

I figured out a solution. After creating a highlight (which in my case adds an element with class="note" similar to the Rangy highlighter module demo), I can loop through all notes and add a data attribute to identify which highlight it is part of:

$(".note").each ()->
  highlight = highlighter.getHighlightForElement($(this)[0])
  $(this).attr("data-highlight-id", highlight.id)

EDIT: I found a better solution

When creating a comment, I am now saving the serialized highlight that goes along with that comment. Before creating a new one, I call highlighter.removeAllHighlights() to make sure the comment only stores its own serialized highlight. Then I can use that info to re-create the highlight when a user clicks on the comment. Just clear all the highlights out and deserialized the one belonging to the comment that was clicked.