Question

I want to attach a class to an object based on cursor position.

I understand the basics of range, and can get/manipulate selected text, but I'm at a loss as to how I can use the cursor to attach a class to the object it's currently in.

I've through about maybe adding a temporary element at the cursor then traversing to the parent element and attaching the class before removing the temporary element. That really seems messy though, and I would have to assign something to initialize it (keyboard shortcut or on keydown).

Any ideas? I've search around but haven't found anything like what I'm wanting.

Was it helpful?

Solution

Thanks to John's lead and results from a more appropriate search term, I found this:

Javascript: Detect Carets Parent Node

To answer the question, here's how it's done.

function getCursorParentNode()
{

  var target = null;
  if(window.getSelection)
  {
    target = window.getSelection().getRangeAt(0).commonAncestorContainer;
    return((target.nodeType===1) ? target : target.parentNode);
  }
  else if(document.selection)
  {
    var target = document.selection.createRange().parentElement();
  }
  return target;

}

Then, initialize it however you prefer, for example:

$('.content').on('keydown',function(){

  var target = getCursorParentNode();
  target.className = 'red';

});

Here's a fiddle to demonstrate.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top