Jquery appending without removing - javascript

So I need to grab content from a specific class and put it in a div, which I use append for...my issue is that append removes the item I append, and I need it to stay there, Here is my code:
$(document).ready(function(){
var $content = $('#popupcontent');
var $window = $('#popupwindow');
$('.open').click(function(){
//alert('runnning');
var a = $(this).contents('span');
$content.append(a);
$window.fadeIn(300);
});
$('.close').click(function(){
//alert('running');
var a = $content.contents('span');
$window.fadeOut(300);
$('#popupcontent span').remove();
});
});
So how can I get the content, when clicked, from each .open span to the #popupcontents id without removing it from the .open class?
To show you what I mean: JSFIDDLE
NOTE: the second time you click a link, it wont append any content because that content has been removed from that class, which is not what I want
NOTE2: I cannot simply just append instead of remove in the $('.close').click function because I cannot detect which instance of the .open class the content came from.

You need to clone the element and append the clone:
$('.open').click(function(){
//alert('runnning');
var a = $(this).contents('span');
$content.append(a.clone());
$window.fadeIn(300);
});
Demo

Related

How do you target an element that is dynamically generated? [duplicate]

Beginner to all of this, playing around with Firebase. Basically, I want to retrieve text entries from Firebase and have an "Approve" button next to it. When the button is clicked, I want that specific text entry to be pushed to a new Firebase location and the text removed from the page. I am creating the button and the text dynamically and I am having some trouble with selecting the button and the divs I created. I know I have to use on() but I'm unsure of how to use it.
Thanks!
approveRef.on('child_added', function(snapshot) {
var posts = snapshot.val();
$('<div id="post">').text(posts.text).append('<button style ="button" id="approve">Approve</button>').appendTo($('#feed'));
});
$('#approve').on("click", function(){
var text = $('#post').val();
postsRef.push({'text':text});
$('#post').remove();
});
You have to bind .on() on a container of your dynamically added element that is already on the page when you load it, and have it like this:
$('#yourContainer').on('click', '#approve', function(){
//your code here..
});
Your .on() didn't work, because you are adding the button dynamically. You can't find the dynamically added elements directly using that elements id selector like $('#approve'). So you should
bind .on() with $(document) selector. This will always contain your dynamically added elements.
$(document).on( eventName, selector, function(){} );
$(document).on('click','#approve',function(){
//your code here
});
I find a quick dip into the DOM, and then running back into jQuery very handy for this problem:
// Construct some new DOM element.
$(whatever).html('... id="mynewthing"...');
// This won't work...
$("#mynewthing")...
// But this will...
$(document.getElementById("mynewthing"))...
This works by turning the DOM object directly into a selector. I like it because the approach is transparent in operation/intent.
Another alternative, simpler to understand, less powerful, also perfectly valid, is to simply bind the event while you create the element:
approveRef.on('child_added', function(snapshot) {
var posts = snapshot.val();
var $button = $('<button style ="button" id="approve">Approve</button>');
$button.on("click", function(){
var text = $('#post').val();
postsRef.push({'text':text});
$('#post').remove();
});
$('<div id="post">').text(posts.text).append($button).appendTo($('#feed'));
});
Another problem you are going to run into, assuming there will be more than one of these on a page, is that you are using IDs in the records. They're going to clash if they aren't unique.
A great alternative is to refer to these items with data-* tags or other identifying characteristics, such as css tags. But in your case, you don't need them at all!
approveRef.on('child_added', function(snapshot) {
var posts = snapshot.val();
var id = snapshot.name();
var $button = $('<button style="button">Approve</button>');
$button.on("click", function(){
// use parent.closest(...) in place of an ID here!
var text = $(this).parent().closest('textarea').val();
postsRef.push({'text':text});
$(this).parent().remove();
});
/* just an example of how to use a data-* tag; I could now refer to this element using:
$('#feed').find('[data-record="'+id+'"]') if I needed to find it */
$('<div data-record="'+id+'">').text(posts.text).append($button).appendTo($('#feed'));
});
I don't sure exactly what are you looking for. You can use .find() to select dynamically elements. I think .find() will look at the html structure again to get needed elements.
$("#button").click(function(e){
$(".parentContainer").find(".dynamically-child-element").html("Hello world");
});
Or
$(".parentContainer").find(".dynamically-child-element").html("Hello world"); // not in click event
So this is my demo

jQuery: Append element to inputfield and remove?

I'm trying to append and remove element in the inputfield.
I can simply append them and it works fine but I don't know hwy it doesn't get deleted/removed when I needed it to!
To explain this issue I have created this fiddle: http://jsfiddle.net/hrL3gn1g/2/
if you click on the images, it will append the element in the div Slevel as well as the inputfield.
If you click on the elements inside the Div, it should delete/remove the element or string from inside the inputfield but it doesn't
could someone please advise on this issue?
You can try this:
$(document).on('click', '.pricetag',function(){
var names = $(this).attr('data-name');
var price = $(this).attr('data-price');
// Create the value you want to remove
var html = '<span data-price="'+price+'" data-name="'+names+'" class="pricetag">'+names+'</span>';
// Replace that value with empty string
var newValue = $('#Finalized').val().replace(html,'')
// Insert new value
$("#Finalized").val(newValue);
});
as i see , you try to remove the words(orange,apple etc) by using $(<input>).remove(<span>), but you cant do this in that way.instead of this , i remove the selected <span> element.
i changed a little the click listener function to this one:
//when the user click on a word
$(document).on('click', '.pricetag',function(){
//this is the <span> element that the user clicked to delete
$(this).remove();
});
i changed the jsfiddle : http://jsfiddle.net/tornado1979/hrL3gn1g/3/
hope helps,good luck.

