Appending new container on click - javascript

I'm trying to learn HTML and Javascript/jQuery. If I have a container which holds a title, an image, a description and a number, then I want to create a new container with the exact same format (except the values will be different), how is this commonly done?
This is an example of the format I'm looking for in each item.
<li>
<div>
<div>
Image Name
</div>
<div>
<a href=URL>
<img src='image_url'>
</a>
</div>
<div>
Description
</div>
<div>
num_comment Comments
</div>
</div>
</li>
Do I just create a string and concatenate with the actual values for the image, then add that string to some variable I've saved called html_content, and then set the html value to html_content? Is that the common way of doing this or is there a better way?
EDIT
To give a better idea of what I'm currently doing, here's the javascript:
var html1 = '<li><div><div>';
var html2 = '</div><div><a href="';
var html3 = '"><img src="';
var html4 = '"></a></div><div>';
var html5 = '</div><div>';
var html6 = '</div></div></li>';
function render(pics){
for (var i in pics){
html = html + html1 + pics[i].name + html2 + pics[i].image_url + html3 + ...
};
$('pics').html(html);
}

In jQuery you just have to use the append() function to add on to something.
You could do something like...
$('select element').append('<li><div>....etc.');
and where you want a different value you can use a variable.

You can use .clone() and create a copy of this, then iterate through the cloned object and change what you need:
var $objClone = $("li").clone(true);
$objClone.find("*").each(function() {
//iterates over every element. customize this to find elements you need.
});
To change the image source you can do:
$objClone.find("img").attr("src", "new/img/here.jpg");
Fiddle demoing the concept: http://jsfiddle.net/H9DnA/1/

You may find it useful to explore some of the JavaScript templating libraries. The essential idea is that you create a template of your markup:
<li>
<div>
<div>
{{name}}
</div>
<div>
<a href="{{url}}">
<img src="{{imageUrl}}">
</a>
</div>
<div>
{{description}}
</div>
<div>
{{comments}}
</div>
</div>
</li>
Then you merge it against some associated matching object and insert it into your document:
{ name: 'Image Name',
url: 'http://example.com',
imageUrl: 'http://example.com/image.jpg',
description: 'Description',
comments [ { text: 'Comment' } ]
}

function render(pics)
{
var theList = document.getElementByid("LIST ID");
for (var i in pics){
var listItem = document.createElement('li'); // Create new list item
var nameDiv = document.createElement('div'); // Create name DIV element
nameDiv.innerHTML = pics[i].name; // Insert the name in the div
var img = document.createElement('img'); // Create Img element
img.setAttribute('src',pics[i].src); // Assign the src attribute of your img
var imgDiv = document.createElement('div'); // Create Img Div that contains your img
imgDiv.appendChild(img); // Puts img inside the img DIV container
var descDiv = document.createElement('div'); // Create Description DIV
descDiv.innerHTML = pics[i].description; // Insert your description
listItem.appendChild(nameDiv); // Insert all of you DIVs
listItem.appendChild(imgDiv); // inside your list item
listItem.appendChild(descDiv); // with appropriate order.
theList.appendChild(listItem); // Insert the list item inside your list.
}
}

I think this will work just fine:
$('#button').click(function () {
var html1 = '<li><div><div>';
var html2 = '</div><div><a href="';
var html3 = '"><img src="';
var html4 = '"></a></div><div>';
var html5 = '</div><div>';
var html6 = '</div></div></li>';
function render(pics){
for (var i in pics){
html = html + html1 + pics[i].name + html2 + pics[i].image_url + html3 + ...
$("ul").append(html);
}
}
// call render
});
I didn't do a test run on your code so there might be an error somewhere. My tweak adds this line $("ul").append(html); inside your loop

Related

How can I add a span to h3 Element with javascript

