Thomas Denney
Thomas Denney

Reputation: 1608

How to maintain selection after click in HTML?

I am coding a WYSIWYG editor (can't use something like TinyMCE - have to code myself) and I want users to be able to set the text as bold, underlined, links, etc by adding in tags to the HTML. The problem I've got is that when users select the text in the editable div and then click the 'Bold' button it is unable to find the selection because it has been deselected because the click event has happened. How can I stop this? Is there a better way to do this?

Upvotes: 5

Views: 6616

Answers (4)

Vijay Rudraraju
Vijay Rudraraju

Reputation: 189

Another, possibly better, way to achieve this is to call 'preventDefault()' on the 'mousedown' event for the 'Bold' button (which is when the selection gets cleared - at least in Chrome):

$('div.boldButton').mousedown(function(event) {
  event.preventDefault();
});

Upvotes: 4

scessor
scessor

Reputation: 16115

This function can help you:

jQuery.fn.getSelectedText = function() {
    var sSelectedText = "";
    // all browsers, except IE before version 9
    if (window.getSelection) {
        var sTagName = this.get(0).tagName.toLowerCase();
        sSelectedText = (
            sTagName == 'input' || sTagName == 'textarea' ?
            this.val().substring (
                this.get(0).selectionStart
                , this.get(0).selectionEnd
            ) :
            document.getSelection().toString()
        );
    }
    // Internet Explorer before version 9
    else {
        if (document.selection.createRange) {
            sSelectedText = document.selection.createRange().text;
        }
    }
    return sSelectedText;
}

Also see my jsfiddle.

=== UPDATE ===

If your button isn't an <input type="button/submit" ... /> or a <button ...>, you have to remember the selected text after each click:

var sSelectedText = '';
$('body').click(function() {
    sSelectedText = $('#text').getSelectedText();
});
$('body').dblclick(function() {
    sSelectedText = $('#text').getSelectedText();
});

On button click the selected text is in sSelectedText:

$('#button').click(function(e) {
    alert(sSelectedText);
});

Also see my new jsfiddle.

Upvotes: 2

Tim Down
Tim Down

Reputation: 324597

You need to make the button unselectable, which can be done with CSS in most browsers and the unselectable attribute in IE and Opera. Here's how:

How to disable text selection highlighting using CSS?

Upvotes: 9

Hoff
Hoff

Reputation: 39846

one idea is to keep track of the selection (by listening to mouseup events), so that your code knows what is highlighted at and given moment, so you can do something with it when the button is clicked...

This article has some good code examples.

Upvotes: 0

Related Questions