I would like to find a snippet of code to us in page using Javascript or JQuery. the function of the code is to make text appear weekly. Like random text or random image but I would like to control the text according to the week within the year ie. week 1 text 1, week 2 text2 etc. Can anyone help?

Recommended Answers

All 12 Replies

Helban,

Try this :-

function getWeekNo(startDay, baseDate){
	var now = new Date();
	startDay = (!startDay) ? 0 : startDay;//Default to Sunday
	baseDate = (!baseDate) ? new Date(now.getYear(), 0, 1) : baseDate;//Default to 1st Jan of current year.
	if(startDay !== -1){
		while(baseDate.getDay() !== startDay){ baseDate.setTime(baseDate.getTime() - (24 * 3600 * 1000)); }
	}
	return Math.ceil((now.getTime() - baseDate.getTime())/(7 * 24 * 3600 * 1000));
}

As it depends on exactly what you mean by "week number", I have made the code flexible. The function accepts two parameters, as follows:

  • startDay : The day which should be used as the first day of each week. 0=Sunday, 1=Monday etc. Pass -1 to use the raw baseDate as week start, regardless of what day it is. Default = 0;
  • baseDate : The date to be used as the first day of the year. Default = 1st January of the current year.

Sample calls:

var weekNo = getWeekNo();//Conventional week numbering based on calender year, each week starting on Sunaday.
var weekNo = getWeekNo(1);//Conventional week numbering based on calender year, each week starting on Monday.
showWeekNo( 6, new Date(new Date().getYear(), 3, 1) );//Week number of UK corporate fiscal year (1 April to 31 March), starting on Saturday (as used by some companies).

I've done some rudimtary testing and for some reason it waits untill 1:00 am on the first day of each week to throw a new week number, rather than the 00:00 (midnight) as you would expect. I can't immediately see why this should be. The rest of the time it seems to behave properly.

Please don't use my function in anything safety/financially/etc. critical.

For text, just set up an array of strings :-

var txtArray = [];
txtArray[1] = 'On no, back to work, I\'m still a bit hung over';
txtArray[2] = 'These dark nights are getting to me';
txtArray[3] = 'Brrrr, had to scrape ice off my bicycle saddle this morning';
txtArray[n] = 'xxxxxxx';
txtArray[52] = 'Oh no, it\'s the Midwinter Retail Festival!';
txtArray[53] = 'New year is upon us again';

Then index into this array with the week number returned by getWeekNo() . eg.

weekMessage = txtArray[getWeekNo()];

Airshow

Thank you so much for your code. I have not made it work successfully which could be due to my lack of javascript knowledge. Here is how I have embedded it within my page so far (txt Array reduced for this emai only), perhaps you could point you where I have gone wrong - many thanks:

<SCRIPT language="Javascript"><!--  
  function getWeekNo(startDay, baseDate){
	var now = new Date();
	startDay = (!startDay) ? 0 : startDay;//Default to Sunday
	baseDate = (!baseDate) ? new Date(now.getYear(), 0, 1) : baseDate;//Default to 1st Jan of current year.
	if(startDay !== -1){
		while(baseDate.getDay() !== startDay){ baseDate.setTime(baseDate.getTime() - (24 * 3600 * 1000)); }
	}
	return Math.ceil((now.getTime() - baseDate.getTime())/(7 * 24 * 3600 * 1000));
}
var txtArray=[53];
txtArray[1]='On no, back to work, I\'m still a bit hung over';
txtArray[2]='These dark nights are getting to me';
txtArray[3]='Brrrr, had to scrape ice off my bicycle saddle this morning';
txtArray[4]='Text week 4';
txtArray[5]='Text week 5';
txtArray[6]='Text week 6';
txtArray[7]='Text week 7';
txtArray[n]='Text week n;
txtArray[37]='Text week 37';
txtArray[38]='Text week 38';
txtArray[39]='Text week 39';
txtArray[40]='Text week 40';
txtArray[41]='Text week 41';
txtArray[42]='Text week 42';
txtArray[43]='Text week 43';
txtArray[44]='Text week 44';
txtArray[45]='Text week 45';
txtArray[46]='Text week 46';
txtArray[47]='Text week 47';
txtArray[48]='Text week 48';
txtArray[49]='Text week 49';
txtArray[50]='Text week 50';
txtArray[51]='Text week 51';
txtArray[52]='Oh no, it\'s the Midwinter Retail Festival!';
txtArray[53]='New year is upon us again';
 
