I have looked at other Questions of this type and none of them solved my problem. I am having this JavaScript code:
var count1;
for (count1 = 1; count1 < 11; count1++) {
var article = res.articles[count1]
var ImageURL = res.articles[count1].urlToImage
$('#showNews').append('<div id="' + count1 + '" class="article"><div class="overlayart"><div class="art"><h3>' + article.title + '</h3 <p>' + article.description + '<br><br><button onclick="divLoad()">Follow Link</button></p></div></div></div>');
$("#" + count1).css('background-image', 'url(' + ImageURL + ')');
x = article.url;
}
function divLoad() {
alert(article.url);
};
Basically there are 10 items with different articles. Scopes of variables are all correct. I can see the links of the items when I console log them in the loop. I want to alert each URL whenever each Item is clicked for a respected button. But when I click that I get the error:
Uncaught ReferenceError: divLoad is not defined
at HTMLButtonElement.onclick
Am I missing something?
EDIT [My Full Code]:
var x;
function divLoad() {
alert(x);
};
$(document).ready(function(){
var url = 'https://newsapi.org/v2/top-headlines?country='+country+'&apiKey=MYAPIKEY';
$.getJSON(url).then(function(res){
//console.log(res)
var count1;
for(count1 = 1; count1 < 11; count1++){
var article = res.articles[count1]
var ImageURL = res.articles[count1].urlToImage
x = article.url;
$('#showNews').append('<div id="'+count1+'" class="article"><div class="overlayart"><div class="art"><h3>'+article.title+'</h3><p>'+article.description+'<br><br><button onclick="divLoad()">Follow Link</button></p></div></div></div>');
$("#"+count1).css('background-image','url(' + ImageURL + ')');
}
});
The problem is that you're always referencing one single, global variable. That variable (x) will only ever hold the last value it was set to in your for loop.
Instead, we can append the articles and give each one a data attribute - that way, we can associate each element with a specific article URL.
function divLoad(url) {
alert(url);
};
$(document).ready(function() {
var url = 'https://newsapi.org/v2/top-headlines?country=' + "test" + '&apiKey=MYAPIKEY';
$.getJSON(url).then(function(res) {
for (let count1 = 1; count1 < 11; count1++) {
let article = res.articles[count1];
$('#showNews').append('<div id="' + count1 + '" class="article"><div class="overlayart"><div class="art"><h3>' + article.title + '</h3><p>' + article.description + '<br><br><button class="article-btn">Follow Link</button></p></div></div></div>');
$("#" + count1)
.css("background-image", "url('" + article.urlToImage + "'")
.attr("data-url", article.url); //Associate the URL to the element
}
});
$("#showNews").on("click", ".article-btn", function() {
var url = $(this).closest(".article").attr("data-url"); //Get the associated URL
divLoad(url);
});
});
If you inspect the <div class="article"> now, you'll see each one has a data-url attribute that holds its URL.
Related
$(document).ready(function(){
var $body = $('body');
var index = streams.home.length - 1;
while(index >= 0){
var tweet = streams.home[index];
var $tweet = $('<div class = tweet></div>');
var $user = $('<div class = users></div>');
var $message = $('<div class = message></div>');
var $time = $('<div class = time></div>');
// $tweet.text('#' + tweet.user + ': ' + tweet.message + ' ' + tweet.created_at);
$tweet.appendTo($('.tweets'));
$time.text(tweet.created_at + '\n').appendTo($tweet);
$user.text('#' + tweet.user + ': ').attr('username', tweet.user).appendTo($tweet);
$message.text(tweet.message + ' ').appendTo($tweet);
index -= 1;
}
//see user history by clicking on name
//click event on name element
//hide all other users that do not have the same username attribute?
$('.tweets').on('click', '.users', () => {
var user = $(this).data('users');
console.log(user);
})
So I'm trying to pull data from a class when I click on it. This involves the last few lines of my code. The data stored in my .users should give me an output of {someName: 'stringOfName"} however when I click on it I get an empty object {}. What am I doing wrong? I'm adding data to my .users and I can clearly see it being displayed holding information so am I pulling the data from this object incorrectly?
$(this).data('users'); would get info from a data-attribute called "users" on the clicked element. But I don't see anywhere in you code where you attach any data-attributes to any of your elements. You've added a "username" attribute, but that's not the same as a data-attribute, and it also has a different name.
Secondly, you can't use an arrow function as your "click" callback function because this will have the wrong scope. (You can read more about this elsewhere online).
Here's a working demo:
$(document).ready(function() {
//some dummy data
var streams = {
"home": [{
"user": "a",
"message": "hello",
"created_at": "Friday"
}]
};
var index = streams.home.length - 1;
while (index >= 0) {
var tweet = streams.home[index];
var $tweet = $('<div class="tweet"></div>');
var $user = $('<div class="users"></div>');
var $message = $('<div class="message"></div>');
var $time = $('<div class="time"></div>');
// $tweet.text('#' + tweet.user + ': ' + tweet.message + ' ' + tweet.created_at);
$tweet.appendTo($('.tweets'));
$time.text(tweet.created_at + '\n').appendTo($tweet);
//create a data-attribute instead of an attribute
$user.text('#' + tweet.user + ': ').data('username', tweet.user).appendTo($tweet);
$message.text(tweet.message + ' ').appendTo($tweet);
index -= 1;
}
//use a regular function insted of an arrow function
$('.tweets').on('click', '.users', function() {
var user = $(this).data('username'); //search for the correct data-attribute name
console.log(user);
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="tweets"></div>
Any help would be appreciate. I need to create a slider based on JSON datas from the moviedb API. I created the slider showing the title, the picture and the description within a for loop but the last thing I need to achieve is to get the movie rating but instead of the number I need to show stars (half or full filled according to the datas provided).
I'm stuck and tried different things but it doesn't work. I know it's quite simple but I'm stuck.
Many thanks for any help. Do not hesitate if you need something else because it's my first post on stackoverflow.
Here is the fiddle of my work :
https://jsfiddle.net/y2hbzej8/7/
Here is my JS code to get datas :
JS :
var urlmoviedb = 'https://api.themoviedb.org/3/movie/upcoming?api_key=e082a5c50ed38ae74299db1d0eb822fe';
$(function() {
$.getJSON(urlmoviedb, function (data) {
console.log(data);
for (var x = 0; x < data.results.length; x++) {
var title = data.results[x].original_title;
var descr = data.results[x].overview;
var note = data.results[x].vote_average;
var noteround = Math.round(2 * note) / 2;
var str = "/jj8qgyrfQ12ZLZSY1PEbA3FRkfY.jpg";
var imageurl = str.replace("/jj8qgyrfQ12ZLZSY1PEbA3FRkfY.jpg", "https://image.tmdb.org/t/p/w1280");
var image = imageurl + data.results[x].backdrop_path;
$('#image').append('<li>' + '<h2 class="h2-like mt-4">' + title + '</h2>' + '<p class="note">' + noteround + '</p>' + "<img class='img-fluid mb-4' src='" + image + "'>" + '<p class="descr">' + descr + '</p>' + '</li>');
}
});
Divide the vote_average field of each row by two since values go from 0 to 10. This will give you five stars based values.
I edited your example, I added font-awesome CSS library that will give you lots and lots of icons you can play with. Check them out
Here's the edited example on JSFiddle
var urlmoviedb = 'https://api.themoviedb.org/3/movie/upcoming?api_key=e082a5c50ed38ae74299db1d0eb822fe';
$(function() {
$.getJSON(urlmoviedb, function(data) {
console.log(data);
for (var x = 0; x < data.results.length; x++) {
var title = data.results[x].original_title;
var descr = data.results[x].overview;
var note = data.results[x].vote_average;
var noteround = Math.round(2 * note) / 2;
var str = "/jj8qgyrfQ12ZLZSY1PEbA3FRkfY.jpg";
var imageurl = str.replace("/jj8qgyrfQ12ZLZSY1PEbA3FRkfY.jpg", "https://image.tmdb.org/t/p/w1280");
var image = imageurl + data.results[x].backdrop_path;
//Translate vote average field into number of stars by dividing them by two since vote_average goes from 0 to 10
var numberOfStars = Math.round(note/2);
var stars = '';
for(var index = 0; index < numberOfStars; index++)
stars += '<span class="fa fa-star"/>';
$('#image').append('<li>' + '<h2 class="h2-like mt-4">' + title + '</h2>' + "<img class='img-fluid mb-4' src='" + image + "'>" + '<p class="descr">' + descr + '</p>' + stars + '</li>');
}
});
});
I have generated multiple barcodes using this code:
function getCode() {
var multipleCodes = document.getElementById('codeArea').value;
var eachLine = multipleCodes.split('\n');
console.log("eachLine = " + eachLine);
for (var i = 0; i < eachLine.length; i++) {
console.log("Inside loop: " + eachLine[i]);
var div = document.createElement('iframe');
div.innerHTML = "";
div.setAttribute('id', 'iFrameID' + i);
document.body.appendChild(div);
document.getElementById('iFrameID' + i).src = 'barCodeGenerator/generateBarCode.php?q=' + eachLine[i];
}
and trying to print it by using this method:
function printDiv(divName) {
var strName = document.getElementById("codeArea").value;
var imageId = document.getElementsByClassName('decoded');
var imagObject = new Image();
imagObject = imageId;
var originalImage = '<img id="imageViewer" src="' + imageSrc + '" style="padding-top: 20px" alt="' + imageSrc + '" />';
popup = window.open('', 'popup', 'toolbar=no,menubar=no,width=700,height=650');
popup.document.open();
popup.document.write("<html><head></head><body onload='print()'>");
popup.document.write(originalImage);
popup.document.write("</body></html>");
window.close('popup');
popup.document.close();
setTimeout(function () { popup.close(); }, 8000);
}
which only print single image by merging all barcodes.
How can i print them separately as multiple images.
Any help will be appreciated.
The most part of this code is irrelevant to your question. Consider removing your logs, the parts about showing popup and hiding it for more clearance.
Seems imageSrc variable in your code contains the source of one image, so you need to change your code by sending the array of image sources and iterating over it:
var originalImage = '';
// assuming imageSrc is an array of image sources
for (var i=; i < imageSrc.length; i++) {
// note that I'm changing the id of the image a litle bit to ensure it will remain unique
originalImage += '<img id="imageViewer' + i + '" src="' + imageSrc[i] + '" style="padding-top: 20px" alt="' + imageSrc[i] + '" />';
}
then the rest of your code must work.
I'm currently using the jQuery get method to read a table in another page which has a list with files to download and links to others similar webpages.
$.get(filename_page2, function(response, status){
var data = $("<div>" + response + "</div>");
var target_element = data.find(target_element_type_page2 + '#' + target_element_id_page2)[0];
var container = document.getElementById(element_change_content_page1);
if (typeof target_element !== "undefined"){
var rows = target_element.rows;
for (var i = 1, n = rows.length; i < n; i++) {
var table = rows[i].cells[1].getElementsByTagName("TABLE")[0];
var isFolder = table.getAttribute("CType") == "Folder";
var elem = table.rows[0].cells[0];
var text = elem.innerText || elem.textContent;
var link = elem.getElementsByTagName("A")[0].getAttribute("href");
if (!isFolder) {
container.innerHTML += "<li class=\"mainfolderfile\">" + "<a class=\"filelink\" href=\"" + link + "\">" + text + "</a></li>";
} else {
container.innerHTML += "<li class=\"folderlist\">" + "<a class=\"folderlink\" onclick=\"open_submenu(this)\" href=\"#\">" + text + "</a><ul></ul></li>";
var elem_page1 = container.getElementsByTagName("li");
var container_page1 = elem_page1[elem_page1.length - 1].getElementsByTagName("ul")[0];
create_subfolder(container_page1, link);
}
}
} else {
container.innerHTML += "<li class=\"mainfolderfile\">" + "<a class=\"filelink\" href=\"" + "#" + "\">" + "Error..." + "</a></li>";
}
}, page2_datatype);
This is working fine, and all the folders and files are being listed. But when I try to do the same thing with the folders (calling the create_subfolder function) and create sublists with their subfolders and files, I'm getting a weird behavior.
function create_subfolder(container2, link1) {
$.get(link1, function(response, status){
var data = $("<div>" + response + "</div>");
var target_element = data.find("table" + "#" + "onetidDoclibViewTbl0")[0];
if (typeof target_element !== "undefined"){
var rows = target_element.rows;
for (var i = 1, n = rows.length; i < n; i++) {
var table = rows[i].cells[1].getElementsByTagName("TABLE")[0];
var elem = table.rows[0].cells[0];
var text = elem.innerText || elem.textContent;
var link2 = elem.getElementsByTagName("A")[0].getAttribute("href");
//nothing is changed in the webpage. The modifications in the html don't appear
container2.innerHTML += "<li>" + text + "</li>";
}
}
alert(container2.innerHTML); // Print the html with all the modifications
}, "html");
}
The second get(), inside the create_subfolder() function are not changing anything in the webpage, so no sublist is created. But, when I call the alert() function at the end of the get() function, it prints the code with all the modifications it should have made in the html at the second get callback. I believe the problem is related with the asynchronous behavior of the get function but I don't know exactly why. Any guess?
I use this jQuery code to append a div to another:
$('#sklep').on('click', '.kup', function () {
var cena = $('#cena').text();
var tytul = $('#tytul').text();
var iden = $('#id').text();
var suma = $('#koszykdiv .cyfry').text();
var dodawanie = parseInt(cena) + parseInt(suma);
$('.cyfry').text(dodawanie);
var source = $("#miniatura").attr("src");
$('.koszyk_content_items').append($('<div class="item_koszyk"><div class="miniatura_koszyk"><img width="165" height="110" src="' + source + '"/></div><span id="opis">' + tytul + ' - ' + cena + ' zł - </span><span class="identyfikator" style="display:none;">' + iden + '</span>USUŃ</div>'));
var licznik = $('#koszykdiv .licznik').text();
alert(licznik);
$('#identyfikator').text(licznik);
var licznik_dodawanie = parseInt(licznik) + 1;
$('#koszykdiv .licznik').text(licznik_dodawanie);
$.cookie("obraz" + licznik_dodawanie, id);
var cena = '';
var tytul = '';
var iden = '';
var source = '';
});
but it always appends a div with the same variables values, even if parent of '.kup' href has another text values. Can you help me and tell where the problem is?
You say in your question that you get the same variable values "even if parent of '.kup' href has another text values."
This is because nothing in your code is relative to the '.kup'-element. You get the src-attribute of the element with id=miniatura everytime.