How to dynamically add html elements with jquery? - javascript

My goal is to have one element on initial load, this element should have id="something_O", when a add link is clicked, underneath already existing element, new, the same html element should be added,not with id="something_o", but with id="something_1", or last element + 1, to be specific. The user should be able to add these elements infinitely. When the user clicks deleted, element should disappear.
Any ideas?
Here is prepared fiddle for easier help...

var counter = 1;
$('.AddEl').live('click', function () {
var el = $('#element_1').clone().attr('id', 'element_' + ++counter).appendTo('body');
});
$('.RemoveEl').live('click', function () {
var el = $(this).parents('.elem')
if (el.get(0).id !== 'element_1') el.remove();
});
Check this here

One means to do this is:
$(document).ready(function() {
$('body').on('click', '.AddEl', function() {
$('.actions:first')
.parent()
.clone()
.attr('id', 'element_' + $('.actions').length)
.insertAfter($('.actions:last').parent());
});
$('body').on('click', '.RemoveEl', function() {
$(this).closest('.actions').parent().remove();
});
});
JS Fiddle demo.
Please note that I've amended your html so that the first element to be cloned is now id="element_0", and targeted that, and all subsequently-created elements, with the CSS selector:
div[id^=element] {
/* css */
}
This could be simplified, but these are simply my first thoughts.
Edited to offer a slightly improved version, in that the initial addition is slightly, or seems a little, more concise, and also features a means to prevent duplicate ids being generated if elements are added/removed:
$(document).ready(function() {
$('body').on('click', '.AddEl', function() {
var $elems = $('.actions').parent();
$elems
.first()
.clone()
.insertAfter($elems.last());
$('div[id^="element_"]').each(
function(i){
$(this).attr('id','element_' + i);
});
});
$('body').on('click', '.RemoveEl', function() {
$(this).closest('.actions').parent().remove();
});
});
JS Fiddle demo.

I just overwrite to your code.
You can try this, may something you want.
http://jsfiddle.net/kongkannika/QeSPP/34/

Related

Click doesn't work correctly after append

