Variable for img src= - javascript

I have a question.
Firstly, I am not going to pretend that I know what I am talking about here. I am a newbie to http and JavaScript.
I think my question may be answered in this post
IMG SRC tags and JavaScript
but I thought I would explain the exact thing I am trying to achieve in case there is an easier way.
I have a webpage, I want to display an image on it. Only thing is, the image is coming from an automated system monitor, the image is automatically generated each day and placed in a new directory depending on date.
e.g. On April 4 = "http://host/partition/2009/apr/04/cpu.gif"
e.g. On April 5 = "http://host/partition/2009/apr/05/cpu.gif"
To facilitate this, I have created some basic JavaScript to give me the date in the format I need it. I have all that working. Now I just want to use that variable I created to show the image.
I have the JavaScript code stored in a function called displaydate()
If I do this <script language="JavaScript"> displaydate() </script> I see
"http://host/partition/2009/apr/05/cpu.gif" and that is correct.
Now how do I display this on the site correctly?
<img src="displaydate()" </td> //This does not work. I am just adding it to show where I have been heading.
P.S. I have read a lot of pages on this and been trying a lot of things, but have had no luck so far. Any help, would be much appreciated.

Yes, that page probably does answer your question. Basically, you want this javascript:
<script type="text/javascript">
document.getElementById('image').src = "yourpicture.png";
</script>
Except you want to replace the "yourpicture.png" with the function you wrote to generate the correct path to the image on disk, so...
<script type="text/javascript">
document.getElementById('image').src = displaydate();
</script>
Of course, you might need to modify this a bit for your own uses, the getElementById will take as an argument whatever the id attribute of your < img > tag is. You probably want to execute the above javascript after your page has loaded, i.e.:
<html>
<head>
<script type="text/javascript">
function load()
{
document.getElementById('image').src = displaydate();
}
function displaydate()
{
//your displaydate() function here
}
</script>
</head>
<body onload="load()">
<img src="nothing.jpg" id="image" name="image"/>
</body>
</html>

You should just need to change this line
document.write("http://host1/Shared/" + year + "/" + month + "/" + day + "/cpu_abs.gif");
to
return "http://host1/Shared/" + year + "/" + month + "/" + day + "/cpu_abs.gif";

Related

Unable to load HTML before Javascript

I am new to Javascript, and know how can I load html before javascript is executed.
I did check the questions on stackoverflow and tried to implement the solutions given but none worked.
Following is the code of various code that I tried.
Wrote script tag before the body ends
wrote the javascript code inside a function and called it inside onload of body but it didn't work either. (Also tried to comment documnet.onload = cal(); and execute).
<!DOCTYPE html>
<html>
<head>
<title>Age Calculator</title>
</head>
<body onload="cal();">
<h1>Age Calculator</h1>
<p>Enter your age and find how many days you have been alive</p>
<script type="text/javascript" src="Age.js"></script>
</body>
</html>
//Javascript code
function cal(){
var age = prompt("How old are you?");
var days = age * 365.25;
alert("You are approx " + days + " days");
}
documnet.onload = cal();
I want the html to be displayed before user is asked How old are you?
The problem is that prompt and similar functions like alert block the browser - they prevent rendering until the pop-up box has been submitted or canceled.
<h1>Age Calculator</h1>
<p>Enter your age and find how many days you have been alive</p>
<script>
var age = prompt("How old are you?");
</script>
If you want to make sure the HTML displays before the prompt comes up, you might use setTimeout, giving the browser a chance to paint the HTML before the prompt gets called:
<h1>Age Calculator</h1>
<p>Enter your age and find how many days you have been alive</p>
<script>
setTimeout(() => {
var age = prompt("How old are you?");
});
</script>
But an even better solution would be to use a proper modal, such as an input box with a submit button, which won't block the browser. (best to never use alert, prompt, and confirm if at all possible)
First of all, I suggest to read this article. Now, based on the source of this document, the best way (using only Javascript) to wait for the document to fully render before executing some code, will be using a listener on the load event of the window element, like this:
window.addEventListener('load', function() {
// Everything has loaded!
});
I have added an image to your code just to test how this approach waits the image to render before prompt to the user:
<h1>Age Calculator</h1>
<p>Enter your age and find how many days you have been alive</p>
<img src="https://via.placeholder.com/500?text=Test+Image">
<script>
function cal()
{
var age = prompt("How old are you?");
var days = age * 365.25;
alert("You are approx " + days + " days");
}
window.addEventListener('load', function()
{
// Everything has been rendered and loaded!
cal();
});
</script>

