How do I expose images from json data - javascript

I have looped over some json and have pulled urls from the data. The thumbnail data looks like:
{href: "https://link/medium.jpg"}
href: "https://link/medium.jpg"
>__proto__: Object
How can I expose each url so the actual images display on the browser not the links. This is my code. console.log(o._links.thumbnail) is the data I receive from above:
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=\, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Fetch Json</title>
</head>
<body>
<p>
thumbnail:
</p>
<script>
const url =
"https://s3-us-west-2.amazonaws.com/example.json";
async function getThumbnail() {
const response = await fetch(url);
const data = await response.json();
var art = data._embedded.artworks;
art.forEach(function(o) {
//console.log(o._links.thumbnail);
var img = document.createElement("image");
img.src = o._links.thumbnail; //set the value equal to the href
document.querySelector("body").appendChild(img);
});
}
getThumbnail();
</script>

You need to manipulate the DOM, something like this.
let elem = document.createElement("img");
elem.src = o._links.href;
document.getElementById("placehere").appendChild(elem);
Reference:
Adding an img element to a div with javascript

Try to append image elements and set the src attribute to the value of href
this is more general than the code I posed before:
1) Loop thru your json
2) create image element
var img = document.createElement("image");
img.src = o._links.thumbnail; //set the value equal to the href
document.querySelector("body").appendChild(img);

Related

Can't change image source of element ID when using variable name instead of string

I am writing a function to change the src of an image based on two strings passed to the function, a, which is the element ID, and b, which is the new source for the image.
In this instance, I have confirmed that both variables are passed to the function correctly.
console.log(a); is layerAddButton
console.log(b); is images/layerAdd-blue.svg
Here is my code :
function swapImg(id,url)
{
var a = id;
var b = url;
document.getElementById(a).src = b;
}
This does not change the url of the image as expected, but gives an error in chrome :
functions.js:3025 Uncaught TypeError: Cannot set properties of null
(setting 'src')
at swapImg (functions.js:3025:32)
at HTMLButtonElement.onmouseleave (app.htm:1132:274)
This works fine when I hard code like so :
document.getElementById('layerAddButton').src = 'images/layerAdd-blue.svg';
I tried it and it works. Make sure to write the Id correctly when passing it to the function. And make sure the script is in the HTML after the element and not in the head.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<img
src="https://www.testingtime.com/app/uploads/2017/07/Grundregeln_fuer_User_Testing-750x500.jpg"
alt=""
id="imgElement"
/>
<body>
<script>
function swapImg(id, url) {
var a = id;
var b = url;
console.log(document.getElementById(a));
document.getElementById(a).src = b;
}
swapImg("imgElement", "https://source.unsplash.com/random");
</script>
</body>
</html>
To fix this, you just needed to pass the variable to the getElementById() function and not just the variable name.
The correct code should be :
function swapImg(id,url)
{
var a = id;
var b = url;
document.getElementById(a).src = b;
}

Getting API Data to show on a webpage with Javascript

I'm trying to get data from https://wttr.in/?format=j1 to show on a webpage. I'm very new to Javascript so I hoped this would be easy but I'm struggling to get it to work, what am I doing wrong?.
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content=
"width=device-width, initial-scale=1.0" />
</head>
<body>
<p id="temp"></p>
</body>
<script>
const api_url = "https://wttr.in/?format=j1";
async function getWeather() {
const response = await fetch(api_url);
const data = await response.json();
const weather = data.results[0].current_condition[0];
let { temp } = weather.temp_C;
document.getElementById("temp").href = "temp:" + temp;
getWeather();
</script>
</html>
As per the comments from CBroe (thanks for the help) the main issues with my code were a few things.
No closing bracket
Not accessing the correct part of the JSON array
Not setting the element correctly
The working code looks like this:
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content=
"width=device-width, initial-scale=1.0" />
</head>
<body>
<p id="temp"></p>
</body>
<script>
const api_url = "https://wttr.in/?format=j1";
async function getWeather() {
const response = await fetch(api_url);
const data = await response.json();
const weather = data.current_condition[0];
let temp = weather.temp_C;
document.getElementById("temp").innerHTML = "temp:" + temp;
}
getWeather();
</script>
</html>
You are not parsing the json response correctly. The data does not have any results array, it is an object.
So to get current_condition you need to do something like this:
const currentCondition = data.current_condition[0];
Also, to get temp_C this is wrong:
let { temp } = weather.temp_C; //WRONG
// reason is that this statement means that `temp_C` is an object, and it contains `temp` property, which is not the case here. Because temp_C is a string.
So to get temp_C you need to simply do this:
let temp_C = currentCondition.temp_C;
Plus, worth mentioning here that if you are using the temp_C only for displaying purposes and not intending to reassign any value to it, then its better to use const instead of let
So it would become:
const temp_C = currentCondition.temp_C;
And if you want to use 'destructuring' you need to write it like this:
const { temp_C } = currentCondition;
Also your function is missing the closing paranthesis }.

How do you add a loading GIF spinner before AOI response in vanilla javascript?

