Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Simple JQuery Question

Hi there. I am new to JQuery and would like to include a message customized to the time of day on my website and output something based on what time it is. I want this to be in the header of my site as well and I am not sure what I am doing wrong because with this code:

            function welcomeMessage()
    {
      var now = new Date();
      var hours = now.getHours();
      var msg;
      if(hours<12)
        msg = "<h3><span>Good Morning</h3></span>";
      else if(hours<18)
        msg = "<h3><span>Good Afternoon</h3></span>";
      else
        msg = "<h3><span>Good Evening</h3></span>";
      return(msg);
    }

That outputs nothing into my header... I am not sure where I am going wrong?

Thank you for your time!

Nevermind, I got it to work :D

1 Answer

Just a few changes

<div class="message"></div>

 function welcomeMessage()
  {
    var now = new Date();
    var hours = now.getHours();
    var msg;
    if(hours<12)
      msg = "<h3><span>Good Morning</h3></span>";
    else if(hours<18)
      msg = "<h3><span>Good Afternoon</h3></span>";
    else
      msg = "<h3><span>Good Evening</h3></span>";
  $('.message').html(msg);  //add message to the element with class message
}
welcomeMessage();

Avoid using classes when it's just one place. You should use IDs for javascript mostly. way faster.

James Barnett
James Barnett
39,199 Points

Repeat after me ... use classes for CSS and ids for JavaScript.


It's still much better to select by ID...because jQuery uses the browser's native method (getElementByID) to do this and doesn't have to do any of it's own DOM traversal, which is much faster.

quote source: http://stackoverflow.com/a/2559973/1756132