Append <div> using jquery's forEach and templatePlugin - javascript

I'm struggeling for some hours with the following problem:
Iterating through a object using jquery's forEach method
For each object element, a template should be used, which also fills the information in the template. The plugin, which I am using: jquery-tempalte
For each object the template should be appended to a <div>
Unfortunately only the last object element is visualized and loaded to the DOM. All other divs, which are created during the steps before, were overwritten.
Find here an jsFiddle, which demonstrates my problem: http://jsfiddle.net/7oq053od/1/
Do you have any idea, what I am missing?
Would be great to get some feedback :)

From Options section on the github webpage you can see this third parameter with the append property set as true.
Just consider add it to your script like this :
$.each(results.features, function (key, value) {
$("#homeView").loadTemplate($("#template"), {
geoFenceName: value.attributes.title,
geoFenceDescription: value.attributes.description
}, {append: true});
});
Here is a working JsFiddle.

For appending multiple div's . you should create a main container that contains all the child div's and when displaying, each div element will be created and append to main container everytime.
Here's a sample code:
<div id="container"></div>
//now in javascript create child div elements and append to main container
<script>
for(var items in data)
{
var newChild = $(document.createElement('div'));
$(newChild).css({
//some css code
});
//now appending it to main container
$('#container').append(newChild);
}
</script>

It seems the template plugin applies the templated values to the same element. If you clone the element, your script works.
$.each(results.features, function (key, value) {
$("#homeView").clone().loadTemplate($("#template"), {
geoFenceName: value.attributes.title,
geoFenceDescription: value.attributes.description
}).appendTo('#fences');
});
See updated fiddle here

The problem is that the loadTemplate function overwrites the div. You can fix that by cloning the template container and then append it to '#homeWiew'.
I created a fork from your jsfiddle that worked for me:
http://jsfiddle.net/6ksdnejw/

Related

.appendChild() an HTML element on click

I wanted to copy an entire row including its' siblings and contents on button click. When I click the button the element, it appears in the console but doesn't append to the page. This is my code:
It doesn't show any error messages. I've tried innerHTML/outerHTML or append() it doesn't work.
$(document).ready(function() {
$('#addSubFBtn').on('click', function() {
var itm = document.getElementById("trFb");
var wrapper = document.createElement('div');
var el = wrapper.appendChild(itm);
document.getElementById("tbFb").append(el);
console.log(el);
});
});
Seems like what you're trying to do is clone the item after you get it from your document. W3schools website explains how to accomplish this. Check out the link: https://www.w3schools.com/jsref/met_node_clonenode.asp
Once you clone the node, [appendchild] should work as intended
Not sure (as said without seeing related HTML) but i see flaw in your logic:
var itm = document.getElementById("trFb");
still exist on the document(so in the page) so you've to retrieve it before you want to add/move it to another place.
using .removeElement will return you removed element(or null if no element matche the selector) so correct script should be:
var itm=document.getElementById("trFb").parentNode.removeChild(document.getElementById("trFb"));
as shown here to remove element you've to use method on to parent element.
So you can add it to any other element existing.
For more specific use or element created in global JS variable (such an createElement not yet appended) you can see :document.createDocumentFragment(); as explained here https://developer.mozilla.org/en-US/docs/Web/API/Document/createDocumentFragment

Create unique buttons dynamically

