user3229136
user3229136

Reputation: 13

Change display:none based on date

I am building a site to be used locally on my tablet, I don't want to us php.

I have several divs that need to be displayed on different days. IE: div 1 displays today div 2 displays tomorrow div 3 displays the next day etc... This is the code I have to change content based on date but this isn't what I want to do. How can I modify the code to change the display (I am a complete noob at js code):

<script type="text/javascript">
var date=new Date();
var year=date.getFullYear();
var month=date.getMonth();
var day=date.getDate(); // fixed
function SetDivContent() {
    var div=document.getElementById('date_dependent');
    if (year==2014 && month==00) { // fixed (the JavaScript months order is 0-11, not 1-12)
        if (day>=3 && day<29) { // the following content will be displayed 12/03/2010, 12/04/2010, [...], 12/09/2010, 12/10/2010
            div.innerHTML='content 1';
        }
        else if (day==11 || day==12) { // this one will be displayed 12/11/2010 and 12/12/2010
            div.innerHTML='content 2';
        }
        else if (day>12) { // this one - 12/13/2010 and later, until the end of December
            div.innerHTML='content 3';
        }
    }
    else if (year==2014 && month>=0) div.innerHTML='Time to start over!!!'; // OPTIONAL - just to ensure that content 3 is displayed even after December.
}
</script>

Upvotes: 1

Views: 4805

Answers (2)

Andrea Parodi
Andrea Parodi

Reputation: 5614

Assuming that your div are defined this way:

<div id="first">content 1</div>
<div id="second">content 2</div>
<div id="third">content 3</div>

You can use this CSS code to initially hide all divs:

<style>
#first,#second,#third {
    display:none;
}
</style>

and then this js code to show the appropriate one:

<script type="text/javascript">
var date=new Date();
var year=date.getFullYear();
var month=date.getMonth();
var day=date.getDate(); // fixed

function SetDivContent() {

    if (year==2014 && month==00) { 
        if (day>=3 && day<29) { 
            $("#first").css("display","block");
        }
        else if (day==11 || day==12) { 
            $("#second").css("display","block");
        }
        else if (day>12) { 
            $("#third").css("display","block");
        }
    }
    else if (year==2014 && month>=0) { 
            $("#third").css("display","block");
        }
    }
</script>

Please note that I also assume that you want to display the div as block when visible. If you need another display value, change "block" with "inline" or whatever you need.

Upvotes: 1

Skye MacMaster
Skye MacMaster

Reputation: 914

To hide a div just set the display attribute to 'none'

div.style.display = "none";

To show a div set the display attribute to 'block'

div.style.display = "block";

Upvotes: 1

Related Questions