A while ago I needed a script to update some content every week, and my question was answered in this forum.
--
Now, and I'm not a jQuery pro like you :), but the "problem" I have is that today (the moment of this post) it's week #52 but the script wasn't working, it wasn't showing the content for week #52, so I changed my HTML to week #53, and it worked.
The "problem" is that there's no week #53, so I'm afraid I'm going to have to change my HTML to continue counting for week #54, #56, #57 and so on, when those weeks don't exist.
Here's an extract of the HTML (the structure repeats over the weeks, content changes of course):
<div class="quotes-container quote-53">
<div class="quote">Quote here...</div>
<div class="author">— Author </div>
</div>
Script:
<script type="text/javascript">
Date.prototype.getWeek = function() {
var onejan = new Date(this.getFullYear(),0,1);
return Math.ceil((((this - onejan) / 86400000) + onejan.getDay()+1)/7);
}
jQuery(function(){
var today = new Date();
var weekno = today.getWeek();
jQuery('#quotes-wrapper').load('/common/testimonials.html div.quote-'+weekno);
});
</script>
Any idea what's going on?
Thanks a lot for any help on this.
EDIT: The script you're using considers a "week" to be Sunday - Saturday. Since a year doesn't always start on a Sunday, it considers the first partial week to be week 1.
If you simply want 7 say periods since the first of the year, use the script below. If you want it based on Sunday, then the script you're using would be correct.
There is a week #53
. It's just not a full week.
But we are in week 52
. I'm guessing the current script doesn't account for leap years.
Instead you can calculate the day of this year, and divide that by 7.
Example: http://jsfiddle.net/etTS2/2/
<script type="text/javascript">
Date.prototype.getWeek = function() {
var onejan = new Date(this.getFullYear(),0,1);
var today = new Date(this.getFullYear(),this.getMonth(),this.getDate());
var dayOfYear = ((today - onejan +1)/86400000);
return Math.ceil(dayOfYear/7)
};
jQuery(function(){
var today = new Date();
var weekno = today.getWeek();
jQuery('#quotes-wrapper').load('/common/testimonials.html div.quote-'+weekno);
});
</script>
You'll still get a result of 53
on the last day of the year (or last two days in a leap year).
EDIT: Fixed a offset of 1
on the dayOfYear
.