I'm new to jQuery and am trying to create jQuery UI buttons dynamically and them to a list. I can create one list item but no more are appended after it. What am I doing wrong?
$('#buttonList').append('<li><button>'+ username + '</button>')
.button()
.data('type', userType)
.click(function(e) { alert($(this).data('type')); })
.append('<button>Edit</button></li>');
<div>
<ul id="buttonList">
</ul>
</div>
This only creates one list item with two buttons (although the second button seems to be encased in the first one, but I can probably figure that issue out). How do I get it to create multiple list items with their own unique 'data' values (i.e. I can't do a find() on a particular button class and give it data values as all buttons would then have the same data)?
I suggest to exchange the position of what you are appending and where you are appending to. This way, you retain the appended object, and should be able to work with it as a standard jQuery selector. From your code i commented out the .button() and the .append() lines, because i'm not sure what you want to do with them. Should you need help adding those lines, just drop a comment to my answer ;)
Oh, i almost forgot: i use var i to simulate different contents for username and userType data.
A JSFiddle for you is here: http://jsfiddle.net/cRjh9/1/
Example code (html part):
<div>
<p id="addButton">add button</p>
<ul id="buttonList">
</ul>
</div>
Example code (js part):
var i = 0;
$('#addButton').on('click', function()
{
$('<li><button class="itemButton">'+ 'username' + i + '</button></li>').appendTo('#buttonList')
//.button()
.find('.itemButton')
.data('type', 'userType'+i)
.click(function(e) { alert($(this).data('type'));
})
//.append('<button>Edit</button></li>')
;
i++;
});
You need complete tags when you wrap any html in a method argument. You can't treat the DOM like a text editor and append a start tag, append some more tags and then append the end tag.
Anything insterted into the DOM has to be complete and valid html.
You are also not understanding the context of what is returned from append(). It is not the element(s) within the arguments it is the element collection you are appending to. You are calling button() on the whole <UL>.
I suggest you get a better understanding of jQuery before trying to chain so many methods together
Just a very simplistic approach that you can modify - FIDDLE.
I haven't added the data attributes, nor the click function (I'm not really sure I like the
inline "click" functions - I generally do them in jQuery and try to figure out how to make
the code efficient. Probably not very rational, but I'm often so).
JS
var names = ['Washington', 'Adams', 'Jefferson', 'Lincoln', 'Roosevelt'];
for( r=0; r < names.length; r++ )
{
$('#buttonList').append('<li><button>'+ names[r] + '</button></li>');
}
$('#buttonList').append('<li><button>Edit</button></li>');

Variable with HTML content parsing

I have this variable called $reservas that contains a string with HTML Tables. I want to remove parts of the tables (.tdRemove), BEFORE I assign them to the div #cenas.
if ($reservas){
$($reservas).find('.tdRemove').each(function(){
console.log($(this).html());
$(this).remove();
});
$("#cenas").html($reservas);
}
I tried this, but it doesn't seem to remove anything.
I've also tried:
$($reservas).find('.tdRemove').remove(); and $($reservas).remove('.tdRemove');
Nothing works. Any suggestions?
Is there any way to tell jQuery that the variable holds html content, and should be parsed as that? If so, how? ..
After converting your string to a jQuery object, it is now a series of DOM objects (in a document fragment) held in the jQuery object. After removing the .tdRemove objects in that fragment, you can then just append that directly to your DOM. No need to go back to HTML:
if ($reservas){
var item = $($reservas);
item.find('.tdRemove').remove();
$("#cenas").empty().append(item);
}
Also, your code didn't work because the $reservas string of HTML was never modified.
I think, from what the documentation tells me, you can only remove() what is already inside the DOM.
Remove the set of matched elements from the DOM.
Maybe you want to add your table first, set it to ? display: none`, then filter for elements to remove and finally display the table.
if ($reservas) {
$("#cenas")
.hide()
.html($reservas)
.find('.tdRemove').each(function(){
console.log($(this).html());
$(this).remove();
})
.show();
}

How do I insert a block of html after a block that I have just rendered on the DOM

I am building a block of nested divs around a specific element on the client. I am using jQuery's .wrap() initially to get the first part of the block which is working fine. But now I want to attach the ending block after the element I am wrapping and I am finding I can't attach it to anything because it is all being created at the same time. I tried using insertAfter() but I don't want it to be a sibling of the element I am wrapping, I want it to come after it's parent.
Here is my code:
$(document).ready(function() {
buildShadows('#section');
});
function buildShadows(element){
$(element).wrap("<div class='section_shadow_wrapper'><div class='section_shadow_curve'><div class='section_shadow_outer'><div class='section_shadow_inner_left'><div class='section_shadow_inner_right'>");
$("<div class='section_shadow_bottom_left'><div class='section_test_bottom_right'>").insertAfter(element);
}
What I am trying to do is append the first element of the second part (section_shadow_bottom_left) as a sibling of 'section_shadow_inner_right' but after 'element'
Any help would be appreciated.
Thanks.
You should be able to just traverse up to the new parent you just created.
Have you tried this?
function buildShadows(element){
$(element).wrap('<div class="section_shadow_wrapper clearfix"><div class="section_shadow_curve"><div class="section_shadow_outer"><div class="section_shadow_inner_left"><div class="section_shadow_inner_right">')
.parent().after('<div class="section_shadow_bottom_left"><div class="section_test_bottom_right">');
}
Try traversing to the next sibling of the original element and using .insertBefore() on it.
var nextsibling = $(element).next();
//Wrap code
$("<div class='section_shadow_bottom_left'><div class='section_test_bottom_right'>").insertBefore(nextsibling);

jQuery: if hovering over an element injects something into the DOM, can I still reference it?

If hovering over an element injects something into the DOM, can I still reference it?
Or do I have to use the live plugin?
I'm using jQuery 1.3.2
i.e. can I do
$("#someItem").attr("src", "htt...")
on it?
I am trying to do it, but I think its not working b/c its a newly added item to the DOM.
Yes, an element that has been added to the DOM can be selected and referenced.
Or, if you already had a reference to it that you used when you added it to the DOM, you can continue to use that reference after it has been added as well.
Using this example, you can see that you can both use a current reference to a newly created element, as well as make a new reference to it.
http://jsfiddle.net/Czuvx/
HTML:
<div id='button'>hover me</div>
jQuery:
$('#button').hover(function() {
$('#newElement').remove();
var $myNewElement = $('<div id="newElement">new Element</div>');
$('body').append($myNewElement);
$myNewElement.css({color:'red'});
},
function() {
// This function has completely different namespace
// from the one that created and inserted #newElement
// and I can get a reference to it just like any other element
var $newReferenceToElement = $('#newElement');
$newReferenceToElement.css({color:'blue'});
});
Showing a bit more of your code would be helpful, but I think I get the general idea.
If you're just looking to add events or something to that item, you can do it before you append the item.
(function($){
$(function(){
$("#link").hover(
function(){
var $div = $("<div class='inserted_div'></div>").bind("click",function(){ ... });
$("body").append($div);
}),
function(){
});
});
})(jQuery);
So just bind the events or attributes at the time of creation, before you append it.

Categories