I am really new with javascript
I am trying to loop my json then add the images to my html, then i need to make it so when i click on that image it shows me the File from my json
var obj = JSON.parse(data);
for (index = 0; index < obj.length; ++index) {
var file = obj[index]['File'];
var image = obj[index]['Image'];
var test = $( ".row" ).append(
`<div class="column">
<div class="card">
<img src="${image}" alt="Avatar" style="width:100%">
<div class="container">
<h4>
<b>Title</b>
</h4>
</div>
</div>
</div>`
);
test.click(function(e) {
alert(file);
});
console.log(file);
console.log(image);
}
Related
**I can get the values of grade and iconPath(url pic). The problem is on for loop, all the picture(url picture) print on 1 card, Anyone can help me how to print images in different card. Thank you **
document.getElementById('cardinfo').innerHTML +=
`<div class="card">
<div class="card-front">
<div class="image-container">
<img class="img-flip" src="image/class-arbalist.png"/></br>
</div>
</div>
<div class="card-back">
<div class="image-container" id="img-link">
`
for (var i = 0; i < grad.length; i++) {
var grade = data.data.inven[i].grade;
var grade1;
if (grade == 4 ){
var iconPath = data.data.inven[i].iconPath;
document.getElementById('img-link').innerHTML +=`
<img class="img-skill2" src="${iconPath}"/>`
}else if(grade == 5){
var iconPath = data.data.inven[i].iconPath;
document.getElementById('img-link').innerHTML +=`
<img class="img-skill3" src="${iconPath}"/>`
}else{
}
}
`
</div>
</div>
</div>`
;
Card. Only first card got all the images not the second card
**Anyone can help me how to put output images(urlpic) in different cards. Thank you **
Trying to trigger click event of a tag with jQuery but the event is linked with data set by $.getJSON in a section.
Following is the code of HTML:
...
const page=1, dataList=[];
$.getJSON('https://api.punkapi.com/v2/beers?page=' + page + '&per_page=25', function (beerList) {
console.log(beerList)
dataList.push(beerList);
currentElements = renderFuntion(beerList);
$('#dynamicData').html(currentElements);
});
function renderFuntion(data) {
var temp = '';
data.forEach(element => {
var item = `
<div class="card col-xs-12 col-lg-4 my-2">
<div class="card-body">
<figure> <img src=${element.image_url} class="img-fluid" alt=${element.name}></figure>
<article class="ms-3">
<h5 class="card-title">${element.name}</h5>
<p class="card-text">${element.description.length > 220 ? element.description.substring(0, 220) + '...' : element.description}</p>
</article>
<!--- This is what's suppose to give the event on click. --->
</i>
</div>
</div>`
temp += item;
});
return temp;
}
//this is what's not working
$('.card a').click(function () {
var usersid = $(this).attr("id");
favouritesList.push(usersid);
console.log(favouritesList);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.js"></script>
<section class="my-3 g-0" id="dynamicData">
</section>
Please do guide if possible. Thanks.
Your code isn't working because your element isn't loaded with the page, so when jQuery runs $('.card a').click(function..., $('.card a') returns null, so the listener is not attached.
Add your listener to the document like so:
$(document).on("click", ".card a", function() { ... })
When the user clicks on the document, jQuery will check if $(".card a") is the target, even if added after the page was initially loaded, and will execute your function if it is.
ajaxComplete also solve your problem.
$(document).ajaxComplete(function () {
$('.card a').click(function () {
const favouritesList = [];
let usersId = $(this).attr("id");
favouritesList.push(usersId);
console.log(favouritesList);
})
})
As #will already pointed out: it is a timing problem. In your code the click event was attached before the contents form your $.getJSON() arrives. By using a delegated event attachment you can solve the problem:
const page=1, dataList=[], favouritesList=[];
$.getJSON('https://api.punkapi.com/v2/beers?page=' + page + '&per_page=25', function (beerList) {
// console.log(beerList)
dataList.push(beerList);
currentElements = renderFuntion(beerList);
$('#dynamicData').html(currentElements);
});
function renderFuntion(data) {
var temp = '';
data.forEach(element => {
var item = `
<div class="card col-xs-12 col-lg-4 my-2">
<div class="card-body">
<figure> <img src=${element.image_url} class="img-fluid" alt=${element.name}></figure>
<article class="ms-3">
<h5 class="card-title">${element.name}</h5>
<p class="card-text">${element.description.length > 220 ? element.description.substring(0, 220) + '...' : element.description}</p>
</article>
<!--- This is what's suppose to give the event on click. --->
click me</i>
</div>
</div>`
temp += item;
});
return temp;
}
//this is now working:
$('section').on("click",".card a",function () {
favouritesList.push($(this).attr("id"));
console.log(favouritesList);
});
.img-fluid {height:80px}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.js"></script>
<section class="my-3 g-0" id="dynamicData">
</section>
To access a dynamic element via click event you have to use something like this $(document).on('click','elementName',function(){})
I have made some minor changes and hope that they are what you are looking for. Happy coding!
var favouritesList = [];
const page=1, dataList=[];
$.getJSON('https://api.punkapi.com/v2/beers?page=' + page + '&per_page=25', function (beerList) {
dataList.push(beerList);
currentElements = renderFuntion(beerList);
$('#dynamicData').html(currentElements);
});
function renderFuntion(data) {
var temp = '';
data.forEach(element => {
var item = `
<div class="card col-xs-12 col-lg-4 my-2">
<div class="card-body">
<figure> <img src=${element.image_url} class="img-fluid" alt=${element.name}></figure>
<article class="ms-3">
<h5 class="card-title">${element.name}</h5>
<p class="card-text">${element.description.length > 220 ? element.description.substring(0, 220) + '...' : element.description}</p>
</article>
<!--- This is what's suppose to give the event on click. --->
</i> User Icon
</div>
</div>`
temp += item;
});
return temp;
}
//I've changed the way you are trying to get that ID from the anchor tag
$(document).on('click','a',function () {
var usersid = $(this).attr("id");
favouritesList.push(usersid);
console.log(favouritesList);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section class="my-3 g-0" id="dynamicData">
</section>
from a querySelectorAll I retrieve every objects from a specific class (list - all the same but with specific value inside...) :
- I create buttons (event) for each objects
- Each object have a specific value
- When clicking on one object. I need to show this specific value contained inside this object.
I'm currently doing it with pure javascript
I use tree HMTL node to move inside and take the data. But whenever, these objects are clicked it's only the last object value come up...
----- EDIT : html added-----
function hello(d)
{
alert("" + d);
}
var Images = document.querySelectorAll('.block-image_carousel-single > figcaption');
for (var i = 0; i < Images.length; i++) {
var Image = Images[i];
Image.addEventListener('click', function (event) {
event.preventDefault();
hello(Image.textContent);
}, false);
}
<div class="block-image_carousel">
<div>
<div class="block-main-image_carousel-display">
<img src="img.png" class="block-image_carousel-display">
<figcaption> Image 1 </figcaption>
</div>
<div class="block-image_carousel-single">
<img src="img.png">
<figcaption> Image 1 </figcaption>
</div>
<div class="block-image_carousel-single">
<img src="img.png">
<figcaption> Image 2 </figcaption>
</div>
<div class="block-image_carousel-single">
<img src="img.png">
<figcaption> Image 3 </figcaption>
</div>
<div class="block-image_carousel-single">
<img src="img.png">
<figcaption> Image 4 </figcaption>
</div>
</div>
</div>
When clicking on one object. I need to show this specific value contained inside this object.
But whenever, these objects are clicked it's only the last object value come up...
ANSWER : use let instead of var for image.
Remove the for loop and use the forEach() method instead to add a click listener to each element and extract the textContent from each figcaption inside the element.
Check and run the following Code Snippet for a practical example of what I described above:
function hello(d) { alert("" + d) }
var images = document.querySelectorAll('.block-image_carousel-single > figcaption');
images.forEach(image => {
image.addEventListener('click', function(e) {
e.preventDefault();
hello(image.textContent);
}, false);
});
<div class="block-image_carousel">
<div>
<div class="block-main-image_carousel-display">
<img src="https://picsum.photos/1000/200" class="block-image_carousel-display">
<figcaption> Image 1 </figcaption>
</div>
<div class="block-image_carousel-single">
<img src="https://picsum.photos/100/100">
<figcaption> Image 1 </figcaption>
</div>
<div class="block-image_carousel-single">
<img src="https://picsum.photos/100/100">
<figcaption> Image 2 </figcaption>
</div>
<div class="block-image_carousel-single">
<img src="https://picsum.photos/100/100">
<figcaption> Image 3 </figcaption>
</div>
<div class="block-image_carousel-single">
<img src="https://picsum.photos/100/100">
<figcaption> Image 4 </figcaption>
</div>
</div>
</div>
Try this
function hello(f,d)
{
alert(f,d);
}
var Images = document.querySelectorAll('.block-image_carousel-single > figcaption');
for (var i = 0; i < Images.length; i++) {
var Image = Images[i];
Image.addEventListener('click', function (event) {
event.preventDefault();
hello(this, Image.textContent);
}, false);
}
Your code is overwriting the "Images" var in the for loop, and only the last instance in the loop is being saved to Images. Also you defined Images twice?
Try modifying your code to this:
function hello(f,d)
{
alert(f,d);
}
var Images = document.querySelectorAll('.block-image_carousel-single > figcaption');
for (var i = 0; i < Images.length; i++) {
Images[i].addEventListener('click', function (event) {
event.preventDefault();
hello(this, Images.textContent);
},false);
}
Your issue is variable scoping, when the for loop ends the variable contains the last value.
You may use this.textContent in the event handler instead of Image.textContent. Or you may use let instead of var in the for loop. Another way to solve it is with IIFE
function hello(d) {
alert("" + d);
}
var Images = document.querySelectorAll('.block-image_carousel-single > figcaption');
for (var i = 0; i < Images.length; i++) {
var Image = Images[i];
Image.addEventListener('click', function (event) {
event.preventDefault();
hello(this.textContent);
}, false);
}
//
// ...loop using let
//
for (let i = 0; i < Images.length; i++) {
var Image = Images[i];
Image.addEventListener('click', function (event) {
event.preventDefault();
hello(Images[i].textContent);
}, false);
}
<div class="block-image_carousel">
<div>
<div class="block-image_carousel-single">
<img src="/media/images/irbOgrandOparis-17-png_956449_1505405590__B-.max-940x640.png" class="block-image_carousel-display">
<figcaption> Image 0 </figcaption>
</div>
<div class="block-image_carousel-single">
<img src="/media/images/irbOgrandOparis-17-png_956449_1505405590__B-.max-940x640.png">
<figcaption> Image 1 </figcaption>
</div>
<div class="block-image_carousel-single">
<img src="/media/images/irbOgrandOparis-17-png_956449_1505405590__B-.max-940x640.png">
<figcaption> Image 2 </figcaption>
</div>
<div class="block-image_carousel-single">
<img src="/media/images/irbOgrandOparis-17-png_956449_1505405590__B-.max-940x640.png">
<figcaption> Image 3 </figcaption>
</div>
<div class="block-image_carousel-single">
<img src="/media/images/irbOgrandOparis-17-png_956449_1505405590__B-.max-940x640.png">
<figcaption> Image 4 </figcaption>
</div>
</div>
</div>
I am trying to lazy load images with knockoutjs binding.
I was able to lazy load images without knockoutjs framework but I am not sure how can i do that with knockoutjs binding.
Here is my HTML
<div class='liveExample'>
<div class="row">
<div data-bind="foreach: items">
<div class="col-lg-4 col-md-4 col-sm-4 " style="padding: 0px">
<img data-bind=" attr: { src: $data }" class="lazy" />
</div>
</div>
</div>
</div>
Javascript:
var SimpleListModel = function(items) {
this.items = ko.observableArray(items);
bind(this); // Ensure that "this" is always this view model
};
var pictures = []; //Initialise an empty array
for (var i = 0; i = 10 ; i++) {
var image; //This is a placeholder
image = 'http://dummyimage.com/300x200/000/fff&text=' + i; //Set the src attribute (imageFiles[i] is the current filename in the loop)
pictures.push(image); //Append the new image into the pictures array
}
ko.applyBindings(new SimpleListModel(pictures));
Here is the jsfiddle
I have made it work by adding extra div tag before foreach binding and assigning afterrender event to the parent div
<div class="row">
<div data-bind='template: {afterRender: myPostProcessingLogic }'>
<div data-bind="foreach: {data: items} ">
<div class="col-lg-4 col-md-4 col-sm-4 " style="padding: 0px">
<img data-bind=" attr: { 'data-original': $data }" class="lazy" style="min-width:100px; min-height:50px;" />
</div>
</div>
</div>
</div>
Javascript
var SimpleListModel = function(items) {
this.items = ko.observableArray(items);
this.myPostProcessingLogic = function(elements) {
$("img.lazy").lazyload({
effect: "fadeIn",
effectspeed: 2000
});
}
};
var pictures = []; //Initialise an empty array
for (var i = 1; i < 100 ; i++) {
var imageUrl = 'http://dummyimage.com/300x200/000/fff&text=' + i; //Set the image url
pictures.push(imageUrl); //Append the new image into the pictures array
}
ko.applyBindings(new SimpleListModel(pictures));
Here is the jsfiddle
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.