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>
Related
from an issue I am experiencing I understand how it works, but I can't find any formal reference that helps me to clarify the behaviour.
<head>
<title>Chapter 7: Example 7</title>
<script type="text/javascript">
var formWeek = document.form1;
var weekDays = new Array();
weekDays = formWeek.theDay.options;
function btnRemoveWed_onclick()
{
console.log("In btnRemoveWed_onclick");
}
</script>
</head>
<body>
<form action="" name="form1">
<select name="theDay" size="5">
<option value="0" selected="selected"></option>
With this code I receive an error on line "weekDays = formWeek.theDay.options;" because "theDay" is not defined. So I believe that while the JS code is executed the browser has not parsed and loaded the DOM (hence it doesn't know about form1).
If I move the variable definition inside the function, everything works fine.
function btnRemoveWed_onclick()
{
console.log("In btnRemoveWed_onclick");
var formWeek = document.form1;
var weekDays = new Array();
weekDays = formWeek.theDay.options;
}
At function execution the browser knows about form1 (load all the HTML code).
So... from the code the behaviour is clear but still it has not 'clicked' on my mind how it works.
I thought that the link below was a good reference to understand the behaviour.
Where should I put <script> tags in HTML markup?
Can you point me to some good reading that explains HTML-JS loading?
For what i know, javascript is loaded in line with HTML. So if you have an element <foo> and then a script that uses <foo> after that, it works. Turn them around, and the script is loaded first, after that the foo element. This way your script cannot find the element.
Change your javascript to:
function init()
{
var formWeek = document.form1;
var weekDays = new Array();
weekDays = formWeek.theDay.options;
function btnRemoveWed_onclick()
{
console.log("In btnRemoveWed_onclick");
}
}
document.addEventListener('DOMContentLoaded', init, false);
this way you make sure the javascript is loaded when the DOM is ready.
When you have an inline script tag in HTML, it blocks the parsing of HTML and it is executed immediately. Anything written after it has not been parsed yet.
It's common practice to put script tags at the end of the body tag, because at that point the DOM has been parsed and JS can safely execute.
As far as the error you pointed out is concerned, you can wait for the browser to finish loading the page by using something like window.onload. Notice lower in the documentation, in the Notes section
The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images, scripts, links and sub-frames have finished loading.
This means by the time the code is run, your HTML has been parsed and put into the DOM. Your script tag, then, will be:
<script type="text/javascript">
window.onload = function() {
var formWeek = document.form1;
var weekDays = new Array();
weekDays = formWeek.theDay.options;
}
function btnRemoveWed_onclick()
{
console.log("In btnRemoveWed_onclick");
}
</script>
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);
<script type="text/javascript">
//window.onload = Now;
function Now(){
var n=new Date();
return n.toLocaleDateString();
};
</script>
i put the above code in the head part.
<body onload="Now();">
but on the page, there is no show anything.when i using window.onload = Now or put the script code after the label; the result is the same, why?
ps:i want to write the result out on the page. but when i used document.write(Now()); it still not displayed on the page.
You aren't doing anything with the return value of Now(), so it is being quietly discarded.
Perhaps you want to do something like onload="alert(Now());"
Try to put alert box. If it exists in the script or not.
Modify your HTML a bit to have a DOM element that will help you post the resut onto your page,
<body onload="Now();">
<span id="dateHelper"></span>
</body>
And then modify your script to do the following,
function Now(){
var n=new Date();
var lds = n.toLocaleDateString();
document.getElementById("dateHelper").innerHTML = lds;
};
Test Link
I have a function to grab a video title from a YouTube json callback, which works - however I'm having issues inserting the variable into an element.
Here is the feed I'm grabbing:
<script type="text/javascript" src="http://gdata.youtube.com/feeds/api/videos/2WNrx2jq184?v=2&alt=json-in-script&callback=youtubeFeedCallback"></script>
The javascript function I'm using:
function youtubeFeedCallback(data) {
var info = data.entry.title.$t;
document.write(info);
}
This works fine, but I'd like to insert it into a div with the ID "box".
Usually I would use the following (and add it to the function - and remove the document.write):
var box = document.getElementById('box');
box.innerHTML = info;
I just cannot get this to work though. What would be the correct way to achieve what I'm trying to do? Thanks
http://jsfiddle.net/b3VYT/
Either make sure that the script is below the element or wrap your code in a document.ready callback so that it is not run until after the DOM is loaded.
http://jsfiddle.net/b3VYT/1
You need to make sure that the element that you are using is declared prior to your script executing:
<div id='test'></div>
<script>
function youtubeFeedCallback(data) {
document.getElementById('test').innerHTML = data.entry.title.$t;
}
</script>
Example
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>