0

Simple question.

I'm newbie on javascript and html.

I have a file index.html like:

<html>
<head>
<link rel=StyleSheet href="beauty.css" type="text/css">
<script src="myjs.js"></script>

</head>
<body>
<p id="foo"></p>
</body>
</html>

and this is my js file:

var d=new Date();
var month = d.getMonth()+1;
var data = d.getDate() + "/" + month + "/" + d.getFullYear();
function showdata(){
    return data;
}

document.getElementById("foo").innerHTML=showdata();

I understand that I need to reference the html, but I do not have idea how to do that.

4
  • What do you mean by reference the html? That could mean a lot of different things... Commented Jul 7, 2012 at 23:12
  • Which HTML do you want to "reference" ? Commented Jul 7, 2012 at 23:13
  • the index.html that has the first lines of code. Commented Jul 7, 2012 at 23:14
  • yes, but which part specifically? Commented Jul 7, 2012 at 23:14

2 Answers 2

1

You might want

window.onload = function() {
   var d=new Date();
   var month = d.getMonth()+1;
   var data = d.getDate() + "/" + month + "/" + d.getFullYear();
   function showdata(){
       return data;
   }

   document.getElementById("foo").innerHTML=showdata();
}

You also might want to specify type="text/javascript" in your <script> tag.

Sign up to request clarification or add additional context in comments.

1 Comment

One trouble with window.onload is that only one function can be attached this way. If you need it for some other purpose, or you use some third-party script that does, one declaration will override all the others. You might want to try Xavi's solution, or look at something to help you run multiple events when the DOM is ready or the window is loaded, not just a single one.
0

Try moving the script tag to the bottom of the page. Right before closing </body> tag. Something like this:

<html>
    <head>
    <link rel=StyleSheet href="beauty.css" type="text/css">

    </head>
    <body>
        <p id="foo"></p>
        <script src="myjs.js"></script>
    </body>
</html>

The problem is that your javascript code was executed before the paragraph element was part of the page.

1 Comment

Why the down votes? Moving your scripts to the bottom of the page is generally good practice regardless. It helps improved perceived page load. Browsers must pause page rendering every time a script tag is encountered. By putting script tags at the bottom of the page, the browser has a chance to render all the page's content before pausing to execute javascript. Also, window.onload is only executed once all the assets on the page are loaded which in many cases needlessly delays javascript execution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.