I'm making a chat and I want to add an avatar pics feature so I figured it might work well with span, but the problem is I don't know how to add the span to the element.
let avatar = document.createElement("span");
let userMessage = document.createElement("H3");
avatar.setAttribute(userMessage);
userMessage.innerHTML = username + ": " + message;
//document.getElementById("chat").appendChild(avatar);
document.getElementById("chat").appendChild(userMessage);
userMessage.style.background = color;
userMessage.style.textAlign = "left";
document.getElementById("msg").value = "";
I am assuming that you have div with id="chat" and you want to append an h3 tag in a span and then append the chat div so your code will look like this
var username="zulqarnain jalil";
var message ="welcome back, have a nice day";
var color='lightgrey';
var avatar = document.createElement("span");
var userMessage = document.createElement("h3");
userMessage.innerHTML = username + ": " + message;
userMessage.style.background = color;
userMessage.style.textAlign = "left";
avatar.appendChild(userMessage);
document.getElementById("chat").appendChild(avatar);
//document.getElementById("msg").value = "";
<div id="chat">
</div>
I have created a chatbot snippet for you, here you can test it
var username="zulqarnain jalil";
function sendMessage()
{
var message =document.getElementById('messagebox').value;
if(message)
{
document.getElementById('messagebox').value='';
var color='lightgrey';
var avatar = document.createElement("span");
var userMessage = document.createElement("h3");
userMessage.innerHTML = username + ": " + message;
userMessage.style.background = color;
userMessage.style.textAlign = "left";
avatar.appendChild(userMessage);
document.getElementById("chat").appendChild(avatar);
}
else
{
// message empty
}
}
//document.getElementById("msg").value = "";
<div id="chatBox">
<div id="chat">
</div>
<div>
<input type="text" id="messagebox" />
<input type="button" onclick="sendMessage()" value="Send" />
</div>
</div>
First you need to add the span as a child of the H3 element.
I think the best approach to this problem is creating a class Message. Initializing that class creates h3 and span with unique ids stored in a variable id for future use. The class will also add the h3 as a child of it's parent element ( what ever it is ), and the span as a child of the h3 element.
var counterText = 0;
var counterAvatar = 0;
class UserMessage {
constructor(msgTxt, avatar){
// This block initializes the text message of the user
// It will also add an id to the tag for future use
let msgTxt = document.createTextNode(msgTxt);
this.messageID = 'text' + counterText;
this.message = document.createElement('h3');
this.message.appendChild(msgTxt);
this.message.setAttribute('id', this.messageID);
counterText++;
// This block creates an img element with the attributes src and id
this.avatarID = 'avatar' + counterAvatar;
this.avatar = document.createElement('img');
this.avatar.setAttribute('src', avatar);
this.avatar.setAttribute('id', this.avatarID);
counterAvatar++;
// This block appends the avatar element to the text and the text to the
// chat div.
let chat = document.getElementById('chat');
this.message.appendChild(this.avatar);
chat.appendChild(this.message);
}
}
to initialize a new instance:
var message = new UserMessage("Hello, this is a text message!",'<path/to/avatar>')
this is an object oriented aproach.
you could also just append the avatar to the message and the message to the chat.
But I think aproaching the problem in an object oriented way is much better since it will save time in the future when you're updating your app.
Markdown works fine in here.
Block-level HTML elements have a few restrictions:
They must be separated from surrounding text by blank lines.
The begin and end tags of the outermost block element must not be indented.
Markdown can't be used within HTML blocks.

Get all image src from array of image src and placing them into div with Javascript?

