Javascript problem when returning function? - javascript

I have a function like this:
function ban_rot(){
var bnr = new Array();
bnr[0] = "/Graphics/adv/businesscrown.gif";
bnr[1] = "/Graphics/adv/webbdesigna.jpg";
num = bnr.length - 1;
i = Math.round(Math.random(bnr) * num);
return '<img src=\"' + i + '\" alt=\"\" border=\"1px\" style=\"border-color:#000;\">';
}
I then have a html code:
<td align="center"><a href="http://www.domain.com" class="links4">
<script type="text/javascript">return ban_rot();</script>
</a>
</td>
The above doesn't work, ie nothing shows up. empty.
Any ideas?
Thanks

return doesn't work like echo in PHP. If you want to output into your HTML, you need to create an element and then update it (for instance, by editing it's innerHTML attribute).
<td align="center"><a href="http://www.businesscrown.com" class="links4">
<div id="banner"></div>
<script type="text/javascript">
document.getElementById('banner').innerHTML = ban_rot();
</script>
</a>
</td>

Since the ban_rot() function returns a String and you want to display the String you may need to do this:
<script type="text/javascript">document.write( ban_rot());</script>

I think you're conflating the server-side templating paradigm with client-side JavaScript. Even if you return a string from a JavaScript function, as you have done, it doesn't magically insert that string into the DOM and remove the <script> tags.
Instead, you need to use DOM API methods to turn your function-returned string into an actual HTML element, like this: document.getElementById('some_element_id').innerHTML = ban_rot();

Just returning the HTML string won't print it.
You need to do something like document.write().

"return" is used to return a value from a function. You can not use it to put code in a page. You can use document.write(...) but I would highly recommend you learn jQuery. It makes modifying the html much easier.

you can't just return in the middle of a document.
<td align="center">
<a href="http://www.domain.com" class="links4" id='myLink'></a>
<script type="text/javascript">
document.getElementById('myLink').innerHTML = ban_rot();
</script>
</td>
note that you have to give your link an id so that it may be referenced (or pick another wya to find it).
the preferred way to do all this is to construct new elements with the DOM methods.
function ban_rot() {
var bnr = new Array();
bnr[0] = "/Graphics/adv/businesscrown.gif";
bnr[1] = "/Graphics/adv/webbdesigna.jpg";
num = bnr.length - 1;
i = Math.round(Math.random(bnr) * num);
var img = document.createElement('img');
img.src = i.toString();
img.style.border = '1px solid #000';
var myLink = document.getElementById('myLink');
myLink.appendChild(img);
}
then you don't need to return anything- the method will add the image to the link.
<td align="center">
<a href="http://www.domain.com" class="links4" id='myLink'></a>
<script type="text/javascript">ban_rot();</script>
</td>

Related

Loading an img object with a src in 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 + '"]');

How to store from external javascript variable value to html variable value

I want to store the jquery variable value to the html variable value.
Here is my code,
This is the javascript function which is in external javascript page
function createImage(settings) {
var kk = createCanvas(settings)[0].toDataURL('image/png');
}
Now, this is in html page
var karan = kk;
<img id="containerQrCode" src = "+ karan +" alt="qr image" />
Now, how can I move the kk value which is in external javascript page to the karan variable which is in html page.
Thanks In Advance.
I will suggest you work with the DOM. Some thing like the below if your are jQuery.
function createImage(settings) {
var kk = createCanvas(settings)[0].toDataURL('image/png');
$("#containerQrCode").attr("src", kk);
}
below can be tried if not using jquery
function createImage(settings) {
var kk = createCanvas(settings)[0].toDataURL('image/png');
document.getElementById("containerQrCode").setAttribute("src", kk);
}
try something like this:
<img id="containerQrCode" src = "
<script type="text/javascript>document.write(karan)</script>
" alt="qr image" />
Sorry misread about setting the variable as well, try this:
Edit the function to say this:
function createImage(settings) {
var kk = createCanvas(settings)[0].toDataURL('image/png');
return kk;
}
Then update where you set karan to this:
var karan = createImage();
You will also need to include the external javascript file in the project like this:
<script type="text/javascript" src="path/to/your/file.js"></script>
var karan = kk;
var img = document.getElementById('containerQrCode');
img.src = karan;

How to access the Javascript variable value outside the script tag

