asenovm
asenovm

Reputation: 6517

Getting the style of the word surrounding the current cursor position

I'm trying to get the style/bold,italic,etc/ of the word under the current cursor position. I have the x and y coord of the click and I've done the following

var range = document.caretRangeFromPoint(x, y);
range.expand('word');
range.queryCommandState('bold');

but this leads to error that range does not have queryCommandState method whilst this reading: http://help.dottoro.com/ljkxwclp.php implies that range or at least text range (I'm JS newbie so pardon me about that) has such a method. Any help is greatly appreciated.

Edit: I kinda workaround this by adding

var range = document.caretRangeFromPoint(x,y);
range.expand('word');
window.getSelection().addRange(range);
document.queryCommandState('bold');
window.getSelection().empty();

but I'm not very happy with it. Is there a better way to achieve this?

Upvotes: 1

Views: 769

Answers (1)

Tim Down
Tim Down

Reputation: 324577

I don't think you can do any better than what you've got without writing lots of code. IE's proprietary TextRange has a queryCommandState() and related methods but that's never made it into Range in other browsers.

If you're unhappy that you need to destroy the selection to do the bold testing, then I agree that it seems unnecessarily complicated and clunky, but it is simple to restore the selection to its original state. Also, the standards-based way to empty the selection is removeAllRanges() rather than empty(), which is WebKit-specific.

Demo: http://jsfiddle.net/GkWTb/1/

Code:

var range = document.caretRangeFromPoint(x, y);
var sel = window.getSelection();
var selRange;

// Save initial selection
if (sel.rangeCount > 0) {
    selRange = sel.getRangeAt(0);
}
range.expand("word");
sel.removeAllRanges();
sel.addRange(range);
alert( document.queryCommandState("bold") );

// Restore original selection
sel.removeAllRanges();
if (selRange) {
    selRange = sel.addRange(selRange);
}

Upvotes: 1

Related Questions