var weekMessage=txtArray[getWeekNo()]
document.write(weekMessage + ' ');
   //-->
   </SCRIPT>

Helban, you're nearly there.

First get rid of my line txtArray[n]='Text week n; , which is just pseudo-code.

It's better not to use document.write if you can avoid it. Do it this way instead :-

<body>
<div id="divExample"></div>
<p>******* <span id="spanExample"></span> *******.</p>
</body>
onload = function(){
	var weekMessage = txtArray[getWeekNo()];
	var ex_1 = document.getElementById('divExample');
	var ex_2 = document.getElementById('spanExample');
	if(ex_1){ ex_1.innerHTML = weekMessage; }
	if(ex_2){ ex_2.innerHTML = weekMessage; }
}

This allows the HTML to load quickly so the browser can start to render it. Javascript functions then follow on and fill in the gaps. It takes a bit of getting used to but you'll grow to love it.

The code above creates an anonymous function that fires when the page has loaded. It sniffs out two elements in your html then pokes weekMessage into them.

This is just an example to show that you can poke data into both block-elements (div in this case) and inline-elements (span in this case). You will do just one of these and give the chosen html element an id that reflects its purpose (eg id="weekMessage" ).

Airshow

Hi Airshow, you have amazing patience with a novice.

Unfortunately, although I am sure it is superb, I cant follow what you said. I already have a body onload on that page so dont know if I can do two. Also although you have written snippets for me I am still not sure how to implement them with the page. For instance, I am not sure what the Span class is supposed to contain. I am also not sure where I would put the 'script Javascript' bit of the code. Is there a way of showing me a complete example within a dummy page and then I can copy it.

By the way the txtArray [n] was just to shortcut in the post and I have used the full 53 in the test I did.

Many thanks Airshow

Regards
Helban

I already have a body onload on that page so dont know if I can do two.

You can add the lines of code from my onload function above or below the lines within your existing onload function.
For example:

onload = function(){
	//existing lines of code
	//existing lines of code
	//existing lines of code
	var weekMessage = txtArray[getWeekNo()];
	var ex_1 = document.getElementById('divExample');
	var ex_2 = document.getElementById('spanExample');
	if(ex_1){ ex_1.innerHTML = weekMessage; }
	if(ex_2){ ex_2.innerHTML = weekMessage; }
}

Typically it will not matter whether you add above or below, but you have to be careful in case one block of code affects or is dependant on the other.

For instance, I am not sure what the Span class is supposed to contain.

SPAN is just a general purpose HTML inline element, in the same way that DIV is a general purpose HTML block element. SPAN can be used to style a portion of a string, or (as we want here) to allow us to address it in javascript. You can read more about div and span here.

I am also not sure where I would put the 'script Javascript' bit of the code.

In a well modern, written web page, all javascript will be in the document's HEAD. You will find many web pages in which javascript appears in the document's BODY however, without exception, anything that needs to be performed in javascript can be performed by code in the HEAD with the BODY free to contain (X)HTML (or other markup language).

Is there a way of showing me a complete example within a dummy page and then I can copy it.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Airshow :: Week Number Calculation</title>

<style type="text/css">
body { font-family:verdana,helvetica,sans-serif; font-size:10pt; }
#weekMessageContainer { width:200px; border:1px solid #006699; }
#weekMessageContainer h1 { margin:0; padding:10px 0; background-color:#006699; color:white; font-size:12pt; text-align:center; }
#divExample { padding:5px; text-align:center; }
#weekMessage { font-size:11pt; }
#spanExample { color:#006699; text-decoration:underline; }
</style>