JQuery appending elements and acces to appended elements

I have a code where i appending to div some html over JQuery like
$("#divId").append("<div class='click' data-id='id'></div>");
and I want to acces by click appended div like this
$(".click").click(function(){
var id = $(this).attr('data-id');
alert(id);
});
but when I click, nothink happens, is there some solution for this? Thanks!
You need to use event Delegation.
$("body").on('click', '.click', function(){
var id = $(this).attr('data-id');
alert(id);
});
As the events are only bound for already existing elements on the page. but in your case you are dynamically appending the elements.
body can also be substituted to the closest ancestor that contains these elements.
$("#divId").on('click',
Check Fiddle

jQuery addClass() to element generated after append()

I am trying to add a class to a newly appended DIV without using something like:
t.y.append('<div class="lol'+i+'"></div>');
Here's a better example of what I'm trying to do:
var t = this;
$(this.x).each(function(i, obj) {
//append new div and add class too <div></div>
t.y.append('<div></div>').addClass('lol'+i);
});
Page load HTML looks like:
<div class=".slideButton0 .slideButton1 .slideButton2" id="sliderNav">
<div></div>
<div></div>
<div></div>
</div>
When you append an element through .append, it doesn't change the context of the jQuery object.
You could write it like this:
$('<div></div>').appendTo(t.y).addClass('lol'+i);
or
$('<div></div>').addClass('lol'+i).appendTo(t.y);
(these both do the same thing, simply in different orders, the second possibly being more clear)
the context of the jQuery object will be the newly created div.
t.y.append('<div></div>').addClass('lol'+i);
should be
t.y.append('<div></div>').find('div').addClass('lol'+i);
In the first case you are adding class to the div to which you are appending ..
SO the context is still the parent div and not the newly appended div..
You need to find it first inside the parent and then add the class..
EDIT
If you want to just add the class to the last appended element ... Find the last div in the parent and then add the class to it..
This will make sure you are not adding the class to all the div's every single time you iterate in the loop..
t.y.append('<div></div>').find('div:last').addClass('lol'+i);
Try this:
t.y.append($('<div></div>').addClass('lol'+i));
Fiddle: http://jsfiddle.net/gromer/QkTdq/
var t = this;
$(this.x).each(function(i, obj) {
//append new div and add class too <div></div>
var d = $('<div />').addClass('lol' + i);
t.y.append(d);
});
The problem is that append returns the container instead of the thing you just appended to it. I would just do the addClass before the append instead of after:
var t = this;
$(this.x).each(function(i, obj) {
//append new div and add class too <div></div>
t.y.append($('<div></div>').addClass('lol'+i));
});
EDIT ... or, in other words, exactly what Gromer said. Beat me by five whole minutes, too. I'm getting slow.
You don't mention why you want to number the class attribute to your list items, but in the case that you are actually using them for css don't forget you have :odd and :even css selector attritbutes and also the equivalent odd/even jQuery selectors.
http://www.w3.org/Style/Examples/007/evenodd.en.html
http://api.jquery.com/odd-selector/
I didn't find anything like this. notice the class attribute!
$.each(obj, function (_index, item) {
resultContainer.append($('<li>', {
class: "list-group-item",
value: item.id,
text: item.permitHolderName || item.permitHolderId
}));
});

Add class name for generated Html using jquery

Below is html part
<li class="main_menu catagory_li" id="cat4">
<p class="ahead"><span class="heading">Item 4</span>
<span class="fright remove">close</span></p>
</li>
when i click close i copy the LI using below code,
$('.remove').live('click',function(){
var closed_elem_id = $(this).parent().parent().attr('id');
s = $(this).parent().parent().clone().wrap('<div>').parent().html();
$('li#'+closed_elem_id).remove();
console.log(s);
});
This one removes the LI in particular place and get the copy and store it in variable s.
My requirement is to add class called no-display in cloned copy like <span class="fright remove no-display">close</span> . I tried this many ways but it fails.
Kindly advice on this
NOTE : updated my question
A little optimized: http://jsfiddle.net/hKUd6/
Something like this:
$('.remove').live('click',function(){
var pLi = $(this).closest('li');
s = $('<div>').append(pLi.clone().addClass('no-display')).html();
pLi.remove();
console.log(s);
});
This whole thing is very sloppy. You don't need to use as much code as you have to accomplish the simple task you're attempting.
Try something like this:
$("li").on("click", ".remove", function(){
var $this = $(this),
liCont = $this.closest("p"),
parentLi = $this.closest("li");
liCont
.clone()
.wrap(
$("<div>").addClass("no-display")
)
.appendTo("body");
parentLi.remove();
});
What we do here is capture the click event on any .remove elements. We select the parent p (which we later clone to wrap with a div) as well as the parent li. We clone the p element (including its contents), wrap it with a div element (which we create using DOM scripting and add the class), and append the finished product to the body (you can change that if needed). We then remove the original li.
Try with this code, it should work:
$('.remove').live('click',function(){
var closed_elem = $(this).closest("li"); //get the li to be closed/removed
var clonedElem = closed_elem.clone().find("span.remove").addClass("no-display"); //clone the original li and add the no-display class to the span having remove class
closed_elem.remove(); //remove the original li
console.log(clonedElem);
});
Please check below lines of code.
first of all you need to get current class name using jquery:
$('li #cat4').find('span').each(function(){
var classname = $(this).attr('class');
$(this).addClass(classname+' no-display');
});
This is not a complete code of your task, but its just a code by which you can get a current class and then add more required string to it and set new class.
Thanks.

Categories