14

I couldn't work out - or find any resources, on how to create the highlighting thing they do on medium.com

To clarify:

When you highlight a selection of words in an article, a little tooltip pops up with the option to tweet or comment on the selection of words you highlighted.

Here's a screenshot: Medium's highlight function

I have absolutely no idea how to achieve this - so I don't have any code to provide (and I can't work it out from the medium.com source)

If you have any idea on how to do this - please share

Thanks, Tom

TomHill
  • 614
  • 1
  • 10
  • 26

3 Answers3

14

First step is to get the selection of the user. This can be done with window.getSelection().

var getSelectedText = function () {
  var selectedText = '';

  if (window.getSelection()) {
    selectedText = window.getSelection();
  } else if (document.getSelection()) {
    selectedText = document.getSelection();
  } else if (document.selection) {
    selectedText = document.selection.createRange().text;
  }

  return selectedText;
};

window.addEventListener('mouseup', function () {
  var result = getSelectedText();

  // Now you can do whatever you want with your selected text 
});

Then you need to create a sticky tooltip on the position of this selection (you can find this by getting the element.offsetLeft, element.offsetTop of your element). Then you need to hook in a commenting system that stores the relationship to the selection (by wrapping the selection with a span and an ID for example and open up the editor.

This is only the basic introduction for what you asked, it’s slightly more complex but also depends on what you exactly want to do with it.

Hope it helps!

helloanselm
  • 329
  • 2
  • 12
2

Try looking at Highlighter.js on github. It's similar to what's happening on Medium.com blog but requires a bit of work in order to achieve what you want.

Brodan
  • 152
  • 1
  • 18
Liam
  • 1,028
  • 13
  • 24
-4

Take a look in this fiddle:

http://jsfiddle.net/9RxLM/

and use below code:

$(".tiptext").mouseover(function() {
    $(this).children(".description").show();
}).mouseout(function() {
    $(this).children(".description").hide();
});

Or you can use jquery tool tip:

http://www.1stwebdesigner.com/css/stylish-jquery-tooltip-plugins-webdesign/

Systematix Infotech
  • 2,345
  • 1
  • 14
  • 31
  • This is fine as a tooltip technique, but I'm not sure how it addresses the question of getting the text the user has selected. – RameyRoad Apr 26 '16 at 15:00