<script>
var txtArray = [];
for(var i=1; i<=53; i++){
	txtArray[i] = "This is Week No. " + i;
}
function getWeekNo(startDay, baseDate){
	var now = new Date();
	startDay = (!startDay) ? 0 : ParseInt(startDay);//Default to Sunday
	baseDate = (!baseDate || baseDate.constructor !== Date) ? new Date(now.getYear(), 0, 1) : baseDate;//Default to 1st Jan of current year.
	if(startDay !== -1){
		while(baseDate.getDay() !== startDay){ baseDate.setTime(baseDate.getTime() - (24 * 3600 * 1000)); }
	}
	return Math.ceil((now.getTime() - baseDate.getTime())/(7 * 24 * 3600 * 1000));
}

onload = function(){
	var weekMessage = txtArray[getWeekNo()];
	var ex_1 = document.getElementById('divExample');
	var ex_2 = document.getElementById('spanExample');
	if(ex_1){ ex_1.innerHTML = weekMessage; }
	if(ex_2){ ex_2.innerHTML = weekMessage; }
}
</script>
</head>

<body>

<div id="weekMessageContainer">
	<h1>Div Example</h1>
	<div id="divExample"></div>
</div>

<p id="weekMessage">Span example: <span id="spanExample"></span>.</p>

</body>
</html>

By the way the txtArray [n] was just to shortcut in the post and I have used the full 53 in the test I did.

Understood.
You will see above that I have done something slightly different. The array is populated in a loop (for the purpose of the demonstration).

Airshow

Dear Airshow

I wanted to thank you for your help a couple of weeks ago with Javascript. Unfortunately I got the week message to work with the last instructions but using it with onload threw out all my other javascript and code including a keyword search so could not risk using it.

I think if I had stuck to the first stages and got them in the right order it might have been ok. It was a good idea for the site I am making but beyond me to install it. I think you have alot of patience.

Thank you all the same.
Helban

Helban,

If you want, post a whole page here and I will try to understand what's going wrong for you. It's probably something simple.

Airshow

This is my page. You will see I already have some Javascript and an onload instruction for a keywords search (php). It is the keyword search that is thrown out if I add another onload instruction.

If you can help with not too much effort I would be very grateful.

Many thanks
Helban

