KPM KPM - 1 year ago 101
Javascript Question

Javascript - sendkeys to proper dynamically created div

I'm a bit lost as to starting the code for my scenario.

I allow the user to create divs dynamically by clicking on an add new div button and remove div button. Therefore, the user could be focused inside any div on the page and I need to make the keypress event send to the correct div.

I have some buttons to insert Mathml on the left of the screen. I want to be able to click on the button and for the Mathml code to appear in the div the user is currently focused in.

From what I've read, I believe I have to attach an event listener to each div as it is created and remove it when the user removes the div (I maintain an index of the divs).

How do I send the keypress event from the button to the div the user is in without losing focus on the div and making sure the Mathml goes into the correct div?

I know in vb or C# .net it is a 2 second job but javascript seems like a real nightmare for this type of functionality.

Any help/pointers/tips etc.. would be most welcome.

Answer Source

Alright, so I created this fiddle for you the get a look at how a possible solution could look.


<div id="container">
<button type="button" id="AddBtn">
<button type="button" id="RemoveBtn">


var No = 0;
var focusedElement;
$(document).ready(function() {
    $('#container').on('click','div',function() {
        focusedElement = this;

    $('#AddBtn').on('click',function() {

    $('#RemoveBtn').on('click', function() {