I have I array of images src ["http://src1", "http://src2", "http://src3"]. I want for get all images from that array and manipulate them, for example placing them into a div?
var imgSrc = ["http://src1,http://src2,http://src3"];
var string = imgSrc[0];
console.log(string);
var array = string.split(",");
console.log(array);
var inHTML = '';
console.log(array[0]);
$.each(array, function(key, value){
var html = '<img src="'+ value[key]+'" align="center">';
inHTML += html;
});
$('div#item').html(inHTML);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="item"></div>
You can append the dynamically created Images from the array to a perticular div. Hope this helps...
HTML
<html>
<head>
</head>
<body>
<h1>Images</h1>
<div id="content">
</div>
<script src="app.js"></script>
</body>
</html>
JS
var imageSources = ["http://src1,http://src2,http://src3"]
imageSources.forEach(element => {
var img = document.createElement("img");
img.width = '300';
img.height = '300';
img.src = element;
document.getElementById("content").appendChild(img)
};
I think your array is somewhat like:
["http://src1","http://src2","http://src3"]
If I am right then you can do something like:
var y = x.map((key,value)=>{return ('<div>'+key+'</div>')});
y will be an array with the div tags containing images.
Hope, I understood your problem.
I want for get all images from that array and manipulate them, for
example placing them into a div
You can dynamically generate img elements and add them to a div.
To iterate through the array you could use forEach, creating the img elements within the loop using createElement and appendChild to append the image to the div
See example below, which should get you started.
var images = ["https://placehold.it/50x50","https://placehold.it/25x25","https://placehold.it/75x75"];
var target = document.getElementById('target');
images.forEach(function(imgSrc){
var newImg = document.createElement("img");
newImg.src = imgSrc;
target.appendChild(newImg);
})
<div id="target"></div>
Creating an Array:
You must use the following syntax to to create a JavaScript Array:
var array_name = [ item1, item2, ... ];
Or Using the JavaScript Keyword new:
var array_name = new Array( item1, item2, ... );
So your array must be like this:
var image_source = [ 'http://src1', 'http://src2', 'http://src3' ];
Access the Elements of an Array:
You refer to an array element by referring to the index number. for example this statement accesses the value of the first element in cars:
var first_image = image_source[ 0 ];
Example:
var image_source = [ 'http://img1', 'http://img2', 'http://img3' ];
document.getElementById( 'demo' ).innerHTML = image_source[ 1 ];
<div id="demo"></div>

JavaScript: Dynamically created html-like string won't tun into html

in DOM I already have a wrapper
<div id="wrapper"></div>
which I need to fill with bunch of divs, where each will represent new category.
Each category will be then filled with various cards representing items of that category. Like this:
<div id="wrapper">
<div data-category="puppy">
Dynamically created category wrapper
<div class="puppy1">...</div>
<div class="puppy2">...</div>
</div>
<div data-category="cat">
...
</div>
</div>
I use following code to create and fill category, but I always end up either having empty category or having a string inside reprenting the html.
var categoryWrapper = document.createElement("div");
categoryWrapper.setAttribute("data-category", key);
categoryWrapper.innerHtml = htmlString;
Here is a fiddle demo of my issue.
https://jsfiddle.net/uuqj4ad5/
I'll be grateful for a help.
There is a typo, innerHml should be innerHTML(Javascript object properties are case sensitive) otherwise it simply add an additional property and nothing gets happened.
categoryWrapper.innerHTML = htmlString;
var htmlString = "<div class='card'><div class='cardImg'><img src='http://cdn.cutestpaw.com/wp-content/uploads/2012/07/l-Wittle-puppy-yawning.jpg' alt='Puppy'></div><div class='cardContent'><div class='cardInfo'><p>Puppy Yawning</p></div><div class='cardDesc'><p>Awww!</p></div></div></div>";
var outerWrapper = $("#wrapper");
var categoryWrapper = document.createElement("div");
categoryWrapper.innerHTML = htmlString;
outerWrapper.append(categoryWrapper);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<h3>
Under this title various categories should be dynamically created
</h3>
<div id="wrapper">outerWrapper waiting for dynamic data...</div>
</div>
FYI : If you want to remove the existing content then use html() method instead of append() method.
innerHtml
should be
innerHTML
Javascript is case sensitive
If you are using jQuery why do you want to mix jQuery and Vanilla JS.
var outerWrapper = $("#wrapper");
// I created new categoryWrapper object
var categoryWrapper = $('<div/>', {
html: htmlString
});
debugger;
// WHen I have the category filled with inner data, I will append it into outerwrapper
outerWrapper.append(categoryWrapper);
jsFiddle
Checkout my fiddle:-
https://jsfiddle.net/dhruv1992/1xg18a3f/1/
your js code should look like this
// This is dynamically filled html template. The data comes from some JSON.
var htmlString = "<div class='card'><div class='cardImg'><img src='http://cdn.cutestpaw.com/wp-content/uploads/2012/07/l-Wittle-puppy-yawning.jpg' alt='Puppy'></div><div class='cardContent'><div class='cardInfo'><p>Puppy Yawning</p></div><div class='cardDesc'><p>Awww!</p></div></div></div>";
// This outer wrapper will in the end contain few categories
var outerWrapper = $("#wrapper");
outerWrapper.append('<div>'+htmlString+'</div>')

What is the best way to create a list of text and images, using JavaScript and little to no HTML?

So I have successfully made a list using strictly HTML and CSS and that was simple enough. Now, I want to create the same list, while using JavaScript, for the most part. I'm not so sure why its so confusing for me.
Now I understand that in my HTML file, I must create a div for that list, and can implement the content in my .js file, while styling it however in my .css file. So here's what I have (and what I'm assuming is all I need) in my html file:
<div class="container">
<div class="row" id="content-list"></div>
</div>
I haven't really touched my css file yet because I like to save the styling for last.
I have a bit of a starting point in my .js file but let me explain a few things before showing my meaningless code (which I wrote based off what I was trying to understand from other examples or tutorials, but didn't fully know what I was doing). All I want, is to display a list of my favorite movies, along with an image aligned next to each movie title. That's all! I don't plan on adding any elements later, or removing... I just want my list but I can't figure it out! I feel so dumb.
Anyway, here's what I have (and yes I'm including the part I had commented out because I'm not sure which way is better, and I apologize for not finishing what I started with):
// JavaScript Document
function myMovies (movieTitle, movieThumb) {
this.movieTitle = movieTitle;
this.movieThumb = movieThumb;
}
/**
var contentList = [
{'content_title':'District 9', 'img_src':'district9.jpg', 'target_dir':''},
{'content_title':'Gladiator', 'img_src':'gladiator.jpg', 'target_dir':''},
{'content_title':'Django Unchained', 'img_src':'django.jpg', 'target_dir':''},
{'content_title':'Fantastic Mr. Fox', 'img_src':'fox.jpg', 'target_dir':''},
{'content_title':'Master and Commander', 'img_src':'master.jpg', 'target_dir':''}
];
**/
myMovies.prototype.myMovies = function (list) {
var html =
};
Please help me, I'm so lost. And if you could also please comment any code you give me, that would be so appreciated. Thank you!
Well, you can do this:
var contentList = [
{'content_title':'District 9', 'img_src':'district9.jpg', 'target_dir':''},
{'content_title':'Gladiator', 'img_src':'gladiator.jpg', 'target_dir':''},
{'content_title':'Django Unchained', 'img_src':'django.jpg', 'target_dir':''},
{'content_title':'Fantastic Mr. Fox', 'img_src':'fox.jpg', 'target_dir':''},
{'content_title':'Master and Commander', 'img_src':'master.jpg', 'target_dir':''}
];
var htmlStr = ''; // declare a variable which will hold the html for list
for(var i=0;i<contentList.length;i++) // create a loop to loop through contentList
{
htmlStr += "<div><img src='"+contentList[i].img_src+"'/>"+contentList[i].content_title+"</div>";
}
document.getElementById('content-list').innerHTML = htmlStr; // assign the innerhtml
I've commented the code.
LIVE DEMO
By the look of that var html =, I take it you're planning to build up a string of HTML code? I'm gonna assume you have your own plans on how to do that. It's mostly string concatenation, after all.
After you have html ready, use document.getElementById to get a reference to the container and set its innerHTML property to the string you've constructed.
document.getElementById('content-list').innerHTML = html;
In Javascript:
var contentList = [
{'content_title':'District 9', 'img_src':'district9.jpg', 'target_dir':''},
{'content_title':'Gladiator', 'img_src':'gladiator.jpg', 'target_dir':''},
{'content_title':'Django Unchained', 'img_src':'django.jpg', 'target_dir':''},
{'content_title':'Fantastic Mr. Fox', 'img_src':'fox.jpg', 'target_dir':''},
{'content_title':'Master and Commander', 'img_src':'master.jpg', 'target_dir':''}
];
var myList = document.createElement("ul"); // create the list
for (var i = 0; i < contentList.length; i++) { // for each Object in your Array
var myItem = document.createElement("li"); // create a item for the list
var myAnchor = document.createElement("a"); // create an anchor for the target_dir property
myAnchor.setAttribute("href", contentList[i].target_dir); // set the href attribute for the anchor
var myTitle = document.createTextNode(contentList[i].content_title); // create the text node to be inside the anchor (from the content_title property)
myAnchor.appendChild(myTitle); // append the text into the anchor
var myImage = document.createElement("img"); // create the DOMElement for the image
myImage.setAttribute("src", contentList[i].img_src); // set the attribute src (from the img_src property)
myImage.setAttribute("alt", contentList[i].content_title); // set the alt attribute only cause it's required for both XHTML and HTML5
myItem.appendChild(myAnchor); // append the anchor into the item list
myItem.appendChild(myImage); // append the image into the item list
myList.appendChild(myItem); // append the item list into the list
}
document.getElementById("content-list").appendChild(myList); // append the list into the div you've created
In jQuery:
var myList = $("<ul>")
for (var i = 0; i < contentList.length; i++) {
var myItem = $("<li>");
var myAnchor = $("<a>").attr("href", contentList[i].target_dir).text(contentList[i].content_title);
var myImage = $("<img>").attr("src", contentList[i].img_src).attr("alt", contentList[i].content_title);
myItem.append(myAnchor).append(myImage);
myList.append(myItem);
}
$("#content-list").append(myList);
In "ugly" (String concatanation) Javascript:
var myHTML = "<ul>";
for (var i = 0; i < contentList.length; i++) {
myHTML += "<li><a href='" + contentList[i].target_dir + "'>" + contentList[i].content_title + "</a><img src='" + contentList[i].img_src + "' alt='" + contentList[i].content_title + "' /></li>";
}
myHTML += "</ul>"
document.getElementById("content-list").innerHTML = myHTML;

how to appending content from array and then clear it in jQuery

Hi i would like to create an array from the title and src of an image set. Then append it to a list, then clear the array (the images in the set changes) then clear the array and the list. repeat it again and again as the images change in the set.
Here is the HTML:
<div id="imageholder">
<img src="images/a001.png" title="orange"/>
<img src="images/a002.png" title="red apple"/>
<img src="images/a003.png" title="green apple"/>
<img src="images/a004.png" title="red apple"/>
</div>
<ul id="list"></ul>
and here is the code:
title_array = [];
src_array = [];
function sumarychange() {
$("#imageholder img").each(function() {
// pushing each values into arrays
title_array.push($(this).attr("title"));
src_array.push($(this).attr("src"));
// i think this part will append the content in the arrays
var list = $('#list');
var existing_item = $('#list_'+ title);
// removing items with the same titles
if (existing_item.length < 1){
var new_item = $('<li />');
new_item.attr('id', 'list_'+ title);
new_item.html('<div>' + title + '</div><img src="' + src + '" />');
list.append(new_item);
}
});
// i think this will set the arrays back to empty
title_array.length = 0;
src_array.length = 0;
}
this is just a sample. In actual the image has more tags. i have no clue how to empty out the list when this function is called again. im just learning coding now and i have no idea how to correct this to make it work.
This looks to me like an XY problem.
Judging from your example code above as well as your previous question, I'm guessing what you're trying to do is update a list of entries based on the attributes of an existing set of elements, but with items with duplicate titles only displayed once.
Assuming I got that right, here's one way to do it: (demo: http://jsfiddle.net/SxZhG/2/)
var $imgs = $("#imageholder"), $list = $("#list");
function summary_change() {
// store data in tmp obj with title as key so we can easily ignore dups
var store = {};
$imgs.find("img").each(function() {
if (store.hasOwnProperty(this.title)) return; // ignore dup title
store[this.title] = this.getAttribute("src");
});
$list.empty(); // empty the list
for (var title in store) { // add new list items
$("<li>")
.append($("<div>", {"text":title}))
.append($("<img>", {"src":store[title]}))
.appendTo($list);
}
}
Note that if more than one image has the same title, only the src of the first one is used in the summary results. If you wish to use the src of the last item found, simple remove the line if (store.hasOwnProperty(this.title)) return;.

Categories