2
<div class="pad" id="test" contenteditable="true" spellcheck="false">
       <div id="a0" class="fif" > text0</div>
       <div id="a1" class="fif" >text1</div>
       <div id="a2" class="fif" >text2</div>
     </div>

As in above code there is a contenteditable div with some child divs inside it. I need a jQuery to return the id of the child div over which I am typing. e.g. if I am editing text1 it should give me (return) "a1".

It works as desired if I use

var clicked;
$('#test').click(function(event){
   clicked = $(event.target);
   alert(clicked.attr('id'));
});`

as shown here

http://jsfiddle.net/bernie1227/cK69Q/ (i.e. on clicking it returns id="a1") but it doesn't work in similar manner if I use

var clicked;
$('#test').keypress(function(event){
   clicked = $(event.target);
   alert(clicked.attr('id'));
});

as shown here http://jsfiddle.net/hari_OM/bLgkv/ i.e. on typing it returns "id=test" and not "id=a1"

I tried using event.target.id and $(this).attr("id") but they return id="test" and not id="a1" , but I need to get "a1". I also tried injecting onkeypress="funcname(this.id)" within child divs and retriving it from defined function, but it doesn't work.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Vivek Dani
  • 347
  • 1
  • 4
  • 19

2 Answers2

0

I have written a solution which relies on tracking the target of the event, using event.target: http://jsfiddle.net/bernie1227/cK69Q/

Bernie
  • 1,489
  • 1
  • 16
  • 27
  • That is not what I want.It works well for **$('#test').click(function(event){..** but it does not work for **$('#test').keypress(function(event){..** as I have shown it here [ http://jsfiddle.net/hari_OM/bLgkv/](http://jsfiddle.net/hari_OM/bLgkv/) . In case of keypress it shows **id=test** and not **id=a1**. – Vivek Dani Mar 04 '13 at 21:23
0

Ever looked into this? DOMCharacterDataModified

$(document).on('DOMCharacterDataModified',  function( event ) {
    if($(event.target).parent().attr('id') === 'parentid') {
        console.log(
            'target',$(event.target),"\r"
        );  
    }
});
Webmaster G
  • 502
  • 5
  • 12