filling out an html img tags 'src' form based on information derived from API javascript code - javascript

So, i am trying to add an img element from openweatherAPI, that shows an icon relative to what is found in the JSON results when the user gets the current web stats from typing a city, (i.e an image of scattered clouds, clear skies, etc). in order to display the img, i understand i need to paste the url into the "src" section of the img tag. the URL would look something like:
const png = "http://openweathermap.org/img/wn/" + icon + "#2x.png"
however, in order to make this dynamic, the img tags "src" would have to change based on what the image file is from the typed in city.
I have the logic defined from the "icon" and "png" variables in the js file. My question is, how to i get the html img 'src' to populate with the results of my "png" variable, based on the city the user inputs on the page?
I have included both html and javasript codes below
const button = document.querySelector(".button")
const inputValue = document.querySelector(".inputValue")
const name = document.querySelector(".name")
const desc = document.querySelector(".desc")
const temp = document.querySelector(".temp")
const img = document.querySelector(".image")
button.addEventListener('click', function (){
fetch('http://api.openweathermap.org/data/2.5/weather?q='+ inputValue.value +'&units=imperial&appid=61dcc0033e94c4172d2bb94bb607fc5d')
.then(response => response.json())
.then(data => {
const nameValue = data['name']
const tempValue = data['main']['temp']
const descValue = data['weather'][0]['description']
const icon = weatherData.weather[0].icon
const png = "http://openweathermap.org/img/wn/" + icon + "#2x.png"
name.innerHTML = nameValue
temp.innerHTML = tempValue
desc.innerHTML = descValue
img.innerHTML =
})
.catch(err => alert("Wrong City name!"))
})
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<title>OpenWeatherAPI</title>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<link rel='stylesheet' type='text/css' media='screen' href='style.css'>
</head>
<body>
<div class="input">
<input type="text" class="inputValue" placeholder="Enter a city">
<input type="submit" value="submit" class="button">
</div>
<div class="display">
<h1 class="name"></h1>
<p class="desc"></p>
<p class="temp"></p>
<img class="image" src="">
</div>
<script src='main.js'></script>
</body>
</html>

If I am not mistaken I do not see anywhere in your Java Script where you change the <img> src.
EDIT
You can change the src by simply getting that element then setting it's source like blow:
document.getElementById("myImg").src = png;
This is assuming you add an id of "myImg" to the <img> tag like so:
<img class="image" src="" id="myImg">
EDIT 2
I did not realize you already got the element earlier on so all you need to do is:
img.src = png;

Related

Change the entry of the pdf file to pass the exact path to it by me