[<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"><!-- InstanceBegin template="/Templates/homepage_temp.dwt" codeOutsideHTMLIsLocked="false" -->
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="description" content="Shalom Ministries information site for Jewish people explaining that Jesus is the Messiah, with stories by Jews and rabbis"/>
<meta name="keywords" content="Jews, Jewish, Judaism, Outreach, Israel, Torah, Talmud, Sidra, Rabbis, Messiah, Messianic, Shalom, Peace, Religion, Missionary, Gospel, Bible"/>
<!-- InstanceBeginEditable name="doctitle" -->
<title>Shalom Ministries, Home Page</title>
<!-- InstanceEndEditable -->
<link href="styles/SMpagestyle.css" rel="stylesheet" type="text/css" />
<link href="styles/SMnavstyles.css" rel="stylesheet" type="text/css" />
<link href="styles/SMsearchstyles.css" rel="stylesheet" type="text/css" />

<!-- InstanceBeginEditable name="head" -->
<!-- InstanceEndEditable -->

</head>

<body onload="if (document.getElementById('zoom_searchbox')) {document.getElementById('zoom_searchbox').focus();}" >
<a name="top" id="top"></a>

<div id="container">
<div id="banner"></div>

  <div id="datetabs">
<div id="datebox"><script language="JavaScript1.2" type="text/javascript">
  var months=new Array(13);
  months[1]="January";
  months[2]="February";
  months[3]="March";
  months[4]="April";
  months[5]="May";
  months[6]="June";
  months[7]="July";
  months[8]="August";
  months[9]="September";
  months[10]="October";
  months[11]="November";
  months[12]="December";
  var time=new Date();
  var lmonth=months[time.getMonth() + 1];
  var date=time.getDate();
  var year=time.getYear();
  if (year < 2000)
  year = year + 1900;
  document.write(date + " ");
  document.write(lmonth + " " + year);
// End --></script></div>
<!--ZOOMSTOP-->

<div id="tabtop1">
  <div id="tabbox"><a href="index.html">Home</a></div>
  <div id="tabbox"><a href="content/contactus.html">Contact</a></div>
  <div id="tabbox"> <a href="shop/books.html">Shop</a></div>
</div>
<!-- InstanceBeginEditable name="Noentry1" -->  <!-- InstanceEndEditable -->
<!--ZOOMRESTART--></div>
    <div id="mainpage">
    <div id="searchmaincont">
         <div id="searchcont"> <div id="wordsearchbox"><form action="http://www.shalom.org.uk/newsite/search/search.php" method="GET"><span class="keywordleft">Keyword:</span><input type="text" name="zoom_query" class="input1" /><input type="submit" name="zoom_button" class="button2" value="Search" alt="Go" /></form></div>
  </div>
  </div>
  <div id="leftcol"><!--ZOOMSTOP-->
      <div id="navcont">
        <div id="nav">
          <ul>
         <li> <a href="content/news.html">News</a></li>
            <li> <a href="content/events.html">Events</a></li>
            <li> <a href="library/library.html">Library</a></li>
            <li> <a href="content/downloads.html">Downloads</a></li>
            <li> <a href="content/relatedsites.html">Related Sites</a></li>
           </ul>
        </div>
        <!-- InstanceBeginEditable name="Noentry2" --><!-- InstanceEndEditable -->
      </div><!--ZOOMRESTART-->
  </div>
  <div id="rightcol"><!-- InstanceBeginEditable name="pagetext" -->  
  <div id="pagetext">    
  <h6>Welcome to the website   of Shalom   Ministries </h6>
  <p>We are a group of Jews and Gentiles who have come to believe that Jesus   of Nazareth is the Messiah of Israel and Saviour of the world. Through Jesus, or   Yeshua, we enjoy the blessings of the New Covenant that God promised to the   house of Israel and the house of Judah. Through him, God's Torah has been   written on our hearts, our sins have been forgiven and we know the God of   Avraham, Yitzak and Ya'acov as our God and Father.
  </p>
  <p>We welcome your   comments and interaction.</p>
  <p> </p>
  <h1>Light from the Sidra</h1>
  <p> </p>
  <p>Weekly text to go here.........</p>


  </div>

  <!-- InstanceEndEditable --></div>
  <div id="clearpage"> </div>
  <!--ZOOMSTOP--><div id="backtonav"> <!-- InstanceBeginEditable name="backtonav" -->
  <div id="backtop"><span class="arrow">∧</span> <a href="#top"> Back to top</a></div>

  <!-- InstanceEndEditable --></div>
  <div id="clearpage"> </div>
  <br /><!--ZOOMRESTART-->
</div>

<!--ZOOMSTOP--><div id="bottombar">
© <script language="JavaScript1.2" type="text/javascript">
  var year=time.getYear();
  if (year < 2000)
  year = year + 1900;
  document.write(" " + year);
// End --></script> 
Shalom Ministries      <span class="title">•</span>    <a href="mailto:email: [email]comms@shalom.org.uk[/email]?subject=Query from www.shalom.org.uk">email: [email]comms@shalom.org.uk[/email]</a>        <span class="title">•</span>    <a href="content/sitemap.html">site map</a><br />
We do not necessarily endorse the contents of this site.
    </div><!--ZOOMRESTART-->

</div>
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
try {
var pageTracker = _gat._getTracker("UA-10982662-2");
pageTracker._trackPageview();
} catch(err) {}</script>
</body>
<!-- InstanceEnd --></html>]

Helban,