My code generates an infinite scroll but when I touch each one it appears alerts many times and that isn't right.
$(window).scroll(function() {
if ($(window).scrollTop() == $(document).height() - $(window).height()) {
var variable = "<div class='corazon'>hi</div>";
$(".hola").append(variable);
$('.corazon').on('click', function() {
alert("hola");
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Thank you.
$('.corazon').on('click', function() {
alert("hola");
});
You're adding a new click listener to all the elements with class "corazon" every time you reach the scroll limit.
You should add the click listener on the created element instead of performing a new query $(".corazon") .
Try this:
var variable = $("<div class='corazon'>hi</div>");
$(".hola").append(variable);
variable.on('click', function() {
alert("hola");
});
This has already been asked, use jquery clone to clone an existing element with listener.
.clone( [withDataAndEvents ] [, deepWithDataAndEvents ] )
Provide both with true.
And yes
$('.corazon').on('click', function(){
alert("hola");
});
Should not be in the scoll listener
Full documentation: https://api.jquery.com/clone/
Instead of:
$('.corazon').on('click', function() {
you shuld have:
$(variable ).on('click', function() {
Now the clickhandler is only added to the new element.

Is there a way to apply jQuery to dynamically created elements? (not event listeners)

I have dynamically created an element with the following class:
<span class="text">Hello</span>
and jQuery:
function changeText() {
var oldText = $(this).text();
$(this).text(oldText + " There");
}
$(function() {
$(".text").each(function(){
changeText.apply(this);
})
})
Obviously, this is a simplified version of what is actually happening but the basics are there. Is it possible to apply this rule to dynamically created elements even though we are not using event listeners?
The problem here is that there is no specific location for these ".text" elements. The only place we know these will show up is in the body. I we use a mutationObserver on the body... wouldn't that be taxing performance?
Do this instead:
function changeText() {
var oldText = $(this).text();
$(this).text(oldText + ' There');
}
$(function(){
$('.text').each(function(i, e){
changeText.call(e);
});
});
Like this
$dynamicElement.find(".text").each(function(){
changeText.apply(this);
})

jQuery Move div into another div

I need to move .link-field-first-ticket-button inside .event-location-one
here's the fiddle: http://jsfiddle.net/ksV73/
It's a cms so I have no choice in the matter.
this is what I'm trying, it's not doing much of anything
$(".widget-upcoming-events-blog li").each( function() {
var links = $(this).children(".link-field-first-ticket-button").html();
$(this).children(".link-field-first-ticket-button").html("");
$(this).children(".event-location-one").append(links);
});
You can just do this:
$(".link-field-first-ticket-button").appendTo(".event-location-one");
It will move the first ticket button to event location
x = $(".widget-upcoming-events-blog").find(".link-field-first-ticket-button").remove()
$(".event-location-one").append(x);
The html method will give you the content inside the element, not the element itself.
Just append the element where you want it. As an element can't exist in two places at once, it will be moved:
$(".widget-upcoming-events-blog li").each( function() {
var links = $(this).children(".link-field-first-ticket-button");
$(this).children(".event-location-one").append(links);
});
try this
$(".widget-upcoming-events-blog li").each( function() {
var links = $(".link-field-first-ticket-button").html();
$(".link-field-first-ticket-button").html("");
$(".event-location-one").append(links);
});
Change your .children() to .find()
$(".widget-upcoming-events-blog li").each( function() {
var links = $(this).find(".link-field-first-ticket-button").html();
$(this).find(".link-field-first-ticket-button").html("");
$(this).find(".event-location-one").append(links);
});
How about use the .appendTo() function?
For example:
$(".widget-upcoming-events-blog li").each( function() {
$(this).find(".link-field-first-ticket-button")
.appendTo( $(this).find(".event-location-one") );
});

jQuery: Moving element to another element and back again renders the element unclickable

In my script, I'm attempting to move an element (list) from one parent (just the text) to another and then back again (to the list). The problem is that when I have moved the element back to the original parent (ul), it has become un-clickable. I thought using the detach() over the remove() might do the trick but it doesn't make a difference.
$(document).ready(function() {
$("#inventoryWeapon li").click(function(event) {
var clickedId = event.target.id;
if ($("td#weapon").is(":empty")) {
$("td#weapon").text(clickedId);
$(this).detach();
}
});
$("td#weapon").click(function(event) {
var unequipping = $(this).text();
$("#inventoryWeapon").append("<li id='" + unequipping + "'>" + unequipping + "</li>");
$(this).detach();
});
});
As suggested in the popular comment above, you are not moving the element. To move it, do this.
$("td#weapon").click(function(event) {
$(this).appendTo($("#inventoryWeapon"));
});
You're not moving the element, you're removing the element in one function, and creating a new element with the same ID and content in the other. But the original event handler was only bound to the original element.
If you want your event handler to work with dynamically created elements, use event delegation:
$("#inventoryWeapon").on("click", "li", function(event) {
...
});
Alternatively, you could save the element when you detach it, instead of recreating it:
var savedLI;
$("#inventoryWeapon li").click(function() {
if ($("td#weapon").is(":empty")) {
savedLI = $(this).detach();
$("td#weapon").text(this.id);
}
});
$("td#weapon").click(function() {
if (savedLI) {
$("#inventoryWeapon").append(savedLI);
$(this).detach();
}
});

Remove internal selected div created dynamically

I've been looking around but i couldn't find a solution yet.
My code is something like this:
$('#addDiv').click( function() {
var divNum = divNum + 1;
var newdiv = document.createElement('div');
var divIdName = 'mydiv';
newdiv.setAttribute('id',divIdName+divNum);
newdiv.className = 'imgDiv';
});
$('#cont-div').on('click', function(e) {
//REMOVE clicked div
});
I have a div named "cont-div" which contains the dynamically created divs.
Probably the solution is very simple, but I can't find a way to identify the clicked div inside 'cont-div' so I can remove it.
You can use event delegation since the divs are created dynamically:
$('#cont-div').on('click', 'div', function(e) {
//REMOVE clicked div
$(this).remove();
});
$('#cont-div div').on('click', function(e) {
var clickedDiv = e.target;
if(clickedDiv != e.currentTarget)
{
//Remove the clicked div if it is not the parent.
$(this).remove();
}
});
Hmmm, your code implies you may have multiple elements with the same ID. Don't do that, that'll make things harder. Just use the class you have set:
$('.imgDiv').on('click', function() {
$(this).remove();
});
You can use jquery remove() to remove the element. Also you will need a delegate for simply handling events on dynamicly inserted elements.
Working Demo
Html:
<input id="addDiv" type="button" value="click!" />
Javascript:
$(function(){
$('body').on('click','.imgDiv',function(){
$(this).remove();
});
});
EDIT: Shortened down code snippet, now only showing relevant parts.

Categories

Resources