I found this code which, you select a pdf file in an input, and it returns the number of pages it has. It turns out that with this way of reading pdfs is the only one I have found that reads absolutely all pdfs correctly.
What I am trying to do is to isolate the code that reads the pdf file, so that I can pass it the path to the file instead of using the input. It is to then read all the files in a folder and display the total number of pages.
But I can't figure out where exactly I would have to pass the path to the pdf file.
<!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>PDF.js Example to Count Number of Pages inside PDF Document</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<h1 class="text-center">Count Pages inside PDF Document</h1>
<div class="form-group container">
<input type="file" accept=".pdf" required id="files" class="form-control">
</div>
<br><br>
<h1 class="text-primary container" id="result"></h1>
</div>
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.12.313/pdf.min.js"></script>
<script>
let inputElement = document.getElementById('files')
inputElement.onchange = function(event) {
var file = event.target.files[0];
//Step 2: Read the file using file reader
var fileReader = new FileReader();
fileReader.onload = function() {
//Step 4:turn array buffer into typed array
var typedarray = new Uint8Array(this.result);
//Step 5:pdfjs should be able to read this
const loadingTask = pdfjsLib.getDocument(typedarray);
loadingTask.promise.then(pdf => {
document.getElementById('result').innerHTML = "The number of Pages inside pdf document is " + pdf.numPages
// The document is loaded here...
});
};
//Step 3:Read the file as ArrayBuffer
fileReader.readAsArrayBuffer(file);
}
</script>
</html>
You need 2 modifications to make it work. Add "multiple" attribute to the input to allow the user to select multiple pdf files.
<input type="file" multiple accept=".pdf" required id="files" class="form-control">
And then loop through the array of files to calculated the number of pages in each:
[].forEach.call(event.target.files, file => {
Update:
Two additional changes have been added.
1. We must reset the file input at the end of the loop. Otherwise it will only work once and then stop.
// clear file selector to allow reuse
event.target.value = "";
2. We also must set the value "workerSrc" to prevent a console warning message. More details about that here.
pdfjsLib.GlobalWorkerOptions.workerSrc = '//cdnjs.cloudflare.com/ajax/libs/pdf.js/2.7.570/pdf.worker.min.js';
Run the code snippet to see how it works (hold shift key down to select multiple pdf files):
let inputElement = document.getElementById('files')
inputElement.onchange = function(event) {
[].forEach.call(event.target.files, file => {
//var file = event.target.files[i];
//Step 2: Read the file using file reader
var fileReader = new FileReader();
fileReader.onload = function() {
//Step 4:turn array buffer into typed array
var typedarray = new Uint8Array(this.result);
//Step 5:pdfjs should be able to read this
const loadingTask = pdfjsLib.getDocument(typedarray);
loadingTask.promise.then(pdf => {
document.getElementById('result').innerHTML += "<li>" + file.name + " has " + pdf.numPages + "pages</li>";
// The document is loaded here...
});
};
//Step 3:Read the file as ArrayBuffer
fileReader.readAsArrayBuffer(file);
})
// clear file selector to allow reuse
event.target.value = "";
}
// Must set worker to avoid error: Deprecated API usage: No "GlobalWorkerOptions.workerSrc" specified.
pdfjsLib.GlobalWorkerOptions.workerSrc = '//cdnjs.cloudflare.com/ajax/libs/pdf.js/2.7.570/pdf.worker.min.js';
<div class="container">
<h4 class="text-center">Count Pages inside PDF Document</h4>
<div class="form-group container">
<input type="file" multiple accept=".pdf" required id="files" class="form-control">
</div>
<br><br>
<ol class="text-primary container" id="result"></ol>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.7.570/pdf.min.js" integrity="sha512-g4FwCPWM/fZB1Eie86ZwKjOP+yBIxSBM/b2gQAiSVqCgkyvZ0XxYPDEcN2qqaKKEvK6a05+IPL1raO96RrhYDQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
You can't.
Browsers don't let you access local paths on a user's computer for security reasons.
The browser doesn't get to know that the pdf is at /home/USERNAME/confidentialdocs/file.pdf, it just gets a data blob with a given filename.

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 do I expose images from json data

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);

Disable external content loading inside iFrame

Is there anyway of disabling loading external content inside of an iFrame?
Imagine there is a an iframe defined like:
<iframe srcdoc="
<html>
<head>
<title>Example Page!</title>
<link rel='stylesheet' type='text/css' href='http://example.com/mystyle.css'>
</head>
<body>
<p class='main'>Here goes the text.
</p>
<script src='http://example.com/js/superscript.js'>
</body>
</html>">
</iframe>
The loading of JS can be disabled with the allow-scripts inside of the sanbox attribute, but is there any way of disabling the load of the external css (and other external content)?
If not, is there any replacement for "rendering" html code (for example by JS), which would enable this?
I've made the following function to remove loading some assets from emails displayed in an iframe:
const replaced = []
const h = html
.replace(/url\s*\(([\s\S]+?)\)/g, (m,url) => {
url = url.trim()
try {
url = decodeURIComponent(url)
} catch (err) {/**/}
replaced.push(url)
return 'url()'
})
.replace(/[\s'"](?:src|srcset|background)?\s*=\s*(['"])([^\1]*?)\1/g, (m,q,src) => {
if (!src) return m // empty
replaced.push(src)
return ''
})
.replace(/<\s*link[^>]*?([\s'"]href\s*=\s*(['"])([^\2]*?)\2)/g, (m,attr,q,src) => {
if (!src) return // empty
replaced.push(src)
return m.replace(attr, '')
})
interestingly, <img alt="test"src="http://src.com/img.jpg"> is valid and will be displayed by chrome so whitespace before an attribute is actually not required, so I edited this answer to account for that...
It's probably not perfect, but you can tweak it as you see more cases by adding attributes...
Yes you can achieve it by using src not srcdoc and prefixing with data:text/html;charset=UTF-8,.
In your example:
<iframe src="data:text/html;charset=UTF-8,<html> <head> <title>Example Page!</title> <link rel='stylesheet' type='text/css' href='http://example.com/mystyle.css'> </head> <body> <p class='main'>Here goes the text. </p><script src='http://example.com/js/superscript.js'> </body> </html>">
</iframe>

Can't get javascript to change img source

A real beginner here, with a really basic question, but I simply can't get Javascript to change pictures when using the build in "onclick()" with HTML images..
I looked through so many questions about this, and tried different approaches to changing it, but can't get it to work.
I've tried with different src's, providing the full path and with online image adresses. Tried passing the variable. Simply can't get it to work.
<head>
<meta charset="utf-8">
<title> Javascript - changing images </title>
<script type="text/javascript">
function change() {
var image = document.getElementByID("fpimage");
image.src = "logo2.png"
}
</script>
</head>
<body>
<img src="logo.png" alt = "bla" id = "fpimage" onclick="change();"">
</body>
</html>
Change
var image = document.getElementByID("fpimage");
TO
var image = document.getElementById("fpimage");
You misspelled getElementById with a capital D
<head>
<meta charset="utf-8">
<title> Javascript - changing images </title>
<script type="text/javascript">
function change() {
var image = document.getElementById("fpimage");
image.src = "logo2.png"
}
</script>
</head>
<body>
<img src="http://i.imgur.com/cJjyJaG.jpg" alt = "bla" id = "fpimage" onclick="change();"">
</body>
</html>
Yep, like Clyde said, you made a mistake on the getElementById() function, keep in mind that Js is case sensitive ;)
<head>
<meta charset="utf-8">
<title> Javascript - changing images </title>
<script type="text/javascript">
function change() {
var image = document.getElementById("fpimage");
image.src = "http://www.dinosoria.com/mammifere/paresseux-206.jpg"
}
</script>
</head>
<body>
<img src="http://s.minutebuzz.com/i/2014/05/sloths-L.jpg.jpg" alt = "bla" id = "fpimage" onclick="change();"">
</body>
</html>

Categories