Skip to Main Content

Jump Link Based on Current Day

Setting the page to jump to a section further down based on the visitors day of the week as set by their computer or browser

I'm working on a restaurant site with a specials page. On the specials landing page each day of the week shows the first two specials with a link off to see the rest of that days specials. This works fine, however the page is a little long and I wanted the page to jump to today's special on page load. This was not difficult to do at all.

The HTML

    
    
      <section class="specials">
	<a name="monday"></a>
</section>

<section class="specials">
	<a name="tuesday"></a>
</section>

<section class="specials">
	<a name="wednesday"></a>
</section>
    
  

The javascript is quite simple. First set a variable 'today' to the current day of the week. Then create a new variable 'jumplink' and insert the first variable into the href attribute append this to the body and trigger a click on page load.

    
    
      var today =	["sunday","monday","tuesday","wednesday","thursday","friday","saturday"][(new Date()).getDay()];

var jumpLink = "<a href='#" + today +"' class='today' style='display:none;'></a>";

$('body').append(jumpLink);


// delay 1s and then click the hidden today link to scroll down to today's specials 
setTimeout(function(){ 
  $('a.today').trigger('click'); 
}, 1000);
    
  

I've also got smooth scrolling set up so that when the page loads it's not a jerky jump. Am using this code which I cribbed from CSS Tricks

    
    
      /*
https://css-tricks.com/snippets/jquery/smooth-scrolling/#comment-197181
*/
$(function() {
  $('a[href*="#"]:not([href="#"]):not([role="tab"])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html, body').animate({
          scrollTop: target.offset().top
        }, 1000);
        return false;
      }
    }
  });
});