I have created input fields dynamically. After choosing file, I want to preview each image. But I can preview only first one. Run the code snippet below to understand me.
I would be glad if someone can help me.
$(document).ready(function () {
$("#imageBrowes").change(function () {
var File = this.files;
if (File && File[0]) {
ReadImage(File[0]);
}
})
})
var ReadImage = function (file) {
var reader = new FileReader;
var image = new Image;
reader.readAsDataURL(file);
reader.onload = function (_file) {
image.src = _file.target.result;
image.onload = function () {
var height = this.height;
var width = this.width;
var type = file.type;
var size = ~~(file.size / 1024) + "KB";
$("#targetImg").attr('src', _file.target.result);
$("#description").text("Size:" + size + ", " + height + "X " + width + ", " + type + "");
$("#imgPreview").show();
var html = '';
html += '<div class="col-md-6"> <div class="btn "> <input type="file" name="Photo" id="imageBrowes" class="inputfile" multiple /> </div> <div id="imgPreview" class="thumbnail" style="display:none"> <img class="img-responsive img-fluid" id="targetImg" /> <div class="caption"> <i class="fas fa-trash-alt"></i> <span id="description"></span> </div> </div> </div>';
$('#newRow').append(html);
}
}
}
<div id="newRow">
<div class="col-md-6">
<div class="btn ">
<input type="file" name="Photo" id="imageBrowes" class="inputfile" multiple />
</div>
<div id="imgPreview" class="thumbnail" style="display:none">
<img class="img-responsive img-fluid" id="targetImg" />
<div class="caption">
<i class="fas fa-trash-alt"></i>
<span id="description"></span>
</div>
</div>
</div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
What do you think of that solution?
$(document).ready(function() {
attachFileChangeHandler()
})
function attachFileChangeHandler() {
$(".imageBrowse").change(function() {
var File = this.files;
if (File && File[0]) {
ReadImage($(this).parent().parent(), File[0]);
}
})
}
function createNewFileInput() {
var html = '';
html += `
<div class="col-md-6">
<div class="btn">
<input type="file" name="Photo" class="inputfile imageBrowse" multiple />
</div>
<div class="thumbnail imgPreview" style="display:none">
<img class="img-responsive img-fluid targetImg"/> <div class="caption">
<a href="#" id="Clearphoto">
<i class="fas fa-trash-alt"></i></a>
<span class="description"></span>
</div>
</div>
</div>`;
$('#newRow').append(html);
setTimeout(attachFileChangeHandler, 100)
}
var ReadImage = function(parent, file) {
var reader = new FileReader;
var image = new Image;
reader.readAsDataURL(file);
reader.onload = function(event) {
var data = event.target.result;
image.src = data;
image.onload = function() {
var height = this.height;
var width = this.width;
var type = file.type;
var size = ~~(file.size / 1024) + "KB";
parent.find(".targetImg").attr('src', data);
parent.find(".description").text("Size:" + size + ", " + height + "X " + width + ", " + type + "");
parent.find(".imgPreview").show();
createNewFileInput();
}
}
}
<div id="newRow">
<div class="col-md-6">
<div class="btn ">
<input type="file" name="Photo" class="inputfile imageBrowse" multiple />
</div>
<div class="thumbnail imgPreview" style="display:none">
<img class="img-responsive img-fluid targetImg" />
<div class="caption">
<a href="#" id="Clearphoto">
<i class="fas fa-trash-alt"></i>
</a>
<span class="description"></span>
</div>
</div>
</div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
Related
I've trying to make research of it but couldn't find any solution. I'm new on javascript so maybe I'm doing something wrong on my function. I want to show a pdf icon at my thumbnail when we uploading pdf file. except from pdf it will show an images of the image that we upload Please assist me
Here are my JavaScript :
function readURL(input, imgno) {
if (input.files && input.files[0]) {
var imgPath = input.files[0].value;
var ext = $(input).val().split('.').pop().toLowerCase();
if ($.inArray(ext, ['gif', 'png', 'jpg', 'jpeg', 'pdf']) == -1) {
MsgBox('Message', 'Only file with extension ".jpg", ".jpeg" , ".png" , ".gif", ".pdf" are allowed');
$(input).filestyle('clear');
} else {
if (input.files[0].size > 1024000) {
MsgBox("Message", "Uploaded File <b> " + input.files[0].name + "</b> " + input.files[0].size / 1000 + "KB");
//bootstrap_alert.warning('#sender-alert', "Uploaded File <b> " + input.files[0].name + "</b> " + input.files[0].size / 1000 + "KB");
'data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw%3D%3D').attr("title", "");
$(input).filestyle('clear');
return;
}
}
var image_holder = $("#image-holder" + imgno);
image_holder.empty();
var filename = input.files[0].name;
//var extn = imgPath.substring(imgPath.lastIndexOf('.') + 1).toLowerCase();
//if (extn == "gif" || extn == "png" || extn == "jpg" || extn == "jpeg") {
var reader = new FileReader();
reader.onload = function (e) {
$("<img />", {
"src": e.target.result,
"class": "thumb-image",
"title": filename,
"width": "100",
"height": "100"
}).appendTo(image_holder);
// $(this).children('a').addClass('active').end()
$("<button />", {
"class": "btn btn-default glyphicon glyphicon-trash btn-sm",
"type": "button",
"onclick": "ClearImage('" + imgno + "')"
}).appendTo(image_holder);
}
reader.readAsDataURL(input.files[0]);
}
}
Here is my HTML :
var base1 = string.Empty; var base2 = string.Empty; var base3 = string.Empty; var base4 = string.Empty; var base5 = string.Empty;
var imgSrc1 = string.Empty; var imgSrc2 = string.Empty; var imgSrc3 = string.Empty; var imgSrc4 = string.Empty; var imgSrc5 = string.Empty; ;
if (Model.Picture1 != null) { base1 = Convert.ToBase64String(Model.Picture1); imgSrc1 = String.Format("data:image/gif;base64,{0}", base1); }
else { base1 = "#"; }
if (Model.Picture2 != null) { base2 = Convert.ToBase64String(Model.Picture2); imgSrc2 = String.Format("data:image/gif;base64,{0}", base2); }
else { base2 = "#"; }
if (Model.Picture3 != null) { base3 = Convert.ToBase64String(Model.Picture3); imgSrc3 = String.Format("data:image/gif;base64,{0}", base3); }
else { base3 = "#"; }
if (Model.Picture4 != null) { base4 = Convert.ToBase64String(Model.Picture4); imgSrc4 = String.Format("data:image/gif;base64,{0}", base4); }
else { base4 = "#"; }
if (Model.Picture5 != null) { base5 = Convert.ToBase64String(Model.Picture5); imgSrc5 = String.Format("data:image/gif;base64,{0}", base5); }
else { base5 = "#"; }
<div class="gallery" id="gallery">
<ul class="enlarge clearfix list-inline" id="tempenlarge">
<li>
<div id="image-holder1">
<img class="img-thumbnail thumbnail-size" src='#imgSrc1' width="100" height="100" id="image1" />
<button class="btn btn-default glyphicon glyphicon-trash btn-sm" onclick="ClearImage('1')" type="button" />
</div>
<input id="file-1" name="uploadImages" type="file" accept="image/x-png, image/gif, image/jpeg, image/pdf" onchange="readURL(this, '1');" class="filestyle form-control " data-buttontext="GOV ID" data-buttonname="btn-primary" data-size="xs">
</li>
<li>
<div id="image-holder2">
<img class="img-thumbnail thumbnail-size" src='#imgSrc2' width="100" height="100" id="image2" />
<button class="btn btn-default glyphicon glyphicon-trash btn-sm" onclick="ClearImage('2')" type="button" />
</div>
<input id="file-2" name="uploadImages" type="file" onchange="readURL(this, '2');" class="filestyle" data-buttontext="DOCUMENT 1" data-buttonname="btn-primary" data-size="xs">
</li>
<li>
<div id="image-holder3">
<img class="img-thumbnail thumbnail-size" src='#imgSrc3' width="100" height="100" id="image3" />
<button class="btn btn-default glyphicon glyphicon-trash btn-sm" onclick="ClearImage('3')" type="button" />
</div>
<input id="file-3" name="uploadImages" type="file" onchange="readURL(this, '3');" class="filestyle" data-buttontext="DOCUMENT 2" data-buttonname="btn-primary" data-size="xs">
</li>
<li>
<div id="image-holder4">
<img class="img-thumbnail thumbnail-size" src='#imgSrc4' width="100" height="100" id="image4" />
<button class="btn btn-default glyphicon glyphicon-trash btn-sm" onclick="ClearImage('4')" type="button" />
</div>
<input id="file-4" name="uploadImages" type="file" onchange="readURL(this, '4');" class="filestyle" data-buttontext="DOCUMENT 3" data-buttonname="btn-primary" data-size="xs">
</li>
<li>
<div id="image-holder5">
<img class="img-thumbnail thumbnail-size" src='#imgSrc5' width="100" height="100" id="image5" />
<button class="btn btn-default glyphicon glyphicon-trash btn-sm" onclick="ClearImage('5')" type="button" />
</div>
<input id="file-5" name="uploadImages" type="file" onchange="readURL(this, '5');" class="filestyle" data-buttontext="DOCUMENT 4" data-buttonname="btn-primary" data-size="xs">
</li>
</ul>
</div>
This answer was written before OP updated the question, but the solution still applies.
Update
In a comment OP asked for further assistance. After reviewing the code I found 6 fatal errors that prevent it from working. Additionally, the code requires 3 minor modifications to display the default PDF image asked for in the question. The corrected code with comments may be found here: JSFiddle
The fiddle includes only the minimum changes to get the code working.
Problem
We want to display thumbnail images of the files the user has selected to upload. When the file is an image type we can use the dataURL to display the actual image. However, we can not display a thumbnail for a PDF file in the same way. And while it is possible to generate an image from the first page of a PDF, it's a complex and lengthy process. So as a simple alternative we want to use a default thumbnail image for PDF files.
Solution
The file object has a type property which we can use to determine if it is an image or some other kind of file. The type value will start with "image/" for gif, png, jpg, and other images. And for a PDF it will be "application/pdf".
So using a conditional (ternary) operator we can select the dataURL (target.result) for images or fallback to a default image for other file types. In this case we only have PDF and one default image, but it could be expanded to show different images for different file types.
let src = file.type.startsWith("image") ? e.target.result : defaultImage;
And this is the example output after selecting an image and a PDF:
Snippet
Unlike the original code, the snippet uses a template literal to display the thumbnail and metadata. However, the src variable could easily be added to OP's existing code.
function readURL(input, imgno) {
let file = input.files[0];
// file validation code not shown
var reader = new FileReader();
reader.onload = function(e) {
let src = file.type.startsWith("image") ? e.target.result : defaultImage;
let size = (file.size / 1024).toFixed(0);
let date = new Date(file.lastModified).toLocaleDateString();
$("#image-holder").append(`
<div id="image-holder-${imgno}" class="list-group-item">
<div class="row">
<div class="col-3">
<img src="${src}" class="thumb-image">
</div
<div class="col">
<ul style="font-size:small">
<li>Filename: ${file.name}</li>
<li>Type: ${file.type}</li>
<li>Size: ${size} kb</li>
<li>Date: ${date}</li>
<li>Remove</li>
</ul>
</div>
</div>
</div>
`);
}
reader.readAsDataURL(file);
}
let defaultImage = "https://upload.wikimedia.org/wikipedia/commons/thumb/8/87/PDF_file_icon.svg/833px-PDF_file_icon.svg.png";
upload.addEventListener("change", function(e) {
readURL(this, 1);
});
body {
font-family: sans-serif;
}
.thumb-image {
height: 100px;
width: auto;
border: 1px solid lightgray;
}
<input type="file" id="upload" accept="application/pdf,image/*">
<hr/>
<div id="image-holder" class="list-group"></div>
<!-- Bootstrap 4 -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.2/dist/css/bootstrap.min.css">
<script src="https://cdn.jsdelivr.net/npm/jquery#3.5.1/dist/jquery.slim.min.js" ></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.6.2/dist/js/bootstrap.bundle.min.js"></script>
I have six boxes. In this box already have dummy image.I need to upload image and that placed to the top box one by one and need to delete also.
When we upload image using upload button, that placed on above div one by one. Currently when i try to add image that placed to all the six divs.
<div class="image-wrapper" style="display:flex;">
<div class="image-wrap">
<img id="img_0" src="assets/images/img1.jpg" class="img-fluid">
</div>
<div class="image-wrap">
<img id="img_1" src="assets/images/unloaded-img.png" class="img-fluid">
</div>
<div class="image-wrap">
<img id="img_2" src="assets/images/unloaded-img.png" class="img-fluid">
</div>
<div class="image-wrap">
<img id="img_3" src="assets/images/unloaded-img.png" class="img-fluid">
</div>
<div class="image-wrap">
<img id="img_4" src="assets/images/unloaded-img.png" class="img-fluid">
</div>
<div class="image-wrap">
<img id="img_5" src="assets/images/unloaded-img.png" class="img-fluid">
</div>
</div>
<div class="upload-btn">
<div class="upload-btn-wrapper">
<button class="btn">Upload a file1</button>
<input type="file" id="files" name="files[]" multiple="">
</div>
</div>
$(document).ready(function() {
if (window.File && window.FileList && window.FileReader) {
$("#files").on("change", function(e) {
var files = e.target.files,
filesLength = files.length;
for (var i = 0; i < filesLength; i++) {
var f = files[i]
var fileReader = new FileReader();
fileReader.onload = (function(e) {
var file = e.target;
$("<div><span class=\"pip image-wrap\">" +
"<img class=\"imageThumb\" src=\"" + e.target.result + "\" title=\"" + file.name + "\"/>" +
"<br/><span class=\"remove\">X</span>" +
"</span></div>").insertAfter(".image-wrap");
$(".remove").click(function(){
$(this).parent(".pip").remove();
});
});
fileReader.readAsDataURL(f);
}
});
} else {
alert("Your browser doesn't support to File API")
}
});
You are using generic selector (".image-wrap") hence image getting added to all div. You can access divs with index 0... n using eq() method and maintain last index in a variable so that you can calculate next index and add next image to the div.
No need to add remove button click handler each time when file loaded as this will cause issue and you will end with multiple click handler. Better, put it outside using .on() so that dynamically added remove buttons will work.
See below code
$(document).ready(function() {
var imageIndex = 0; // variable to save index
if (window.File && window.FileList && window.FileReader) {
$("#files").on("change", function(e) {
var files = e.target.files,
filesLength = files.length;
for (var i = 0; i < filesLength; i++) {
var f = files[i]
var fileReader = new FileReader();
fileReader.onload = (function(e) {
var file = e.target;
$("<div><span class=\"pip image-wrap\">" +
"<img class=\"imageThumb\" src=\"" + e.target.result
+ "\" title=\"" + file.name + "\"/>" +
"<br/><span class=\"remove\">X</span>" +
"</span></div>").insertAfter(".image-wrap:eq(" + imageIndex + ")"); // use index
imageIndex++; // increment index by 1
});
fileReader.readAsDataURL(f);
}
});
} else {
alert("Your browser doesn't support to File API")
}
// put remove action here for dynamically added image
$(document).on("click",".remove",function(){
$(this).parent(".pip").remove();
});
});
Just because you are using a class selector with insertAfter its adding the image after every div having class .image-wrap instead use below code. Use the last() function to get the last .image-wrap and append it to that element. Below is a sample code.
$(document).ready(function() {
if (window.File && window.FileList && window.FileReader) {
$("#files").on("change", function(e) {
});
} else {
alert("Your browser doesn't support to File API")
}
});
function uploadFile() {
var files = $('#files')[0].files,
filesLength = files.length;
for (var i = 0; i < filesLength; i++) {
var f = files[i]
var fileReader = new FileReader();
fileReader.onload = (function(e) {
var file = e.target;
var emptyImg = $('img.img-fluid:not(.hasImage)');
emptyImg[0].src = e.target.result;
$(emptyImg[0]).addClass('hasImage');
$(".remove").click(function() {
var img = $(this).parent().find('img.hasImage')[0];
img.src = '';
$(img).removeClass('hasImage');
});
});
fileReader.readAsDataURL(f);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="image-wrapper" style="display:flex;">
<div class="image-wrap">
<img width="100" id="img_0" src="assets/images/img1.jpg" class="img-fluid">
<span class="remove">X</span>
</div>
<div class="image-wrap">
<img width="100" id="img_1" src="assets/images/unloaded-img.png" class="img-fluid">
<span class="remove">X</span>
</div>
<div class="image-wrap">
<img width="100" id="img_2" src="assets/images/unloaded-img.png" class="img-fluid">
<span class="remove">X</span>
</div>
<div class="image-wrap">
<img width="100" id="img_3" src="assets/images/unloaded-img.png" class="img-fluid">
<span class="remove">X</span>
</div>
<div class="image-wrap">
<img width="100" id="img_4" src="assets/images/unloaded-img.png" class="img-fluid">
<span class="remove">X</span>
</div>
<div class="image-wrap">
<img width="100" id="img_5" src="assets/images/unloaded-img.png" class="img-fluid">
<span class="remove">X</span>
</div>
</div>
<div class="upload-btn">
<div class="upload-btn-wrapper">
<button class="btn" onclick="uploadFile()">Upload a file1</button>
<input type="file" id="files" name="files[]" multiple="">
</div>
</div>
Hope this helps :)
I'm new here and I'm a beginner in programming.
I need help with my weather app. I'm using metaweather api for displaying weather, but i need to display weather for multiple location.
This is how i display weather for only one city, but i dont know how to pass more cities?!
Please help!
Here it's code (HTML)
<main>
<section>
<div class="container">
<div id="main_panel">
<div class="row">
<div class="col-xs-12 col-sm-6 col-md-4">
<div class="app">
<img class="img-responsive img-rounded" src="images/warszawa.jpg" alt="Warszawa">
<span id="warsaw">
<span class="location">
Unknown
<i class="fa fa-map-marker"></i>
<span class="today">Today</span>
</span>
</span>
<span class="weather">
<span class="temperature">
0<sup>°</sup>
<span class="unit">c</span>
</span>
<span class="weather-icon"></span>
<h3 class="weather-state"></h3>
</span>
</div>
</div>
<div class="col-xs-12 col-sm-6 col-md-4">
<div class="app">
<img class="img-responsive img-rounded" src="images/berlin.jpg" alt="Berlin">
<span id="berlin">
<span class="location">
Unknown
<i class="fa fa-map-marker"></i>
<span class="today">Today</span>
</span>
</span>
<span class="weather">
<span class="temperature">
0<sup>°</sup>
<span class="unit">c</span>
</span>
<h3 class="weather-state"></h3>
<span class="weather-icon"></span>
</span>
</div>
</div>
<div class="col-xs-12 col-sm-6 col-md-4">
<div class="app">
<img class="img-responsive img-rounded" src="images/lizbona.jpg" alt="Lizbona">
<span id="location">
Unknown
<i class="fa fa-map-marker"></i>
<span class="today">Today</span>
</span>
<span class="weather">
<span id="temperature">
0<sup>°</sup>
<span class="unit">c</span>
</span>
<h3 class="weather-state"></h3>
<span class="weather-icon"></span>
</span>
</div>
</div>
</div>
</div>
</section>
</main>
And here it is JavaScript
var temperature = [];
var cityName = 'warsaw';
var weatherSiteUrl = "http://cors-anywhere.herokuapp.com/https://www.metaweather.com/";
var weatherAPIUrl = weatherSiteUrl + "api/";
var cityLocation = weatherAPIUrl + "location/search/?query=";
var iconUrl = "https://www.metaweather.com/";
function drawWeather() {
$.getJSON(cityLocation + cityName, function(data) {
$.getJSON(weatherAPIUrl + 'location/' + data[0].woeid, function(data) {
$('.location').html(cityName + '<i class="fa fa-map-marker"></i>'); // Name of location
$('.weather-state').html(data.consolidated_weather[0].weather_state_name); //Weather state
temperature[0] = Math.floor(data.consolidated_weather[0].the_temp);
$('.temperature').html(temperature[0] + '<sup>°</sup><span class="unit">c</span>'); // Temperature
var weatherImg = iconUrl + 'static/img/weather/' + data.consolidated_weather[0].weather_state_abbr + '.svg';
$('.weather-icon').html('<img src=' + weatherImg + '>');
});
});
};
drawWeather();
Instead of hardcoding 'warsaw' pass the location to the function
var temperature = [];
var weatherSiteUrl = "http://cors-anywhere.herokuapp.com/https://www.metaweather.com/";
var weatherAPIUrl = weatherSiteUrl + "api/";
var cityLocation = weatherAPIUrl + "location/search/?query=";
var iconUrl = "https://www.metaweather.com/";
function drawWeather(cityName) {
$.getJSON(cityLocation + cityName, function(data) {
$.getJSON(weatherAPIUrl + 'location/' + data[0].woeid, function(data) {
$('.location').html(cityName + '<i class="fa fa-map-marker"></i>'); // Name of location
$('.weather-state').html(data.consolidated_weather[0].weather_state_name); //Weather state
temperature[0] = Math.floor(data.consolidated_weather[0].the_temp);
$('.temperature').html(temperature[0] + '<sup>°</sup><span class="unit">c</span>'); // Temperature
var weatherImg = iconUrl + 'static/img/weather/' + data.consolidated_weather[0].weather_state_abbr + '.svg';
$('.weather-icon').html('<img src=' + weatherImg + '>');
});
});
};
Then instead of drawWeather(); run the function using drawWeather('warsaw');, drawWeather('berlin');,...
I have 3 images. What i want to do is when i click on any one of the image a random image should be displayed on a div.
Here is the code. Help please.
var iarr=["1.jpg","2.jpg","3.jpg"];
function select()
{
var random=Math.floor(Math.Random()*3);
document.getElementById('disp').innerHTML = iarr[random];
}
<html>
<body>
<h4> MAKE A CHOICE </h3>
<img id='x' onclick="select" src='1.jpg'/>
<img id='y' onclick="select" src='2.jpg'/>
<img id='z' onclick="select" src='3.jpg'/>
<div id='disp'/>
var iarr=["1.jpg","2.jpg","3.jpg"];
function select(){
var random = Math.floor(Math.random() * iarr.length);
var div = document.getElementById('disp');
var image = "<img src=\"" + iarr[random] + "\"/>";
div.innerHTML = image;
}
<html>
<body>
<h4> MAKE A CHOICE </h4>
<img id='x' onclick="select()" src='1.jpg'/>
<img id='y' onclick="select()" src='2.jpg'/>
<img id='z' onclick="select()" src='3.jpg'/>
<div id='disp'/>
Working example: https://jsfiddle.net/pndtdt7t/
var iarr = [
"http://www.wallpapers-for-desktop.com/desktopbilder_for_free/free_desktopbild.jpg",
"http://wikiin.com/media/images/15/04/21/cfe0fdfb23.jpg",
"http://data.whicdn.com/images/89382997/large.jpg"
];
function select() {
var img = "<img src=\""+iarr[Math.floor(Math.random() * iarr.length)]+ "\" />";
document.getElementById('disp').innerHTML = img;
}
<html>
<body>
<h4> MAKE A CHOICE </h3>
<img id='x' onclick="select()" src='1.jpg'/>
<img id='y' onclick="select()" src='2.jpg'/>
<img id='z' onclick="select()" src='3.jpg'/>
<div id='disp'/>
I have the following html:
<div id="prog" class="downloads clearfix">
<div class="item">
<div class="image_container">
<img src="/img/downloads/company.png" width="168" height="238" alt="">
</div>
<div class="title">
pricelist: <label id="pr1"></label>
</div>
<div class="type">
pdf document
</div>
<div class="link">
<a id="pdfdocument" class="button" target="_blank" href="#">start Download </a>
</div>
</div>
</div>
I want build HTML which is inside the <div id="prog"> with Javascript:
<div id="prog" class="downloads clearfix"></div>
I'm trying to use this Javascript, but without success:
var tmpDocument, tmpAnchorTagPdf, tmpAnchorTagXls, parentContainer, i;
parentContainer = document.getElementById('prog');
for (i = 0; i < documents.length; i++) {
tmpDocument = documents[i];
tmpAnchorTagPdf = document.createElement('a id="pdfdocument" ');
tmpAnchorTagPdf.href = '/role?element=' + contentElement.id + '&handle=' + ope.handle;
tmpAnchorTagPdf.innerHTML = 'start Download';
tmpAnchorTagXls = document.createElement('a');
tmpAnchorTagXls.href = '/role?element=' + contentElement.id + '&handle=' + ope.handle;
tmpAnchorTagXls.innerHTML = 'start Download';
parentContainer.appendChild(tmpAnchorTagPdf);
parentContainer.appendChild(tmpAnchorTagXls);
}
If this is a section of code that you will be using more than once, you could take the following approach.
Here is the original div without the code you want to create:
<div id="prog" class="downloads clearfix">
</div>
Create a template in a hidden div like:
<div id="itemtemplate" style="display: none;">
<div class="item">
<div class="image_container">
<img src="/img/downloads/company.png" width="168" height="238" alt="">
</div>
<div class="title">
pricelist: <label></label>
</div>
<div class="type">
pdf document
</div>
<div class="link">
<a class="button" target="_blank" href="#">start Download </a>
</div>
</div>
</div>
Then duplicate it with jquery (OP originally had a jquery tag; see below for JS), update some HTML in the duplicated div, then add it to the document
function addItem() {
var item = $("#itemtemplate div.item").clone();
//then you can search inside the item
//let's set the id of the "a" back to what it was in your example
item.find("div.link a").attr("id", "pdfdocument");
//...the id of the label
item.find("div.title label").attr("id", "pr1");
//then add the objects to the #prog div
$("#prog").append(item);
}
update
Here is the same addItem() function for this example using pure Javascript:
function JSaddItem() {
//get the template
var template = document.getElementById("itemtemplate");
//get the starting item
var tempitem = template.firstChild;
while(tempitem != null && tempitem.nodeName != "DIV") {
tempitem = tempitem.nextSibling;
}
if (tempitem == null) return;
//clone the item
var item = tempitem.cloneNode(true);
//update the id of the link
var a = item.querySelector(".link > a");
a.id = "pdfdocument";
//update the id of the label
var l = item.querySelector(".title > label");
l.id = "pr1";
//get the prog div
var prog = document.getElementById("prog");
//append the new div
prog.appendChild(item);
}
I put together a JSFiddle with both approaches here.