Jack Gerrard
Jack Gerrard

Reputation: 97

first JS, looking for advice from experienced JS programmer

I need to write a script to show particular divs on particular dates. My pseudocode looks like this so far:

import date from local system, //not sure if can/should do this?
var date == dateImported

switch(date){
    case date less than or equal to feb 14th:
          div called .valentines{ display: block;}
    break;
    case date equal to or less than march 17th:
          div called .paddys{display: block}
    break;
    case date between last event and dec 25th:
        div called .christmas display: block;
    break;

My questions are:

  1. Is there a cleaner way to do this?
  2. Whats the best way to decide the date variables value in this script?
  3. How should I make sure the div is hidden again after each occasion has passed?

I'm thinking I should I try not to be so specific and just use: var mm = today.getMonth()+1; and have a div for each month instead but I'd like to aim higher than that

Please don't write the code up for me, I want the practice. I just want guidance, much appreciated.

Upvotes: 0

Views: 88

Answers (2)

Nathan Thompson
Nathan Thompson

Reputation: 11

I would use momentjs to check dates.

var today = moment();
today.isBetween('2014-1-1', '2017-1-1'); // true
today.isBetween('2001-1-1', '2010-1-1'); // false

With moment, you can query before, same, after, combos of both, etc.

With that, you can use switches and add/remove classes to hide/show divs base on those switches with a javascript library (i.e. jquery).

Upvotes: 1

georg
georg

Reputation: 214949

One way to implement this would be the following:

Add two attributes to the divs in question like data-display-after and data-display-before, for example:

<div id="valentines" 
    data-display-after="2016-02-14 00:00:00" 
    data-display-before="2016-02-15 00:00:00">...

Hide these divs initially (with CSS).

On page load, convert the current date (new Date) into the above format.

For each element in document that has the data-display-before attribute (you'll need querySelectorAll), compare attribute values (getAttribute) and if currentDate >= data-display-after && currentDate <= data-display-after, then show the element.

This way, your JS and your markup will be "decoupled" and easy to maintain.

Upvotes: 1

Related Questions