Insert iframe into site without using document.write

Our website uses an iframe to display a library of products we offer, and recently the iframe stopped loading in Google Chrome, because they stopped supporting document.write. We need a solution to show the page the same way we have been, but without using document.write. I am a novice, and have tried several solutions but nothing has worked.
what we have:
<script language="JavaScript">
<!--
var ss='<span style="font-size: small;"><b>NOTICE:</b> If you are having
trouble finding a pattern, try searching the first three letters of the
pattern name in the search bar. Also, be aware that some sheers may be
photographed with a window pane to show sheer quality.<br>If you are using
Google Chrome and have an issue viewing the library, please switch to another
browser.</span><br><br>';
var upper_limit = 500000000;
//-->
document.write(ss);
function getIP(json) {
document.write('<iframe frameborder="0" marginheight="0" width="100%"
height="700" src=" ' + 'http://client.richloomfabrics.com/cgi-bin/Wdrv01?
&PARPAR=CON&MELMEL=ALL&PTYPTY=UPH&IPAIPA=' + json.ip +
'&IPACOK=' + RandomNumber(upper_limit) + '&PGMPGM=WC033&>
</iframe>');
}
</script>
<script type="application/javascript" src="https://api.ipify.org?
format=jsonp&callback=getIP"></script>
We use a shopping cart, which is why we need the random number and IP. I have tried a few solutions I've seen but don't know enough about this to properly edit. Can anyone send me in the right direction?
You can also use appendChild
var iframeElem = document.createElement('iframe');
iframeElem.src = 'https://www.google.com';
document.body.appendChild(iframeElem);
In a very simple case you can just use innerHTML property of body, something like this
<script language="JavaScript">
<!--
var ss='<span style="font-size: small;"><b>NOTICE:</b> If you are having
trouble finding a pattern, try searching the first three letters of the
pattern name in the search bar. Also, be aware that some sheers may be
photographed with a window pane to show sheer quality.<br>If you are using
Google Chrome and have an issue viewing the library, please switch to another
browser.</span><br><br>';
var upper_limit = 500000000;
//-->
document.body.innerHTML += ss;
function getIP(json) {
document.body.innerHTML += '<iframe frameborder="0" marginheight="0" width="100%"
height="700" src=" ' + 'http://client.richloomfabrics.com/cgi-bin/Wdrv01?
&PARPAR=CON&MELMEL=ALL&PTYPTY=UPH&IPAIPA=' + json.ip +
'&IPACOK=' + RandomNumber(upper_limit) + '&PGMPGM=WC033&>
</iframe>';
}
</script>
<script type="application/javascript" src="https://api.ipify.org?
format=jsonp&callback=getIP"></script>

how can i combine javascript variables inside html

i was wondering how to change a picture's size with a dynamic variable, but i cant make it work for some reason. here is my code:
i have a variable named picH inside my javascript block:
var picH = 2;
and then i have my html code which supplies the image with the height property:
img src="img/1.png" height="picH"
I tried to supply the variable but it doesn't seem to work. the size does change if i enter a number instead.
Ok so first off as sad as it may be, I agree with the mean comments above that you should probably just read a few HTML and JavaScript tutorials. jQuery is probably a good way to go but believe it or not back in the olden days we used JavaScript without the benefit of fancy frameworks. I'd say what you're driving at is something a little more like this:
<html>
<head>
<title>Webpage</title>
</head>
<body>
<img src="img/1.png" id="theIDofTheImage">
</body>
</html>
<script>
var picH = 2;
var imageElement = document.getElementById("theIDofTheImage");
imageElement.height = picH;
</script>
Of course I'm sure you're doing something a little more complicated but I wanted to just give a simplistic answer to your question.
Cheers!
~JI

Function tag seems to not work?

I am trying to write a simple "Choose your own adventure" style game in Javascript format, mainly because its simple to write, but I have run into a problem. I am trying to get the javascript to run on page load, but it wont start. I am just left with a blank page.
Here is the code:
<!doctype html>
<body>
<title>Dungeons and Dwarves</title>
<script type="text/javascript>
function begin() {
alert("Welcome to Dungeons and Dwarves! A free 'Choose Your Own Adventure' game. In this adventure, you will be faced with many decisions, some of which could potentially lead to your death. If you are willing to put your life on the line, and leap forward into a new world and explore the unexplored, press OK to begin.")
var myAge = prompt("How old are you, adventurer?")
if (myAge < 18)
{
alert("Oh! They start younger and younger every year! You'll be careful out there, wont you?")
}
else
{
alert("I see you have had some experience with adventures! I wish you the best of luck, not that you will need it!")
}
}
</script>
<body onload='javascript:begin()'>
</body>
Im not sure what I have done wrong here, but I think the function tag isn't working properly. Just the way it looks in Notepad++, that might just be me. Could anyone give me assistance?
I apologise if I have formatted this wrong.
The browser thinks your JavaScript is not JavaScript (but some other, unknown kind of script):
<script type="text/javascript>
You omitted the second " from the type attribute.
As of HTML 5, the type attribute may be omited if you are using JavaScript, so just write:
<script>
Additionally, you have two <body> start tags. Only one of them has an onload attribute. Browsers may parse the first one and then ignore the second one.
These (among some other errors) would have been picked up by a validator.
You forgot " at:
<script type="text/javascript>
Make sure you put the " in front of >:
<script type="text/javascript">
And as Quentin notes, you have two body tags.
type="text/javascript" //add a " at the end
Correction
<script type="text/javascript">
Try this:
<html>
<head>
<title>Dungeons and Dwarves</title>
<script>
function begin()
{
alert("Welcome to Dungeons and Dwarves! A free 'Choose Your Own Adventure' game. In this adventure, you will be faced with many decisions, some of which could potentially lead to your death. If you are willing to put your life on the line, and leap forward into a new world and explore the unexplored, press OK to begin.")
var myAge = prompt("How old are you, adventurer?")
if (myAge < 18)
{
alert("Oh! They start younger and younger every year! You'll be careful out there, wont you?")
}
else
{
alert("I see you have had some experience with adventures! I wish you the best of luck, not that you will need it!")
}
}
</script>
</head>
<body onload='javascript:begin()'></body>
</html>
You are missing " at:
<script type="text/javascript>
You have misplaces the <body> tag at line number 2: remove body tag from there.
You need to include your <title> tag in <head> tag.
<script type="text/javascript>
would be
<script type="text/javascript">
and <body onload='javascript:begin()'></body>
would be
<body onload='javascript:begin();'></body>
all your alerts need to end like
var myAge = prompt("How old are you, adventurer?");

where to embed javascript section in a html page [duplicate]

This question already has answers here:
when and where to put javascript in html
(7 answers)
Closed 9 years ago.
the thing is i'm unable to figure out where to embed javascript in html page whether in head section or body section.
example 1:
<html>
<head>
<title>events</title>
<script>
document.getElementById("b").onclick=function(){displayDate()};
function displayDate()
{
document.getElementById("demo").innerHTML=Date();
}
</script>
</head>
<body>
<p id="demo"></p>
<button id="b">new</button>
</body>
</html>
in the above example I placed script tags in head section but it is not working.
example: 2
<html>
<head>
<title>events</title>
<script>
function upper()
{
var x=document.getElementById("t");
x.value=x.value.toUpperCase();
}
</script>
</head>
<body >
enter some text:<input type="text" id="t" onChange="upper()"/>
</body>
</html>
in the second example I placed the javascript in head section it is working properly.first example demonstrates that on clicking a button date will be displayed in the second example in a text box when data is entered and if we come out of the box the letters in the box will we converted to uppercase.
To have it more readable I prefer to always place JavaScript in the head section. If you need to access elements from there, use the window.onload event:
<head>
<title>events</title>
<script type="text/javascript">
window.onload = function() {
document.getElementById("b").onclick = function() {
displayDate();
};
};
function displayDate()
{
document.getElementById("demo").innerHTML=Date();
}
</script>
</head>
This would work just fine.
Your second example worked because you just defined a function, you didn't try to access any element.
You can put it in the head. The problem is that your examples are not the same. The first one doesn't work because the current date is retrieved by calling Date(), when it should be new Data().getDate(). The second example works because the code is valid.
The problem you're running into is that you're trying to reference an element before it is loaded into the DOM.
When you're putting the script in the HEAD tag, the dom hasn't been loaded yet and the document.getElementById won't find what you're looking for.
You have a few different options to deal with this. You can put the script at the end of the page, which will work for your small example here.
Probably a better option is to take a look at learning/using jquery or another js utility. Jquery makes it easy to solve this issue by giving you a "ready" event. This ready event will be triggered when the DOM is fully loaded. So:
$(document).ready(
function()
{
$("#demo").html((new Date()).toString());
});
Is all you really need. With this approach, it doesn't matter where the script it on the page.

Categories