5

I'm trying to write a website that allows users to highlight some text (change background to yellow), and then the app will save this so that the next time he or she comes back to the page, it'll be yellow already (as if they never left).

This is kind of two questions in one:

  1. I can get the text using window.getSelection().toString(), but I don't know how to get it as a selector so I can change the background of the selection to yellow.

  2. I don't know how to get the "address" of the selection. I need this so that I can save it to the database and colour it yellow the next time the user loads the page.

EDIT Currently looking into this: https://github.com/timdown/rangy

adrianmcli
  • 1,956
  • 3
  • 21
  • 49

1 Answers1

2
  1. You'll want to wrap the selected text in a <span> with a class that sets the desired background color style. This question should help.

  2. This somewhat depends on your backend architecture. You'll probably want to store the element with the highlighted text, as well as the indices of the start and end points of the highlight. Then, when the page is served again, reapply the <span> accordingly. If you're not storing anything in the database, you could try storing this data in localStorage, and then parsing it and applying the highlight on page load.

Edit: I might have misunderstood. If you're talking about resetting the actual highlight (as in the text gets reselected), you can do that with JavaScript as well. You'll still need a way to store the user's selection data, either server side or via localStorage.

Community
  • 1
  • 1
benjarwar
  • 1,794
  • 1
  • 13
  • 28
  • Yeah, I read something about X-Path? That seems like a kind of "address" I can save to the DB? – adrianmcli Aug 05 '15 at 00:46
  • XPath is a query language for navigating XML nodes. On its own, this is not going to be a solution. You might want to do some homework on backend systems if you're needing to persist data to a database. That's way too large a subject to discuss in StackOverflow's Q&A format. – benjarwar Aug 05 '15 at 02:55