I'm just starting to learn javascript, so this is likely a pretty simple question. I've tried searching for an answer, but I think I just don't know enough to be like, 'oh, this looks different but answers my question too.'
What I want to be able to do is to change the background color of a page based on the time of day, and also change an image based on the time of day. I have it working with an if...else if... statement for the background color placed in the head of the page, and a separate if...else if... statement affecting the image in the body.
The head script that changes the bg color looks like:
var d=new Date();
var time=d.getHours();
if (time>=0 && time<=5)
{
document.write ('<body style="background-color: 296688">')
}
else if
...and then the other times follow, each with a different color.
The body script that changes the image looks like:
<img src="" name="sunMoon" id="sunMoon" />
<script type="text/javascript">
var d=new Date();
var time=d.getHours();
var elem = document.getElementById('sunMoon')
if (time>=0 && time<=5)
{
elem.src = 'Images/sunMoon1.png'
}
else if
...and then the other times follow, each with a different src.
Is it possible to change the image AND the bg color using the same if...else if... statement in the head? I tried something like this in the head:
var d=new Date();
var time=d.getHours();
var elem=document.getElementById('sunMoon')
if (time>=0 && time<=5)
{
document.write ('<body style="background-color: 2966B8">');
elem.src="images/sunMoon1.png"
}
else if...
but it didn't work.
I think with the third (nonworking) example, either it's not possible to have a single if... do two things (change the bg color AND the image), or I'm just messing up the image code.
The problem with your third (non-working) bit of code is that you are trying to change the source attribute of an element that doesn't exist when the script is run. Generally speaking the browser parses the page's HTML from top to bottom, when it comes across a block it runs the code then continues on through the HTML. So in the example you have working the JavaScript code that alters the image source comes after the element in the HTML which is why it works. In the broken code you call elem=document.getElementById('sunMoon') in the head section, so no element with ID 'sunMoon' exists yet.
Generally it is best practice to place your scripts at the bottom of the page (just before the closing tag) so that they run after everything else has loaded, and don't block the rendering of the page. If you were to do that you'd need to change the code that alters the background colour as you can't write it directly to the body tag. The best practice solution would be to apply a different CSS class to the body depending on the time of day and then set up style rules for each class in your CSS.
So for example:
<script type="text/javascript">
var body = document.getElementsByTagName('body')[0];
var elem = document.getElementById('sunMoon');
if (time>=0 && time<5)
{
body.className = 'morning';
elem.src = 'Images/sunMoon1.png';
}
else if (time>=5 && time<10)
{
body.className = 'afternoon';
elem.src = 'Images/sunMoon2.png';
}
</script>
Then in your CSS you need rules for .morning, .afternoon etc
Yes you can, you can change the body style like this:
document.body.style.backgroundcolor = color;
Yes you can use
var d=new Date();
var time=d.getHours();
var elem=document.getElementById('sunMoon')
if (time>=0 && time<=5)
{
document.body.style.backgroundImage ="images/sunMoon1.png";
document.body.style.backgroundColor = "#2966B8";
}
use onload event
<html>
<head>
<script>
function onBodyload(e){
var image = document.getElementById('sunMoon');
if(condition){
document.body.style.backgroundcolor = ...
image.src = ...
}else if(condition){
document.body.style.backgroundcolor = ...
image.src = ...
}else if...
}
</script>
</head>
<body onload="onBodyload">
...
...
</body>
</html>
Related
I'll start by apologising as this may seem like or actually be a duplicate, but I've tried every solution I've encountered and none seem to be working for me.
In my HTML I have an iframe referencing another HTML document. With JavaScript, at the press of a list of buttons I insert text into the body of that iframe. I also use JavaScript to maintain focus on the iframe body. The problem is that nothing appears to work for me to get the cursor to move to the end of the text each time I press those buttons, it always moves to the beginning.
One of the solutions I've tried was to add this code to the function that handles my button presses:
iFrameBody.focus();
var content = iFrameBody.innerHTML;
iFrameBody.innerHTML = content;
so the function looks like this:
function typeIn(buttonId) {
var iFrameBody = document.getElementById("iFrame").contentWindow.document.body;
iFrameBody.innerHTML += buttonId;
iFrameBody.focus();
var content = iFrameBody.innerHTML;
iFrameBody.innerHTML = content;
}
Something else I tried was, in the HTML file referenced by my iframe I did:
<body onfocus="this.innerHTML = this.innerHTML;"></body>
I tried several other more complicated solutions that frankly I didn't even quite understand to be honest, all to no avail. Any help would be much appreciated.
I figured it out. The issue was that I was using a body element, writing to it's innerHTML and trying to set focus on the body. By simply using a textarea inside my iFrame instead it became very simple and it only required the simplest code.
This to set focus when the page loads:
window.onload = function () {
var iFrameTextArea = document.getElementById("iFrame").contentWindow.document.getElementById("iFrameTextArea");
iFrameTextArea.focus();
}
And then this to set the button to write to the textarea while maintaining focus:
function typeIn(buttonId) {
var iFrameTextArea = document.getElementById("iFrame").contentWindow.document.getElementById("iFrameInput");
iFrameTextArea.focus();
iFrameTextArea.value += buttonId;
}
Super easy!!
Instead of again using textarea in iframe, u can also solve this by using the following code.
var iframeElement = document.getElementById("iFrame").contentWindow.document.body;
iframeElement.focus();
var len = iframeElement.length ;
iframeElement.setSelectionRange(len, len);
I have a js function that takes an html node and fades it from yellow to white. But it only works if before calling it from my js file I add text to body element via document document.writeln('Hi');. If I write text directly in my html file and don't call document.writeln then I don't see the fade effect after opening index.html.
<!DOCTYPE html>
<html>
<head>
<script src="program.js"></script>
</head>
<body style='width: 100%; height: 100%'>
Hi
</body>
</html>
JS file:
'use strict';
document.writeln('Hi'); // If we comment out this line we don't see the fade effect.
// Define a function that sets a DOM node's color
// to yellow and then fades it to white.
var fade = function (node) {
var color = 1;
var step = function () {
var hex = color.toString(16);
node.style.backgroundColor = '#FFFF' + hex + hex;
if(color < 15) {
color++;
setTimeout(step, 100);
}
}
setTimeout(step, 100);
};
fade(document.body);
EDIT:
Using window.onload for fade function also does not help.
I tried to use this one and it works without any errors:
document.addEventListener('DOMContentLoaded',function(){
fade(document.body);});
If the DOM is not loaded yet, you can't change it. So, this listener might help.
As described here, if you call Document.writeln() the browser calls Document.open() before, so there is an existing Document object. That might be the reason, why it worked, when you added this line before.
https://developer.mozilla.org/de/docs/Web/API/Document/write
You can also move the <script src="program.js"></script> to right before the </body> tag.
Is the function wrapped in a
$(document).ready(function()
{
//Function goes here
});
or a
window.onload = //function name here
if not, use either one & it should be working
EDIT
I've forgotten to say that you shouldn't forget to add jQuery before the external js file
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
I'm probably doing something obviously wrong but I'm using node.js and I have a javascript file linked properly (alert("hello"); works). But I can't affect anything with the DOM. Simple example:
jade:
doctype html
html
head
link(rel='stylesheet', href='/stylesheets/styles.css')
script(src='/javascripts/script.js')
body
block index_block
div#divClassName
stylus:
#divClassName
background-color red
width 200px
height 200px
js:
alert("hello");
var div = document.getElementById("divClassName");
div.style.backgroundColor = "green";
The box remains red. Why? Thanks.
Since your script is ran before the HTML has been read, the div variables returns undefined since no such element exists at the time your script is executed. Wrapping your JS in a function onload of the document allows you to defer execution until the document has been fully loaded.
window.onload = function(){
alert("hello");
var div = document.getElementById("divClassName");
div.style.backgroundColor = "green";
}
I'm trying to get an image to display in a div depending on the URL of the page. This div is in an include file that gets used for all pages of the website. What I want is if it's the homepage (with or without index.php), is for the div to show the image. What I've pieced together so far is:
<script type="text/javascript">
var d = location.href
if (d="website.com" || "website.com/index.php")
{
<img src="/images/DSLogo2.jpg" />;
}
</script>
I'm not sure if this is correct, or even the best way to go about it. Any help is very greatly appreciated, as I am still learning more and more each day.
Try:
<script type="text/javascript">
var d = window.location.href
if (d="website.com" || "website.com/index.php")
{
document.write('<img src="/images/DSLogo2.jpg" />');
}
</script>
Do not confuse = and == operator. The correct way how to code the condition is
if (d=="website.com" || d=="website.com/index.php")
Javascript is not a preprocessor, you can't usi it to create the code like in PHP. If you want to add element, you have to work with DOM:
<div id="target"></div>
<script>
var d = location.href;
var target = document.getElementById("target");
if (d=="website.com" || d=="website.com/index.php") {
target.innerHTML = '<img src="/images/DSLogo2.jpg"/>';
}
</script>
JavaScript doesn't work that way. You could use document.write with logic like that but something like this would be better:
if (your logic here) {
var image = document.getElementById('my_image');
image.src = 'some_image.jpg';
}
Notice that assumes you'll have a unique id on your image element. You'll want to put this logic in the document ready event or window on load.
I am trying to display a certain div depending on what day of the week it is with JavaScript. I have a div with an id of "thu". In the JavaScript code I try to pull that id from the document but nothing happens. Here's what I have:
Here is the div, while the separate style sheet displays it as "none".
<div id="thu">Thursday</div>
Here is the JavaScript in the head section of the same page.
var date = new Date();
var dayNum = date.getDay();
switch (dayNum)
{
case 4:
document.getElementById('thu').style.display='block';
break;
It won't display the div. I also tried assigning the element to a variable like this...
var block = document.getElementById("thu");
document.write(block);
...but it wrote "NULL".
Am I missing something? any help would be great.
Is the code running before the HTML has been written to the page? That is, is the <script> block before the <div id="thu">? That seems like the most likely problem.
You're probably attempting to access the element before the DOM is fully loaded. Put the call in the body Onload event, or better yet, take a look at JQuery - the way all this is handled there is very elegant.
The second block would write null if the element wasn't found. If it was found you'd get a response along the lines of [object HTMLDivElement]
You need to wait until the DOM is ready or the window has fully loaded before you can interact with it. To do that, you'll need to wrap your code in this format:
window.onload = function() {
// put your code in here
};
When I add a closing brace } after the break, it works for me.
<div id="thu" style="display:none">Thursday</div>
<script type="text/javascript">
var date = new Date();
var dayNum = date.getDay();
switch (dayNum)
{
case 4:
document.getElementById('thu').style.display='block';
break;
}
</script>