daveyfaherty
daveyfaherty

Reputation: 4613

Add keyDown() function to <a> which are new children of a contenteditable div

Jsfiddle: http://jsfiddle.net/qTEmc/1/

I need to associate events with the keypress event on links which are added in the contenteditable.

If you try typing in the contenteditable area in the linked jfiddle, you'll see it creates a link and you can type within it. I fyou press return, you go to a newline. What I want is for pressing return in the new link to trigger a function. For the sake of progress, I'm just trying to get it to return an alert at the moment.

Does anyone know a reliable way to do this?

Upvotes: 0

Views: 162

Answers (1)

Tim Down
Tim Down

Reputation: 324587

You won't be able to detect key events within the links themselves because they don't fire key events. Instead, you'll need to adapt your existing keypress handler for the contenteditable element to inspect the selection to see if it lies within a link. Here's a function to do that. I've also updated your demo.

function selectionInsideLink() {
    var node = null, sel;

    // Get the selection container node
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.rangeCount) {
            node = sel.getRangeAt(0).commonAncestorContainer;
        }
    } else if (document.selection) {
        sel = document.selection;
        if (sel.type != "Control") {
            node = sel.createRange().parentElement();
        }
    }

    // Check if the node is or is contained inside a link
    while (node) {
        if (node.nodeType == 1 && node.tagName.toLowerCase() == "a") {
            return true;
        }
        node = node.parentNode;
    }
    return false;
}

Upvotes: 1

Related Questions