the javascript execute not work how to change it? - javascript

<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

Related

What is read first HTML or JavaScript?

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>

Can Zombie.js/Phantom.js be used to get HTML of newly open window by window.open?

I am trying to get html of newly open window after activating a link that uses javascript by zombie.js.
Here is the html code
<html>
<head>
<script type="text/javascript">
function newin(id)
{
var url="page.php?id="+id;
window.open(url,id,"toolbar=no,location=top,directories=no,status=no,scrollbars=yes,hscroll=no,resizable=yes,copyhistory=no,width=1025,height=1250");
}
</script>
</head>
<body>
<div>
123<br/>
234<br/>
345<br/>
</div>
</body>
The Script I am using is:
var Browser = require("zombie");
var browser = new Browser();
browser.visit("http://localhost:8000/testpage.html", function () {
browser.wait(function(){
var selector = "a[href*='newin']";
var elements = browser.queryAll(selector);
for (var e=0;e<elements.length;e++){
browser.clickLink(elements[e],function(){
browser.wait(function(){
console.log(browser.html());
});
});
}
});
});
I am not able to get HTML of any window.Any ideas what is wrong in this code ? Or is this possible with phantomjs??
Finally I come to know that if a link contains JavaScript directly in the href or action, Zombie seems to understand that as opening a new page like a normal hyperlink would. While the JavaScript is still executed correctly, the DOM is lost as a result of Zombie trying to load the invalid target as a new page.
A problematic link would be e.g.
test
There’s no support for javascript:links, it is still an open issue:
https://github.com/assaf/zombie/issues/700

Javascript - Issue while updating value through innerHTML

I was trying to check some of javascript code and I found one thing which I am not able to understand the exact reason. In my html file, I have a div with id called test which dont have any value. Now, I want to update the a text/ sentence inside this div through innerHTML. as it is just for testing purpose I am not using any function/ event. Just adding a to update the value.
<body>
<script type="text/javascript">
var test_content = "This is new text in my test div";
document.getElementById("test").innerHTML = test_content;
</script>
<div id="test"></div>
</body>
Now, when I load the page, it showing empty nothing inside the test div but if put the javascript code below the div as in below, then it is showing the value in the variable. (note: I am not using any function nor event, just want to update on page load).
<body>
<div id="test"></div>
<script type="text/javascript">
var test_content = "This is new text in my test div";
document.getElementById("test").innerHTML = test_content;
</script>
</body>
can any one explain me the reason for this? Thanks in advance.
Thanks!
Robin
That's because the first is executed before the div#test is created, so it currently doesn't exist. That's why is a good practice to either put your script tags at the bottom of the page or wrap them with an window.onload event listener.
<body>
<script type="text/javascript">
window.onload = function () {
var test_content = "This is new text in my test div";
document.getElementById("test").innerHTML = test_content;
}
</script>
<div id="test"></div>
</body>
If you are using jQuery, you can also do this:
$(function () {
var test_content = "This is new text in my test div";
document.getElementById("test").innerHTML = test_content;
});
And since you seem to be a beginner in JavaScript coding, I recommend you read some articles on MDN, like this one and this one.
Pretty standard issue. Needs an 'onload' of some sort!
<body>
<div id="test"></div>
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function() {
var test_content = "This is new text in my test div";
document.getElementById("test").innerHTML = test_content;
});
</script>
</body>
The reason this is not happening in the the first instance, is because the DOM element, 'test' has not been created yet.
When you place the script after the div, the element has already been created and hence, the script can execute.
You will need to execute your code once the DOM is ready, by listening for load event dispatched from the body tag. This can be done quite simply using an in-line listener such as <body onload='myFunction'> or by an onload handler in javascript:
body.onload = function() {...}
Javascript is executed at runtime, as soon at it is being called. In your first example, the parser reads the script tag, executes it and then loads the rest of the page (top-to-bottom). As the script is executed before the div is laoded and created, the div will stay empty. That's the reason the onload event was introduced. http://www.w3schools.com/jsref/event_onload.asp
take one example of jquery you either have to write $(document).ready() or you have to write your jquery code at the last of html code and, both have same meaning i.e when all the html is loaded then do some function. this is same in this case, do some function after all the document content is loaded. take two cases:
case #1:
in this case we have the javascript code written above the html as in your first case which is without any event handler, the html engine will start reading the html code from top to bottom and at the moment it will hit to script tag it will call javascript engine. so according to this javascript code will be executed first.
if you write this line document.getElementById("test").innerHTML = test_content;
as :
var x = document.getElementById("test");
x.innerHTML = test_content;
then the console will return null i.e the value of x would benull.because div is still not loaded, therefore the value of div will not change
case #2:
script tag is placed at the last. so now, all the html is loaded by html engines, so now the value of x will be <div id="test"></div> and now all the javascript code will be executed without any error.
as i mentioned earlier about jquery $(document).ready()... well this is a jquery method but this can be written as in javascript as:
<script type="text/javascrip">
var start_script = function(){
// function to be performend
}
</script>
<body onload="start_script();">
......
</body>
because all the event are triggered when all the html is loaded and compiled.

Inserting variable (grabbed from json) into element

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

Problem with document.getElementById in JavaScript

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>

Categories

Resources