Try this :

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"><!-- InstanceBegin template="/Templates/homepage_temp.dwt" codeOutsideHTMLIsLocked="false" -->
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="description" content="Shalom Ministries information site for Jewish people explaining that Jesus is the Messiah, with stories by Jews and rabbis"/>
<meta name="keywords" content="Jews, Jewish, Judaism, Outreach, Israel, Torah, Talmud, Sidra, Rabbis, Messiah, Messianic, Shalom, Peace, Religion, Missionary, Gospel, Bible"/>
<!-- InstanceBeginEditable name="doctitle" -->
<title>Shalom Ministries, Home Page</title>
<!-- InstanceEndEditable -->
<style>
ul.inline {
	list-style-type: none;
	margin:0;
	padding:0;
	font-size:9pt;
}
ul.inline li {
	display: inline;
	padding: 0 9px;
	border-left: 1px solid #333;
}
ul.inline li.first {
	padding-left: 0;
	border-left-width: 0;
}
</style>
<link href="styles/SMpagestyle.css" rel="stylesheet" type="text/css" />
<link href="styles/SMnavstyles.css" rel="stylesheet" type="text/css" />
<link href="styles/SMsearchstyles.css" rel="stylesheet" type="text/css" />
<!-- InstanceBeginEditable name="head" -->
<!-- InstanceEndEditable -->
<script language="JavaScript1.2" type="text/javascript">
onload = function(){
	var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
	var time = new Date();
	year = (time.getYear() < 2000) ? (time.getYear() + 1900) : time.getYear();
	var el =  document.getElementById('date');
	if(el){ el.innerHTML = time.getDate() + " " + months[time.getMonth() + 1] + " " + year; }
	var el2 = document.getElementById('c_year');
	if(el2){ el2.innerHTML = year; }
	var el3 = document.getElementById('zoom_searchbox');
	if(el3){ el3.focus(); }

	var getWeekNo = function(startDay, baseDate){
		var now = new Date();
		startDay = (!startDay) ? 0 : startDay;//Default to Sunday
		baseDate = (!baseDate) ? new Date(now.getYear(), 0, 1) : baseDate;//Default to 1st Jan of current year.
		if(startDay !== -1){
			while(baseDate.getDay() !== startDay){ baseDate.setTime(baseDate.getTime() - (24 * 3600 * 1000)); }
		}
		return Math.ceil((now.getTime() - baseDate.getTime())/(7 * 24 * 3600 * 1000));
	};
	var txtArray = [];
	// ******* Replacve this line to provide one message per week (hard coded). *******
	for(var i=0; i<53; i++){ txtArray.push('This is week number ' + i); }
	// ******* **************************************************************** *******
	var el4 = document.getElementById('weekMessage');
	if(el4) { el4.innerHTML = txtArray[getWeekNo()]; }
}
</script>
</head>

<body>
<a name="top" id="top"></a>
<div id="container">
  <div id="banner"></div>
  <div id="datetabs">
    <div id="datebox"><span id="date"></span></div>
	<!--ZOOMSTOP-->
    <div id="tabtop1">
      <div id="tabbox"><a href="index.html">Home</a></div>
      <div id="tabbox"><a href="content/contactus.html">Contact</a></div>
      <div id="tabbox"> <a href="shop/books.html">Shop</a></div>
    </div>
