dynamically added div will not work when being called on [duplicate] - javascript

This question already has answers here:
Events triggered by dynamically generated element are not captured by event handler
(5 answers)
Closed 10 years ago.
I am trying to create a list of divs. When the new layer button is clicked, there is a new div created with a unique ID. When I try to call on these dynamically added divs, there is no response. I am confused because the preexisting divs work.
<input type="submit" id="newLayer" value="New Layer">
<div id="layersContainer" class="layerscontainer">
<div class="layer" id="layer1">fadfa</div>
<div class="layer" id="layer2">2</div>
</div>
var newLayerCounter = 2;
var layerID = "";
var layersArray = new Array();
var clickedElement = "";
function selectLayer(){
$(clickedElement).css({"background-color":"yellow"});
}
$('#layersContainer div').on("click", function(){
clickedElement = $(this).attr("id");
alert(clickedElement);
selectLayer();
});
$('#newLayer').on("click", function(){
newLayerCounter = newLayerCounter + 1;
layerID = "#layer"+ newLayerCounter;
$('<div/>', {
id: "layer"+ newLayerCounter,
class: "layer"
}).appendTo('#layersContainer');
$(layerID).text('hey');
})
Here is a link to a working JSfiddle
http://jsfiddle.net/Q3dSp/24/

Change your
$('#layersContainer div').on("click", function(){
to
$(document).on("click", '#layersContainer div', function () {
clickedElement = $(this).attr("id");
alert(clickedElement);
selectLayer();
});
It is known as delegated event.

Try with $('#layersContainer').on("click", "div", function(){ (...) });
http://jsfiddle.net/3hqfn/1/

change :
$('#layersContainer div').on("click", function(){
with this:
$('#layersContainer').on("click", "div", function(){

Try with this one:
$('#layersContainer').on("click", 'div', function(){
clickedElement = $(this).attr("id");
alert(clickedElement);
selectLayer();
});
In this situation you need a event delegation to existing closest parent when dom was ready.

Related

JQuery selector scope [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 5 years ago.
I am trying to create a simple list with the option to add and remove elements, but it seems there are some scope rules about the selectors that I couldn't find in the official documentation. My HTML, including the jQuery is as follows:
$(function() {
$("#add").click(function() {
let val = $("input").val();
if (val !== "") {
let ele = $("<li></li>").text(val);
ele.append("<button class='rem'>X</button>");
$("#mylist").append(ele);
$("input").val("");
// $(".rem").click(function(){
// $(this).parent().remove();
// });
};
});
$(".rem").click(function() {
$(this).parent().remove();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" placeholder="Add new item">
<button id="add">Add</button>
<ol id="mylist">
</ol>
The commented part is the part that is running properly, but the one that is outside of the click function for the #add element is not working.
When you call $(".rem").click(.. jQuery will look for elements with class ".rem" and bind this new click event.
However, this only happens once. If you add elements later with the same class, those don't automatically get that event.
So what you'll want to do is bind this event to the new element you created, after you created it.
Lets clean this up:
<script>
function onAddClick() {
let val = $("input").val();
if (val !== ""){
let ele = $("<li></li>").text(val);
ele.click(onRemClick); <--- HERE
ele.append("<button class='rem'>X</button>");
$("#mylist").append(ele);
$("input").val("");
};
}
function onRemClick() {
$(this).parent().remove();
}
$(function() {
$("#add").click(onAddClick);
});
</script>

can't get click event of div element in jquery [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 6 years ago.
This problem is so weird and the title might not seem to fully explain the meaning, so this is what i mean, i have list of div nested in each other and i can get the click event and other event of the outer Div but can't get the click event and other event of the inner div and it's content. below is my code
var scrollWidth = 124;
var currentPhoto;
var defaultDisplayPhoto = 5;
var maxScrollCount=0;
var maxScroll =(scrollWidth*currentPhoto)-(scrollWidth*defaultDisplayPhoto);
var maxScroll;
var timeCounter;
var duration = 1000; //time to wait to fire the event;
var photoAllowed = 12;
var canAddMore;
var eventCounter= [];
$("input.upload").on('change',function(event){
$(".mycarousel-container").show();
if(eventCounter){
i=eventCounter.length;
}else{
i=0;
}
imgsrc = URL.createObjectURL(event.target.files[0]);
//for(var i=0; i <eventCounter.length; i++)
var div = $("<div class='mycarousel' style='left:"+left+"px' id='picture"+i+"'></div>");
var transparentDiv = $("<div class='transparent'></div>");
var deleteIcon = $("<span class=\"deletebutton\"><i class=\"glyphicon glyphicon-trash\"></i></span>");
var imgPreview = "<img class='myimg' src="+imgsrc+">"
transparentDiv = transparentDiv.html(deleteIcon);
div = div.html(transparentDiv);
div = div.append(imgPreview);
$(".carouser-inner").append(div);
left = left+120;
eventCounter.push(imgsrc);
if(eventCounter.length>5){
$("#carousel_control_left").show();
$("#carousel_control_left").addClass('myActive');
scrollThumb('Go_R');
}else{
$("#carousel_control_left,#carousel_control_right").hide();
}
if(eventCounter.length == 12){
alert('end')
$("input.upload").attr('disabled',true);
}else{
$("input.upload").attr('disabled',false);
}
});
$('.mycarousel').click(function(){
alert('this is inner div with border color blue');
});
$('.myimg').click(function(){
alert('this is inner image');
});
DEMO ON FIDDLE
please see the demo on fiddle and add some images and divs will show up, now try to get the click event of the div with border color BLUE or the image in it
use $(document).on cause when you assign your click event , div element is not in DOM yet
$(document).on( 'click', '.mycarousel', function () {
alert("here");
});
You can't register a static listener, because you add the items dynamically. You can use on with document instead:
$(document).on("click", '.mycarousel', function(){
alert('this is inner div with border color blue');
});
$(document).on('click', '.myimg', function() {
alert('this is inner image');
});
Try this.
$(document).on('click', '.mycarousel' , function() {
//code here ....
});

Assign click-event on a new element in the event itself

I want to create a new element and assign this element the same event for onclick, which it has created it.
DEMO
$(function(){
var counter = 0;
$('.sub').click(function(event){
event.stopPropagation();
counter++;
$div = $(this); // makes more sense in the original code
$div.append('<div class="sub" title="subsub">subsub' + counter + '</div>');
//$div.find('.sub').click // <-- ?????
});
});
In my demo I want to create a new subsub for every sub, which was clicked. Than I want to add the same click event to the new subsub element.
Could anyone help me with this?
I've found nothing for this problem. Maybe I don't have the correct keywords for google or SO :/
Just use event Delegation
$(document).on('click', '.sub', function(event){
Your click events seem to be working correctly at this point,because you are using append which actually nests the new div inside the div that is clicked. Try using after and the functionality breaks.
$(function(){
var counter = 0;
$(document).on('click', '.sub', function(event){
event.stopPropagation();
counter++;
$div = $(this); // makes more sense in the original code
$div.after('<div class="sub" title="subsub">subsub' + counter + '</div>');
});
});
Check Fiddle
Why not create proper elements instead :
$(function(){
var counter = 0;
$('.sub').on('click', doStuff);
function doStuff(event) {
event.stopPropagation();
counter++;
var $div = $(this),
$sub = $('<div />', {'class':'sub',
title : 'subsub',
text : 'subsub' + counter,
on : {
click : doStuff
}
}
);
$div.append($sub);
}
});

jQuery click dynamic element

See the code's comment:
$.each($('input[type="radio"]'), function(){
var input = $(this);
var container = $('<div class="radio"></div>');
var mark = $('<span />');
input.wrap(container).after(mark);
container.click(function(){
alert('test'); // Not triggered.
});
});
The html is:
<input type="radio" value="female" name="gender" />
Anyone know why the alert is not triggered when clicked, and yes it is visible in CSS. When I use :
console.log(container);
It does give me the HTML it is containing.
Thanks
$('body').on('click', 'div.radio', function() {
});
Full Code
$('body').on('click', 'div.radio', function() {
alert('test');
});
$.each($('input[type="radio"]'), function(){
var input = $(this);
var container = $('<div class="radio"></div>');
var mark = $('<span />');
input.wrap(container).after(mark);
});
NOTE
Instead of body, you should use a static-element that is the container of container.
Why you need this
You need delegate event handler, as your element added to DOM dynamically that means. after page load.
after some tested it seems to me that the "wrap" clone the object you pass it as argument, or reference to the object is lost but I'm not so sure.
a first solution is to assign the event "onclick" before moving the object in the "wrap".
$.each($('input[type="radio"]'), function(){
var input = $(this);
var container = $('<div class="radio"></div>');
var mark = $('<span />');
$(container).click(function(){
alert('test'); // triggered now.
});
input.wrap(container).after(mark);
});
a simplified version :
$.each($('input[type="radio"]'), function(){
var wrapper = $('<div class="radio"></div>').click(function(){
alert('test'); // triggered now.
});
$(this).wrap(wrapper).after($('<span />'));
});
dont forget to decalare this function in the onload function
$(function(){
// your code here ....
});
I was also affected by this and found that on is available only with jquery 1.7 and above.
I am on jquery 1.4.1 and on is not available with version. Upgrading jquery was something I wanted to avoid.
Thankfully delegate was there and it solved the problem.

trying to append content to DOM element

I'm trying to add a div to a row of content with the click of a button. My code works for the first row but not for any other row. Please help. This is the function for the button:
$(".addMMbtn").each(function() {
$(this).bind("click",
function() {
var thisRow = $(this).closest(".txtContentRow");
var thisTxt = thisRow.find(".txtContent");
var cellStr = '<div class = "mmCell prep"></div>';
$(cellStr).appendTo(thisTxt);
}
);
});
You can see a fiddle of the problem here: http://jsfiddle.net/z7uuJ/
$(".addMMbtn") will only find the elements present on the page and your code will only attach click event handler on them. Since you are adding the elements dynamically you should either use delegate or on (if you are using jQuery 1.7+) for click event to work on them too. Try this
Using delegate
$('#default').delegate('.addMMbtn', 'click', function() {
$('<div class = "mmCell prep"></div>')
.appendTo($(this).closest(".txtContentRow").find(".txtContent"));
});
Using on
$('#default').on('click', '.addMMbtn', function() {
$('<div class = "mmCell prep"></div>')
.appendTo($(this).closest(".txtContentRow").find(".txtContent"));
});
Demo
Instead of assigning click event directly on the button you need to use on():
$(document).on("click", ".addMMbtn",
function() {
var thisRow = $(this).closest(".txtContentRow");
var thisTxt = thisRow.find(".txtContent");
var cellStr = '<div class = "mmCell prep"></div>';
$(cellStr).appendTo(thisTxt);
}
);
In this case event handler will be subscribed to all newly added elements.
Code: http://jsfiddle.net/z7uuJ/5/
You don't need to loop through the elements to bind the handler:
$(".addMMbtn").live('click', function() {
var thisRow = $(this).closest(".txtContentRow");
var thisTxt = thisRow.find(".txtContent");
var cellStr = '<div class = "mmCell prep"></div>';
$(cellStr).appendTo(thisTxt);
});

Categories