0

I am writing a draggable html div as:

enter image description here

And it looks like this:

enter image description here

But I cannot input anything like a normal input div as: <input />. It does not response for any key events.

I have tried to use stopPropagation to stop the event to its parents as:

    input.onclick = function ( evt ) {
        evt.stopPropagation();
        console.log( 'input got clicked' );
    };


    $( input ).on( 'keydown', function ( evt ) {
        evt.stopPropagation();
        console.log( 'input got keydown' );
    } );

where the input is:

    let input = document.createElement( 'input' );
    input.setAttribute( 'type', 'text' );

and with console.log( input ):

enter image description here

but it does not help. (And for the later keydown event, no output is given in the console.)

Can anyone suggest me a way to debug this problem? It really drives me crazy. Thanks!

PS: Chrome is used.

Update: I find the problem, but do not know the reason.

It is because I decorate the parent dom as jquery draggable, and I need to cancel the <input class='x-leaf'/> as:

    $('#input-parent').draggable({
        containment: 'window',
        cancel: '.x-leaf'
    });

With the previous stopPropogation and the way suggested by @Brainfeeder, it finally works.

Zhenjie Zhao
  • 363
  • 1
  • 5
  • 17

1 Answers1

1

Because input is created after DOM loading you better call .on() on a parent element that exists in DOM on page load.

$('#someParentEl').on( 'keydown', '.x-node input', function ( evt ) {
    console.log( 'input got keydown' );
} );
Brainfeeder
  • 2,604
  • 2
  • 19
  • 37
  • try changing `$(input)` to `.x-node input` or some selector matching the input instead of the object. – Brainfeeder Jan 24 '18 at 14:08
  • ` $( document ).on( 'keydown', $( '.x-node input' ), function ( evt ) { evt.stopPropagation(); console.log( 'input got keydown' ); } );` – Zhenjie Zhao Jan 24 '18 at 14:22
  • Thanks for your patience. I have detected the event with the above code. But I still cannot input anything. – Zhenjie Zhao Jan 24 '18 at 14:23
  • The real weird thing is that, once I add this `input.classList.add('x-connection');`, then it works, even with my previous buggy code. – Zhenjie Zhao Jan 24 '18 at 14:25
  • `.x-connection{ position:absolute; border:solid 1px #dedede; background-color:#2e2e2e; width:0.5em; height:0.5em; border-radius:0.5em; }` – Zhenjie Zhao Jan 24 '18 at 14:26
  • You might need to delete `evt.stopPropagation();` This keeps the data from being added to the input. – Brainfeeder Jan 24 '18 at 14:28
  • Thanks again. In the flavor of what I am doing, I add a similar question here: https://stackoverflow.com/questions/10920355/attaching-click-event-to-a-jquery-object-not-yet-added-to-the-dom, and my preferred answer: http://jsfiddle.net/cn7y2mwb/, for people may find it useful. – Zhenjie Zhao Jan 24 '18 at 15:10