<!-- InstanceBeginEditable name="Noentry1" --> <!-- InstanceEndEditable -->
<!--ZOOMRESTART--></div>
  <div id="mainpage">
    <div id="searchmaincont">
      <div id="searchcont">
        <div id="wordsearchbox"><form action="http://www.shalom.org.uk/newsite/search/search.php" method="GET"><span class="keywordleft">Keyword:</span><input type="text" name="zoom_query" class="input1" /><input type="submit" name="zoom_button" class="button2" value="Search" alt="Go" /></form></div>
      </div>
    </div>
    <div id="leftcol"><!--ZOOMSTOP-->
      <div id="navcont">
        <div id="nav">
          <ul>
          <li><a href="content/news.html">News</a></li>
          <li><a href="content/events.html">Events</a></li>
          <li><a href="library/library.html">Library</a></li>
          <li><a href="content/downloads.html">Downloads</a></li>
          <li><a href="content/relatedsites.html">Related Sites</a></li>
          </ul>
        </div>
        <!-- InstanceBeginEditable name="Noentry2" --><!-- InstanceEndEditable -->
      </div><!--ZOOMRESTART-->
    </div>
    <div id="rightcol"><!-- InstanceBeginEditable name="pagetext" -->
      <div id="pagetext">
        <h6>Welcome to the website of Shalom Ministries </h6>
        <p>We are a group of Jews and Gentiles who have come to believe that Jesus of Nazareth is the Messiah of Israel and Saviour of the world. Through Jesus, or Yeshua, we enjoy the blessings of the New Covenant that God promised to the house of Israel and the house of Judah. Through him, God's Torah has been written on our hearts, our sins have been forgiven and we know the God of Avraham, Yitzak and Ya'acov as our God and Father.</p>
        <p>We welcome your comments and interaction.</p>
        <h1>Light from the Sidra</h1>
        <p>Message of the week : <span id="weekMessage"></span></p>
      </div>
      <!-- InstanceEndEditable --></div>
    <div id="clearpage"> </div>
    <!--ZOOMSTOP--><div id="backtonav"> <!-- InstanceBeginEditable name="backtonav" -->
      <div id="backtop"><span class="arrow">&and;</span>&nbsp;<a href="#top">Back to top</a></div>
    <!-- InstanceEndEditable --></div>
      <div id="clearpage"> </div>
      <!--ZOOMRESTART-->
    </div>
    <!--ZOOMSTOP--><div id="bottombar" style="margin-top:1.5em;">
      <ul class="inline">
        <li class="first">&copy;&nbsp;<span id="c_year"></span>&nbsp;Shalom Ministries</li>
        <li><a href="mailto:comms@shalom.org.uk?subject=Query from www.shalom.org.uk">email: comms@shalom.org.uk</a></li>
        <li><a href="content/sitemap.html">site map</a></li>
      </ul>
      We do not necessarily endorse the contents of this site.
    </div><!--ZOOMRESTART-->
</div>
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
try {
  var pageTracker = _gat._getTracker("UA-10982662-2");
  pageTracker._trackPageview();
}
catch(err) {}
</script>
</body><!-- InstanceEnd -->
</html>

As you will see, I have installed your weekly text and otherwise tidied the page up quite a lot. In particualr :

  • Moved most of the embedded javascript out of the html and put it in the header (in a function that will run when the page has loaded).
  • Purged all <br>s as a means of controlling vertical spacing (almost nothing drives me more nuts!)
  • Converted a rather messy "bottombar" to a nice clean inline list (with a handful of css directives in the head).

You can style up the weekly message as you wish in css and can adopt as many of my ideas or discard as you see fit.

Hope it helps.

Airshow

should have named that anonymous onload function since the beginning...

if(!this.addEventListener){
attachEvent('onload', namedFunction)} 
else {addEventListener('load', namedFunction, 0)}

Regards

Thank you very much Airshow for all your hard work. I am unable to get anything working now on the page so am calling it a day and will stick with manual entries for the weekly message and revert to the original code.

I have learnt a lot from you and your tips (the bits I understand!) especially when you tidied up my code.

Really appreciate all your help.

Helban

Helban,

Try changing the line:

baseDate = (!baseDate) ? new Date(now.getYear(), 0, 1) : baseDate;//Default to 1st Jan of current year.

to

baseDate = (!baseDate) ? new Date(now.getFullYear(), 0, 1) : baseDate;//Default to 1st Jan of current year.

My mistake, I forgot about .getFullYear(); which is necessary for cross-browser compatibility.

Apart from that you may need to adjust your css where I might have overtidied the HTML. Or, selectively revert to your original HTML.

Tested this time in IE6, FF 3.5.5 and Opera 9.01

If this doesn't work then I will call it a day too.

Airshow

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.