So far I've tried using the let method make the GIF a constant and attempting to switch display type is js style function. Can someone guide me into displaying GIF image before API response and hiding it when fetch() is processed.
Html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="./doggos.css">
<title>Dogs</title>
</head>
<body>
<h1>Doggos</h1>
<button class="add-doggo">Add Doggo</button>
<div class="doggos">
<div class="loader"><img src="./giphy (1).gif"></img></div>
</div>
<script src="./doggos.js"></script>
</body>
</html>
Javascript
const DOG_URL = "https://dog.ceo/api/breeds/image/random";
const doggos = document.querySelector(".doggos");
function addNewDoggo() {
const promise = fetch(DOG_URL);
promise
.then(function(response) {
const processingPromise = response.json(); //This line of code parses the API response into a usuable js object
return processingPromise; //this code returns a new promise and this process is called | PROCESS-CHAINING
})
.then(function(processedResponse) {
const img = document.createElement("img");
img.src = processedResponse.message;
img.alt = "Cute doggo";
doggos.appendChild(img);
});
}
document.querySelector(".add-doggo") .addEventListener("click", addNewDoggo)

Toggle properties of anchor and image elements via JavaScript

I currently have a single web page that contains two elements:
image (wrapped in anchor, loads URL in iframe)
iframe (loads themes.html by default)
The image, on-click, toggles/switches the iframe between themes.html and styles.html, as well as the image source. However, despite the numerous tutorials and forum posts I have read online, I cannot get it to work.
How would I go about having the image toggle when clicked, as well as toggling the source of the iframe between the two HTML files?
<!DOCTYPE HTML>
<html>
<head>
<title>Manager</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
<link rel="stylesheet" href="assets/css/main.css" />
</head>
<body>
<div class="switch">
<a href="styles.html" target="switchframe" id="toggleURL" onclick="toggleURL();">
<img src="images/segment-theme.png" id="toggleImage" onclick="toggleImage();"/></a>
<iframe id="frame" name="switchframe" src="themes.html"></iframe>
</div>
<script>
function toggleImage() {
var img1 = "images/segment-theme.png";
var img2 = "images/segment-style.png";
var imgElement = document.getElementById('toggleImage');
imgElement.src = (imgElement.src === img1)? img2 : img1;
}
function toggleURL() {
var url1 = "themes.html"
var url2 = "styles.html"
var urlElement = document.getElementById('toggleURL');
urlElement.href = (urlElement.href === url1)? url2 : url1;
}
</script>
</body>
</html>
EDIT: I figure I could maybe have it just toggle the iframe's src property directly, but if I can't even get the image's src to toggle to begin with, I fear I won't be able to get that working either.
EDIT 2: I can get it to load styles.html in the iframe with the code below; however, I cannot get it to toggle back to themes.html:
function toggleURL() {
var url1 = "themes.html"
var url2 = "styles.html"
var urlElement = document.getElementById('frame');
urlElement.src = (urlElement.src === url1)? url2 : url1;
}
I believe you're having issues because you're using element.attribute instead of element.getAttribute('attribute-name').
Since image.src will return the absolute path www.domain.com/path/to/image.png where getAttribute returns the value specified in the element.
Also you need only one event handler for your case.
<html>
<head>
<title>Manager</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
<link rel="stylesheet" href="assets/css/main.css" />
</head>
<body>
<div class="switch">
<a href="styles.html" id="toggleURL" onclick="toggle(event);">
<img src="images/segment-theme.png" id="toggleImage" />
</a>
<iframe id="frame" src="themes.html"></iframe>
</div>
<script>
function toggle(e) {
e.preventDefault();
var img1 = "images/segment-theme.png";
var img2 = "images/segment-style.png";
var imgElement = document.getElementById('toggleImage');
var src = imgElement.getAttribute('src');
imgElement.setAttribute('src', (src === img1) ? img2 : img1)
var url1 = "themes.html"
var url2 = "styles.html"
var urlElement = document.getElementById('toggleURL');
var href = urlElement.getAttribute('href');
document.getElementById('frame').setAttribute('src', href)
urlElement.setAttribute('href', (href === url1) ? url2 : url1)
}
</script>
</body>
</html>

How to store the value of an attribute inside a variable using html, javascript?

I have a line <meta property="product:price:amount" content="3.05"/>
in a large html file.
I need to store the value of content inside a variable, so that I may access it globally.
How can I do that?
Just catch it with querySelector to get it's content attribute.
const content = document.querySelector('meta').content;
console.log(content);
<meta property="product:price:amount" content="3.05"/>
In case of multiple meta tags:
const elems = document.querySelectorAll('meta');
let content = Array.from(elems).find(v => v.content).content;
console.log(content);
<meta property="product:price:amount"/>
<meta property="product:price:amount"/>
<meta property="product:price:amount" content="3.05"/>
To very specifically get the meta tag you are after (event if there are multiple meta tags):
var variable = document.querySelectorAll('meta[property="product:price:amount"]')[0].content;
If there is only one item then simply
document.getElementsByTagName("meta")[0].content
For a single meta tag:
var myGlobal = document.querySelector('meta[content]').getAttribute('content');
document.body.textContent = myGlobal;
<meta property="product:price:amount" content="3.05"/>
If you have a lot of tags:
var contentArray = [];
document.querySelectorAll('meta[content]').forEach(function(meta){
contentArray.push(meta.getAttribute('content'));
});
document.body.textContent = contentArray.join(' - ');
<meta property="product:price:amount" content="3.05"/>
<meta property="product:quality:amount" content="9.25"/>
<meta property="product:id:amount" content="1.0"/>
If you want to be more specific about the tag you can change the selector:
...querySelector('meta[property="product:price:amount"][content]')...
Read more about selectors https://developer.mozilla.org/en-US/docs/Learn/CSS/Introduction_to_CSS/Selectors

Categories