Loading an img object with a src in javascript - javascript

I want to add a thumbnail picture to a book's details, derived from the google books api, on the webpage. The code below will place the source code (api) for the appropriate book, first into the text field bookCover and then into the var copyPic, and then it should be copied into imgDisp, but it doesn’t. I can see that bookCover holds the right text, and have checked that copyPic holds the correct content.
<img id="imgDisp" src="http://books.google.com/books/content?
id=YIx0ngEACAAJ&printsec=frontcover&img=1&zoom=5&source=gbs_api" width="85" height="110"" />
$.getJSON(googleAPI, function(response) {
$("#title").html(response.items[0].volumeInfo.title);
$("#subtitle").html(response.items[0].volumeInfo.subtitle);
$("#author").html(response.items[0].volumeInfo.authors[0]);
$("#description").html(response.items[0].volumeInfo.description);
$("#version").html(response.items[0].volumeInfo.contentVersion);
$("#modeR").html(response.items[0].volumeInfo.readingModes.text);
$("#bookCover").html(response.items[0].volumeInfo.imageLinks.thumbnail);
var copyPic = document.getElementById('bookCover').innerHTML;
document.getElementById("imgDisp").src=copyPic;
Does anyone know why not? Or can I put the api details directly into imgDisp (can’t find such code syntax anywhere on the net)? Everything else is working fine. If I put a src in directly, then it works e.g.
document.getElementById("imgDisp").src = “http://.....api”
but not with a variable.

Without more info - eg, I can't see where the getJSON() function ends or what the URL's are, I can't see what the issue may be (except, perhaps, as in my last comment).
I idea seems ok, as I can replicate it (in a cut-down version of course):
function copyImageSource() {
let d = document.getElementById("bookCover").innerHTML;
document.getElementById("imgDisp").src = d;
}
<button onclick="copyImageSource();">Get image</button>
<div id="bookCover">https://duckduckgo.com/assets/icons/meta/DDG-icon_256x256.png</div>
<img id="imgDisp" src="">
I assume that this is the sort of thing you are trying to achieve?
(javascript -> jquery:
let copyPic = $("#bookCover").html();
$("#imgDisp").attr("src", copyPic);
)
Version using jquery:
function copyImageSource() {
let d = $("#bookCover");
d.html("http://books.google.com/books/content?id=YIx0ngEACAAJ&printsec=frontcover&img=1&zoom=5&source=gbs_api");
let dCopy = d.html().replace(/&/g, "&");
$("#imgDisp").attr("src", dCopy);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick="copyImageSource();">Get image</button>
<div id="bookCover"></div>
<img id="imgDisp" src="https://www.picsearch.com/images/logo.png"/>

If you have jQuery you can easily do the following:
let source = 'https://img.com/image.png';
//to get the image object that has the above just do this:
let img = $('img[src="' + source + '"]');

Related

How to access 2 different HTML files from 1 JS file?

I have two HTML pages and one JS file, which does the logic for both of them. When I try to change an image dynamically in one of my HTML files using var mainImage = document.getElementById("lastImageID"); this works, but when I try to do the same thing for the other HTML file, it doesn't (I receive null as a result).
I have "included" <script type="text/javascript" src="controller.js"></script> the JS file in both HTML files.I also tried to find information here, in Stack Overflow, how to access an element in an HTML file other than using the document notation, but seems this is the only right way.
I also checked and there are no identical IDs in both files.
First HTML file (relevant code):
<div class="thumbnail">
<img id="mainImageId" src="img/decision.jpg"
alt="Decision">
</div>
<div class="textMessage">
<div id="messageToUserID" class="infoText">
<h5>some text</h5>
</div>
</div>
Second HTML file (relevant code):
<div class="thumbnail">
<img id="lastImageID"
src="img/congratulations.jpg"
alt="Decision">
</div>
<div class="textMessage">
<div id="lastMessageToUserID" class="infoText">
<h5>some text</h5>
</div>
JavaScript Code:
// A function, which receives an new image, and updates the main image of the simulation by it.
function updateImageInLastScreen(newImage){
var mainImage = document.getElementById("mainImageId");
mainImage.src = newImage;
var lastImage = document.getElementById("lastImageID");
lastImage.src = newImage;
}
// A function, which receives an new message, and updates the main message of the simulation by it.
function updateMessageInLastScreen(newMessageToUser){
var mainMessageToUser = document.getElementById("messageToUserID");
messageToUserID.innerHTML = newMessageToUser;
var lastMessageToUser = document.getElementById("lastMessageToUserID");
lastMessageToUser.innerHTML = newMessageToUser;
}
The access to the elements in the first file work, but to those in the second one do not...
Here are 4 small files I am working with
Try adding if checks before manipulating the content:
// A function, which receives an new image, and updates the main image of the simulation by it.
function updateImageInLastScreen(newImage){
var mainImage = document.getElementById("mainImageId");
if (mainImage) {
mainImage.src = newImage;
}
var lastImage = document.getElementById("lastImageID");
if (lastImage) {
lastImage.src = newImage;
}
}
// A function, which receives an new message, and updates the main message of the simulation by it.
function updateMessageInLastScreen(newMessageToUser){
var mainMessageToUser = document.getElementById("messageToUserID");
if (mainMessageToUser) {
messageToUserID.innerHTML = newMessageToUser;
}
var lastMessageToUser = document.getElementById("lastMessageToUserID");
if (lastMessageToUser) {
lastMessageToUser.innerHTML = newMessageToUser;
}
}
So...I dont understand very well. Tell me if my explanation is equal your problem.
I have created page1.html
<h1>Image 1</h1>
<img src="" alt="image one" style="width:304px;height:228px;" id="image1">
<script src="myfile.js" type="text/javascript"></script>
Then, I have created page2.html
<h1>Image 2</h1>
<img src="" alt="image two" style="width:304px;height:228px;" id="image2">
<script src="myfile.js" type="text/javascript"></script>
In myfile.js I put the one piece image
var image1 = document.getElementById('image1');
var image2 = document.getElementById('image2');
if( image1) image1.src = 'image.jpg';
if( image2 ) image2.src = 'image.jpg';
This way is your problem ? Here, this way works both images.
when you call the same function updateImageInLastScreen() for the second html this line var mainImage = document.getElementById("mainImageId"); gets the value as null (since 'mainImageId' is not there in second html) and the second statement after it mainImage.src = newImage; throws an exception saying
TypeError: Cannot set property 'src' of null
at updateImageInLastScreen
and stops the further execution. You can verify the same in F12 console.
But when you call it from the first html then also it throws an exception for lastImage.src = newImage; but since it comes after the mainImage it's getting updated.
As per your code it's obvious that either of the element will be null since it's being called from a single html file. And you are blindly looking for the availability of the second element.
You can overcome this by putting your code inside a try..catch block as
function updateImageInLastScreen(newImage){
try{
var mainImage = document.getElementById("mainImageId");
mainImage.src = newImage;
}
catch(e){
console.log(e);
}
try{
var lastImage = document.getElementById("lastImageID");
lastImage.src = newImage;
}
catch(e){
console.log(e);
}
}
you can find it working here https://jsfiddle.net/hk30k20t/1/

Display html link with javascript

In some part of an html page, I have a link with the following code :
<a id="idname" class="classname" href="www.MySite.com/image-name.jpg">link-text</a>
I would like to automatically display the same link in another part of the same page by using a javascript.
What would be the script to insert in my page ?
Thank you in advance for any help in this matter.
Patrick
Try this:
myVar = document.getElementById("idname");
varLink = (myVar.attributes.href);
As son as you know the target id:
<div id="targetID">New Link: </div>
<div id="targetID2">New Link 2: </div>
And If you are using jQuery you can do like this:
var link = $("#idname").clone();
link.attr("id",link.attr("id") + (Math.random() * 10));
$("#targetID").append(link);
If not:
var link = document.getElementById("idname");
var newLink = document.createElement("a");
newLink.href = link.href;
newLink.className = link.className;
newLink.innerHTML = link.innerHTML;
newLink.id = link.id + (Math.random() * 10);
document.getElementById("targetID2").appendChild(newLink);
See this Example
<script>
window.onload = function() {
// get data from link we want to copy
var aHref = document.getElementById('idname').href;
var aText = document.getElementById('idname').innerHTML;
// create new link element with data above
var a = document.createElement('a');
a.innerHTML = aText;
a.href = aHref;
// paste our link to needed place
var placeToCopy = document.getElementById('anotherplace');
placeToCopy.appendChild(a);
}
</script>
Use code above, if you want just to copy your link to another place. JSFiddle
First, I want to point out that if you will just copy the element that will throw an error because the copied element will have the same id of the first one, so if you will create a copy of your element you don't have to give it the same id.
Try this code:
function copyLink(newDestination){
var dest=document.getElementById(newDestination);
var newLink=document.createElement("a");
var myLink=document.getElementsByClassName("classname")[0];
newLink.href=myLink.href;
newLink.className = myLink.className;
newLink.innerHTML = myLink.innerHTML;
newDestination.appendChild(newLink);
}
The newDestination parameter is the container element of the new Link.
For example if the new Container element has the id "div1":
window.onload = function() {
copyLink(div1);
}
Here's a DEMO.
Thank you very much to everyone for so many prompt replies.
Finally, I was able to use Jquery.
So, I tried the solution given by Andrew Lancaster.
In my page, I added the codes as follows, in this order :
1-
<span id="span1">
<a class="classname" href="www.MySite.com/image-name.jpg">link-text</a>
</span>
<p>
<span id="span2"></span>
</p>
and further down the page :
2-
<script type="text/javascript">
var span1val = $('#span1').html();
$('#span2').html(span1val);
</script>
Therefore, the two expected identical links are properly displayed.
But, unfortunately, I forgot to say something in my initial request:
the original link is in the bottom part of my page
I would like to have the duplicated link in a upper part of my page
So, would you know how to have the duplicated link above the original link ?
By the way, to solve the invalid markup mentioned by David, I just deleted id="idname" from the original link (that I could ignored or replaced by other means).
Thank you again in advance for any new reply.
Patrick
Using Jquery you could wrap your link in a span with an ID and then get the value of that ID and push it into another span id.
HTML
<span id="span1">
<a id="idname" class="classname" href="www.MySite.com/image-name.jpg">link-text</a>
</span>
<p>
<span id="span2"></span>
</p>
jQuery
var span1val = $('#span1').html();
$('#span2').html(span1val);
Example can be found here.
http://jsfiddle.net/3en2Lgmu/5/

Pass variables to code <input type="image" src="imageSrc;" >

hope someone can help a noob. Many thanks in advance.
I have an index page with links to hundreds of other pages holding song words.
I have built each song page but it would be MUCH simpler to have one MASTER page that took a variable from the index page and found the corresponding words (which exist as png graphics.)
I have sorted Step 1 - I can pass a variable from the index page to the master page using:
<a href="javascript: window.open('MUSIC/beatles/mastertest2.html?song=ER', '_parent')">
where song=ER is the variable to display the words for Eleanor Rigby. For Step 2, I can also retrieve that information in the master page with:
var imageSrc = (qs("song")+".png"); document.write(imageSrc);
which will display the text ER.png which is the name of the image I want to display.
For Step 3 I am trying to get this same variable read into:
<input type="image" src="imageSrc;">
to display the picture. I have searched this and other forums for days now and nothing suggested works for me. I could be missing out an essential early step in the coding?
Update:
My master html file has this code to retrieve the variable:
function qs(search_for) {
var query = window.location.search.substring(1);
var parms = query.split('&');
for (var i=0; i<parms.length; i++) {
var pos = parms[i].indexOf('=');
if (pos > 0 && search_for == parms[i].substring(0,pos)) {
return parms[i].substring(pos+1);;
}
}
return "";
}
And it uses this code to disply the variable (appended with .png) just to prove to me that it is getting through:
var imageSrc = (qs("song")+".png");
document.write(imageSrc);
Then I am trying to feed the variable into a routine to display the png selected. The next script doesn't work but I am thrashing about trying anything right now:
var imageSrc = (qs("song")+".png");
document.write(imageSrc);
<input type="image" src="#imageSrc;" border="0" value="Notes" onClick="placeIt(); showIt()">
<input id="song-image" type="image">
var imageSrc = 'ER.png';
var input = document.getElementById('song-image');
input.src = imageSrc;
If you have already <input type="image"> in your HTML page, you must add an id and then set it's src attribute with
HTML:
<input id="song-image" type="image">
JS:
var imageSrc = 'http://www.lorempixel.com/200/100';
var input = document.getElementById('song-image');
input.src = imageSrc;
JSFiddle for testing.
If I understood you right, its very simple. Are you looking for this?
var input = document.createElement('input');
input.type = 'image';
input.src = imageSrc;
document.body.appendChild(input);
If you can print the variable imageSrc using document.write, then you can use it like shown above.

Getting a function to actually output HTML

Have some JavaScript running that's dynamically building an array of images.
Here's the simplified version:
var imgArray = new Array(
"mainBG.jpg",
"mainBG2.jpg",
"mainBG3.jpg",
"mainBG4.jpg"
);
var img = Math.floor(Math.random()*imgArray.length);
jQuery(document).ready(function() {
$("body").ezBgResize({img : "/lib/img/bkgr/" + imgArray[img]});
});
function generateThumbs(){
var t = document.getElementById("thumbs");
var ret = '';
for(i=0;i<imgArray.length;i++){
var image = imgArray[i];
ret += '<a href="#" onclick="changeBig(\''+image+'\')" /><img src="/lib/img/bkgr/'+image+'" alt="thumbnail image" width="77" height="44" /></a>';
}
return ret;
};
function changeBig(bg){
$("body").ezBgResize({img : "/lib/img/bkgr/" + bg});
}
Then in the page, it's being written out simply with:
<div class="scrollable">
<div class="items" id="thumbs">
<script>document.write(generateThumbs());</script>
</div>
</div>
Problem is, when I view the source, it never outputs actual HTML. The source just shows that line. Is there a way to get that function to actually output HTML into the page-- partially for SEO, but also so some jQuery can interact with it
?
When you view source all you see is the code returned to the browser from the webserver without any modifcations javascript has done to the dom. To have the code in the raw source you need to generate it on the server side.
To see the generated source with the javascript modifications you can use firebug in firefox or the built in developer tools in Chrome/Safari/IE9.
This will do the trick
$(function(){
$("#thumbs").html(generateThumbs());
});
Don't call document.write in the context of an HTML page. You should be doing something like this:
<script type="text/javascript" language="javascript">
document.getElementById('thumbs').innerHTML = generateThumbs();
</script>
Try:
$('#thumbs').html(generateThumbs());

Changing data content on an Object Tag in HTML

I have an HTML page which contains an Object tag to host an embedded HTML page.
<object style="border: none;" standby="loading" id="contentarea"
width="100%" height="53%" type="text/html" data="test1.html"></object>
However, I need to be to change the HTML page within the object tag. The current code seems to create a clone of the object and replaces the existing object with it, like so:
function changeObjectUrl(newUrl)
{
var oContentArea = document.getElementById("contentarea");
var oClone = oContentArea.cloneNode(true);
oClone.data = newUrl;
var oPlaceHolder = document.getElementById("contentholder");
oPlaceHolder.removeChild(oContentArea);
oPlaceHolder.appendChild(oClone);
}
This seems a rather poor way of doing this. Does anyone know the 'correct' way of changing the embedded page?
Thanks!
EDIT: In response to answers below, here is the full source for the page I am now using. Using the setAttribute does not seem to change the content of the Object tag.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Test</title>
<script language="JavaScript">
function doPage()
{
var objTag = document.getElementById("contentarea");
if (objTag != null)
{
objTag.setAttribute('data', 'Test2.html');
alert('Page should have been changed');
}
}
</script>
</head>
<body>
<form name="Form1" method="POST">
<p><input type="button" value="Click to change page" onclick="doPage();" /></p>
<object style="visibility: visible; border: none;" standby="loading data" id="contentarea" title="loading" width="100%" height="53%" type="text/html" data="test1.html"></object>
</form>
</body>
</html>
The Test1.html and Test2.html pages are just simple HTML pages displaying the text 'Test1' and 'Test2' respectively.
You can do it with setAttribute
document.getElementById("contentarea").setAttribute('data', 'newPage.html');
EDIT:
It is also recommended that you use the window.onload to ensure that the DOM has loaded, otherwise you will not be able to access objects within it.
It could be something like this:
function changeData(newURL) {
if(!document.getElementById("contentarea"))
return false;
document.getElementById("contentarea").setAttribute('data', newURL);
}
window.onload = changeData;
You can read more about window.onload here
This seems to be a browser bug, setAttribute() should work. I found this workaround, which seems to work in all browsers:
var newUrl = 'http://example.com';
var objectEl = document.getElementById('contentarea');
objectEl.outerHTML = objectEl.outerHTML.replace(/data="(.+?)"/, 'data="' + newUrl + '"');
The above solutions did not work properly in Firefox, the Object tag doesn't refresh for some reason. My object tags show SVG images.
My working solution for this was to replace the complete Object node with a clone:
var object = document.getElementById(objectID);
object.setAttribute('data', newData);
var clone = object.cloneNode(true);
var parent = object.parentNode;
parent.removeChild(object );
parent.appendChild(clone );
Here's how I finally achieved it. You can do
document.getElementById("contentarea").object.location.href = url;
or maybe
document.getElementById("contentarea").object.parentWindow.navigate(url);
The Object element also has a 'readyState' property which can be used to check whether the contained page is 'loading' or 'complete'.
I found a very simple solution that also works in Chrome. The trick is to make the object (or a parent element) invisible, change the data attribute, and then make the object visible again.
In the code below, it is assumed that object_element is the object element and parent_element is the parent, and url is the url of the data.
parent_element.style.display = 'none'; // workaround for Chrome
object_element.setAttribute('data', url);
parent_element.style.display = '';
Following user2802253, I use this one on Safari and Firefox, which also forces a redraw. (sorry, not enough reputation to post as a simple comment).
theObject.style.visibility = null;
theObject.setAttribute("data", url);
theObject.style.visibility = "visible";
var obj = document.getElementById("pdfDoc");
obj.setAttribute('data', newPdf);
worked on Chrome version 54 and Safari, but didn't work on IE 11
what worked on them all
var obj = document.getElementById("pdfDoc");
obj.setAttribute('data', newPdf);
var cl = obj.cloneNode(true);
var parent = obj.parentNode;
parent.removeChild(obj);
parent.appendChild(cl);
This snippet did the job in my case
var object = document.getElementById(objectID);
object.setAttribute('data', newData);
var clone = object.cloneNode(true);
var parent = object.parentNode;
parent.removeChild(object );
parent.appendChild(clone );
<div id='myob'>
<object style="border: none;" standby="loading" id="contentarea"
width="100%" height="53%" type="text/html" data="test1.html"></object>
</div>
$('#myob').html($('#myob').html());
Changing the data attribute should be easy. However, it may not work perfectly on all browsers.
If the content is always HTML why not use an iframe?
Antoher way of doing it, you could embed the object in a DIV
var newUrl = 'http://example.com';
var divEl = document.getElementById('divID');
var objEl = document.getElementById('objID');
objEl.data = newUrl;
// Refresh the content
divEl.innerHTML = divEl.innerHTML;
I think this is a better way to achieve your objective.
Html:
<div id="mytemplate"><div>
Js:
function changeTemplate(t){
var mytemplate = document.getElementById("mytemplate");
mytemplate.innerHTML = '<object type="text/html" data=' + t + '></object>';
}
changeTemplate('template.html');
changeTemplate('whatever.html');
var content_area = document.getElementById("contentarea");
content_area.data = newUrl;
Refreshes object in Chrome Version 42.0.2311.90 m
the main reason of this issue is using "/" in local files.
The Wrong Code :
var obj = document.getElementById("hostedhtml");
obj.setAttribute('data', "pages\page2.html");
The Right Code :
var obj = document.getElementById("hostedhtml");
obj.setAttribute('data', "pages\\page2.html");

Categories