I want to access the Javascript variable value outside the Javascript tag.
function getprices(input) {
return input.match(/[0-9]+/g);
}
var subtotals = get_getprices('%GLOBAL_OrderTotal%');
var Grand_total = subtotals[0];
<img height="0" width="0" border="0" src="http://testing.com?merchantId=M1&orderNo=%%GLOBAL_OrderId%%&saleAmount=I want the Grand+Total Value here">
You'd need to update the src property on that img element. Let's suppose you gave the img an id (you don't have to, there are other ways to select it, but I'm keeping it simple):
<img id="the-image" height="0" width="0" border="0" src="http://testing.com?merchantId=M1&orderNo=%%GLOBAL_OrderId%%&saleAmount=I want the Grand+Total Value here">
Then:
function getprices(input) {
return input.match(/[0-9]+/g);
}
var subtotals = getprices('%%GLOBAL_OrderTotal%%'); // <=== Changed to `getprices`, was `get_getprices`
var Grand_total=subtotals[0];
var img = document.getElementById("the-image");
img.src = "http://testing.com?merchantId=M1&orderNo=%%GLOBAL_OrderId%%&saleAmount=" + Grand_total;
It looks like Grand_total will always be a number, but for the general case where it might not be, , be sure to use encodeURIComponent (it doesn't do any harm even if it is a number):
img.src = "http://testing.com?merchantId=M1&orderNo=%%GLOBAL_OrderId%%&saleAmount=" + encodeURIComponent(Grand_total);
If you didn't use an id on the img, that's fine, you can use any CSS selector via document.querySelector. That's supported by all modern browsers, and also IE8.
Note that there are other issues with that code, though, not least that getprices looks fairly suspect.
All you need to do is to assign your value to src of img in your javascript
$("#imgNeeded").attr("src",".../"+Globalvalue)
As T.J. Crowder said. make sure you encode URI if your variable contain something other than number
You can use
document.getElementsByTagName("img")[***index of the image tag***].src = "<THE STRING>"+<THE VARIABLE>+"<THE REMAINING STRING>";
or assign an id to the <img> and use
`document.getElementById("id of the image").src = ""++"";
The problem the provided approaches share is, that how they are, your image will get loaded with the unwanted source before changed:
<html>
<head>
<script>
function getprices(input){return input.match(/[0-9]+/g)};
function changeSrc(){
var tE = document.querySelector("img[src*='saleAmount=']");
var tS = getprices('anyPrice1');
if (tE && tS) tE.src += encodeURIComponent(tS[0]);
};
</script>
</head>
<body onload = 'changeSrc()'>
<img height = '0' width = '0' border = '0' src = 'http://JUSTTOSHOWtesting.com?merchantId=M1&orderNo=%%GLOBAL_OrderId%%&saleAmount=' onerror = 'console.log(this.src)'>
</body>
Your console will log two calls:
- GET http://justtoshowtesting.com/?merchantId=M1&orderNo=%%GLOBAL_OrderId%%&saleAmount= net::ERR_NAME_NOT_RESOLVED
- GET http://justtoshowtesting.com/?merchantId=M1&orderNo=%%GLOBAL_OrderId%%&saleAmount=1 net::ERR_NAME_NOT_RESOLVED
So what you could do is placing a placeholder, until you have the source you need:
<html>
<head>
<script>
function getprices(input){return input.match(/[0-9]+/g)};
function createSrc(){
var tE = document.querySelector("ins[src*='saleAmount=']");
var tS = getprices('anyPrice1');
if (tE && tS){
var tI = document.getElementById('iPlaceholder');
if (!tI){
tI = document.createElement('img');
tI.id = 'iPlaceholder';
tI.onerror = function(){console.log(this.src)};
tE.parentNode.insertBefore(tI, tE.nextSibling);
};
tI.src = tE.getAttribute('src') + encodeURIComponent(tS[0]);
};
};
</script>
</head>
<body onload = 'createSrc()'>
<ins src = 'http://JUSTTOSHOWtesting.com?merchantId=M1&orderNo=%%GLOBAL_OrderId%%&saleAmount='></ins>
</body>
</html>
Now your console will merely log one call:
- GET http://justtoshowtesting.com/?merchantId=M1&orderNo=%%GLOBAL_OrderId%%&saleAmount=1 net::ERR_NAME_NOT_RESOLVED

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