Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New Coder
    Join Date
    Jun 2013
    Location
    Rio Rancho
    Posts
    18
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Need help with text per hour generator

    So I want to generate a certain text at each time of day, but my code does not appear to be working. The page just displays blank and white.

    <script>
    function myFunction()
    {
    var x="";
    var time=new Date().getHours();
    if (time<10)
    **{
    **x="Good morning";
    **}
    else if (time<20)
    **{
    **x="Good day";
    **}
    else
    **{
    **x="Good evening";
    **}
    document.write=x;
    }
    </script>

  • #2
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,733
    Thanks
    202
    Thanked 2,508 Times in 2,486 Posts
    This is obviously homework!


    What are the ** supposed to do?

    You do not call your function anywhere. So the page just displays blank and white.

    Try this (note how the greetings are ordered):-


    Code:
    <script type = "text/javascript">
    
    function myFunction() {
    var x="Good evening";  // default
    var time=new Date().getHours();
    if (time<20) {x="Good day"}
    if (time<10) {x="Good morning"}
    document.write(x);  //note the syntax
    }
    
    myFunction();  // call (execute) the function
    </script>
    Note that document.write is obsolete and you should use DOM methods to display a message to your user.

    It is recommended that the opening brace { is placed on the same line as the function, if, else, do, while, or for statement and not on the following line. This is because of something known as automatic semi-colon insertion. If you disregard this advice it is looking out for it chance and one day it will rise up and bite you in the undercarriage, and create an error which can be hard to find.



    All advice is supplied packaged by intellectual weight, and not by volume. Contents may settle slightly in transit.
    Last edited by Philip M; 09-08-2013 at 09:50 AM.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • Users who have thanked Philip M for this post:

    Cadethen (09-14-2013)

  • #3
    New Coder
    Join Date
    Jun 2013
    Location
    Rio Rancho
    Posts
    18
    Thanks
    2
    Thanked 0 Times in 0 Posts
    Not homework, just an old code I found on my website I need to revamp. Thanks for your help! As for the ** I'm not sure where they came from, probably just a copy paste error.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •