FrenkyB FrenkyB - 2 months ago 14
HTML Question

Dynamically added element function call not working

I have a problem with function call, when element is dynamically added.
Here is the link to code pen example. Function call - onclick - is from this button:

<button id="btnFocus" class="btnFocus" onclick="focusToDIV($(this))">Focus to DIV</button>


Function focusToDIV:

var focusToDIV = function(btnReference){
btnReference.parent().find("#div3").focus();
}


First element which contains this button is statically added. All the other elements can be added with button 'Add new'. With statically added element function focusToDIV gets called and div3 receives focus.

With dynamically added elements btnReference is not defined, that is why this error is thrown:


Uncaught TypeError: Cannot read property 'parent' of undefined


How to make this function work (put focus on div3 with click on btnFocus) with dynamically added elements? Why is btnReference not defined, if element is added dynamically to DOM?



var focusToDIV = function(btnReference){
btnReference.parent().find("#div3").focus();
}


var addNew = function(){

$("#divMain").append("<div class='divContainer' class='divContainer'> <div id='divInner' class='divInner'>" +
"<div id='div2' class='div2'> <div id='div3' class='div3' contentEditable='true'></div>" +
"</div></div> <button id='btnFocus' class='btnFocus' onclick='focusToDIV($(this))'>Focus to DIV</button> </div>");


}






.divMain{
height: 100vh;
width: 100vw;
}

.divContainer{
position: relative;
display: inline-block;
left: 20%;
top: 10%;
}

.divInner{
width: 300px;
height: 300px;
border: 1px solid black;
}

.div2{
position: relative;
left: 20px;
top: 20px;
width: 200px;
height: 100px;
border: 1px solid blue;
}

.btnFocus{
position: absolute;
top: 305px;

}

.div3{
position: relative;
left: 10%;
top: 10%;
width: 150px;
height: 80px;
border: 1px solid red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="divMain" class="divMain">

<button id="btnAdd" onclick="addNew()">Add new</button>

<div class="divContainer" class="divContainer">
<div id="divInner" class="divInner" >
<div id="div2" class="div2">
<div id="div3" class="div3" contentEditable="true"></div>
</div>
</div>
<button id="btnFocus" class="btnFocus" onclick="focusToDIV($(this))">Focus to DIV</button>

</div><!-- divContainer -->


</div><!-- divMain -->




Answer

You need to change the onclick method from focusToDIV() to focusToDIV($(this)).

As the element wasn't passed btnReference is undefined and you were calling a method on that undefined variable.

var addNew = function(){

  $("#divMain").append("<div class='divContainer' class='divContainer'> <div id='divInner' class='divInner'>" +
    "<div id='div2' class='div2'> <div id='div3' class='div3' contentEditable='true'></div>" +
    "</div></div>  <button id='btnFocus' class='btnFocus'  onclick='focusToDIV($(this))'>Focus to DIV</button>    </div>");


}