0

I want to bind focus() event only to children of divs with certain class. This is what I tried and didn't work:

var boxedElements = "p,div,h1,h2,h3,h4,h5,h6,table";

    $(".myBox").find(boxedElements).focus(function () {
        var tagname = $(this).prop("tagName");
        console.log(tagname);
    });

The function is never reached for some reason. Any ideas of how to approach this?

Edit

<div class="myBox" contenteditable="true">
<h3>This is a header</h3>
<p>This is a paragraph</p>
<p>This is another paragraph</p>
</div>

Now the user can either click on of the elements or, since its contenteditable, can navigate using the keyboard arrows from h3 to the the first p element for example. I want to be able to detect that.

Shiran Dror
  • 1,472
  • 1
  • 23
  • 36
  • 2
    Are you sure these elements can have focus at all? Check http://stackoverflow.com/questions/1599660/which-html-elements-can-receive-focus – Nikolay Ermakov Mar 03 '16 at 01:16
  • why you doing `focus` and not `hover` – mmativ Mar 03 '16 at 01:23
  • I was not aware of this limitation. Thank you. Any idea of how to mimic focus event on such elements? the parent div is contenteditable so I can either click them (which is easy to handle) or move with the keyboard. – Shiran Dror Mar 03 '16 at 01:26
  • You can either insert focusable elements inside those elements and focus between them or listen to keypress event and iterate elements based on a key pressed. – Nikolay Ermakov Mar 03 '16 at 02:07

1 Answers1

0

So this is how I solved it eventually, Thanks @Nikolay Ermakov and @mmativ

    var boxedElements = "p,div,h1,h2,h3,h4,h5,h6,table";

    $(".myBox").find(boxedElements).click(function (e) {
        var tagname = $(this).prop("tagName");
        console.log(tagname);
        e.stopPropagation();
    });

    $(".shmeditor").click(function () {
        var tagname = $(this).prop("tagName");
        console.log("other tag: " + tagname);
    });

    $(".myBox").keydown(function (e) {
        var $element = $(getSelection().getRangeAt(0).commonAncestorContainer.parentNode).closest(boxedElements);
        if ($element.hasClass("myBox")) {
            console.log("other tag: ");
        }
        else {
            console.log($element.prop("tagName"));
        }
    });
Shiran Dror
  • 1,472
  • 1
  • 23
  • 36