10/26/2010

SharePoint: Create a Quote of the Day Web Part (a CEWP trick!)

 

Note: The following works for both SharePoint 2007 and 2010.

The 2013 version of this can be found here: http://techtrainingnotes.blogspot.com/2015/06/sharepoint-2013-create-quote-of-day-web.html

 

Quote of the Day / Tip of the Day

Want to display some “wise words” for your coworkers? You need a Quote of the Day web part!

image

 

This web part is another simple Content Query Web Part solution.

  • Works from a normal SharePoint list
  • Displays a random quote from the list
  • Can display a new quote on each page view, or just one new quote a day
  • Can be used to display quotes, product announcements or any kind of text
  • Uses a Rich Text field so you can include formatting

Create the Quotes list

While you could use a Custom List, I used an Announcements list as it already had what I needed, a Title field and a Rich Text field.

  1. Go to Site Actions, Create
  2. Click Announcements
  3. Add a name for the list such as “Quotes”
  4. The description is optional, but is best left blank as it adds a little complication later on
  5. Click OK
  6. If you are not using the Announcements list type then from the list’s Settings menu click Create Column and add a “Multiple Lines of Text” column. Name the column “Quote” (although any name will work) and click “Rich text (Bold, italics, text alignment)
  7. Add a few quotes by clicking New
    image
  8. Create a new view by clicking the “View:” dropdown and click Create View
  9. Create the view as a Standard view and name it something like “Web Part View”. Un-checkmark all columns except for “Quote” column (the “Body” column if using an announcements list)
  10. In 2010, expand the Tabular View section and uncheckmark "Allow individual item checkboxes"
  11. Click OK

 

 

Add the Quotes list web part to the page

  1. Go to the page where you want to add the “Quote of the Day”
  2. Click Site Actions, Edit Page
  3. Click add a web part and add the web part for the quotes list
  4. In the web part click Edit and Modify Shared Web Part
  5. Select the view you created above (“Web Part View”)
  6. Click OK

image

 

The Content Editor Web Part

  1. Add a Content Editor Web Part (CEWP) and move it so it is below the quotes web part 
  2. Click the CEWP’s dropdown menu and select Modify Shared Web Part
  3. In the Appearance section add a title for the web part (perhaps “Quote of the Day”)
  4. Now you have two choices:
    • Click the Source Editor button and copy and paste the JavaScript that you will find later in this article
                    or (good idea for 2007 and the best practice for 2010!)
    • Create the JavaScript in your favorite HTML editor (Visual Studio, SharePoint Designer, Notepad, etc), upload it to a library and enter the path to the file in the Content Editor Web Part’s  “Content Link” box.

      This second choice is preferred for a few reasons:
      • You can use your editor’s Intellisense, copy and paste,  and other features to help write the code
      • You can write the code and upload to a library once, then use it in multiple Content Editor Web Parts   (…edit in one place…update in many…)
      • Easier to backup, share with other site owners and document

 

ID’ing your Web Part

To write JavaScript to interact with the HTML of a web part you need to indentify the web part’s HTML. SharePoint’s web parts have a custom attribute named “title”.  This title consists of two parts: the title entered in the Appearance section of the web part’s properties and the description entered in the list’s “Title, Description and Navigation” settings. Note that when you have a description, the title attribute includes a “-“ as separator.

Examples:

Web Part Title List Description HTML “title”
Quotes none entered Quotes
Quotes Cool words of wisdom Quotes - Cool words of wisdom
     

So how do you find it, just to make sure…

Display the SharePoint page with the list’s web part (probably your site’s home page), use the browser’s “View Source” feature (In IE 6 click the View menu, then click Source) and search for the name of the web part. What you are looking for should be something like this:

  image_thumb9

Or like this if there is no list description:

  image_thumb10

 

The JavaScript

Copy and paste the following JavaScript into your Content Editor Web Part. (see the two options described above)

 

<!-- add your own formatting here... -->

<span name="QuoteText" id="QuoteText"></span>



<script>
// another CEWP trick from http://TechTrainingNotes.blogspot.com
//
// name of the quotes library web part
var quotesWebPartName="Quotes"; 
//
// set this to "true" so the user will see the same quote 
// for 12 hours or until they close and reopen the browser
var OneQuotePerVisit = false;

// don't change these
var QuoteList;
var QuoteArray = [];
var quoteCount = 0;


  //Find the quotes web part and hide it
  var x = document.getElementsByTagName("TD"); // find all of the table cells

  var i=0;
  for (i=0;i<x.length;i++) 
  {
    if (x[i].title == quotesWebPartName)
    {
      // tables in tables in tables... ah SharePoint!
      QuoteList = x[i].parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode;

      // hide the links list web part
      QuoteList.style.display="none"; 
      break;
    } 
  }

  if (!QuoteList)
  {
    document.all("QuoteText").innerHTML="Web Part '" + quotesWebPartName + "' not found!";
  }

  //Count the quotes

  var links = QuoteList.getElementsByTagName("TR") // find all of the rows
  var url;
  var quoteCount = 0;
  for (i=0;i<links.length;i++) 
  {
    
    if (links[i].childNodes[0].className=="ms-vb2")
    {
      QuoteArray[quoteCount] = i; 
      quoteCount++;
//alert("quotes " + links[i].childNodes[0].innerHTML)

    }
  }
  
  if (quoteCount==0)
  {
    document.all("QuoteText").innerHTML="No quotes found in web part '" + quotesWebPartName + "'!";
  }

  var id=-1;

  // check for a cookie and use last ID if found

  if (OneQuotePerVisit)
  {
    // check for a cookie with the last quote ID
    if (document.cookie.length>0)
    {
    c_start=document.cookie.indexOf("LastQuoteDisplayedID=");
    if (c_start!=-1)
      {
      c_start=c_start + "LastQuoteDisplayedID".length+1;
      c_end=document.cookie.indexOf(";",c_start);
      if (c_end==-1) c_end=document.cookie.length;
      id = unescape(document.cookie.substring(c_start,c_end));
      }
    }
  }

  if (id == -1) 
  { 
    // generate a random quote ID
    id = Math.floor(Math.random() * QuoteArray.length) 
  }

  // display the quote
  document.all("QuoteText").innerHTML= QuoteList.getElementsByTagName("TR")[QuoteArray[id]].childNodes[0].innerHTML;

  if (OneQuotePerVisit)
  {
    // set a cookie so they see the same quote for xx hours (.5 = 1/2 day = 12 hours)
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + 1);
    document.cookie="LastQuoteDisplayedID=" + id //+ ";expires=" + exdate.toUTCString();
  }

</script>

 

.

39 comments:

Anonymous said...

Is there a way to have more than one Quote of the day web part on a page? When I put two on there, text is only visible in one. Thanks!

Mike Smith said...

> more than one Quote of the day web part on a page?

Yes, just add multiple SPAN tags, each with it's own ID: "QuoteText2", "QuoteText3", etc.

Then add a copy of the script for each Quote web part, each edited with the unique web part name and the SPAN name.

Mike

Anonymous said...

Brilliant!!! works most excellently, thanks!!!

Eyespiral said...

Hi Mike,

I've book looking for this for ages! Thank you.

When I paste in the script & update the title to match my web part ("Tips") and click OK, the random tip displays correctly on my edit page. However, when I exit edit mode, the list comes back and my CEWP displays the text "Web Part 'Tips' not found!" Do you have any idea why I am running into this problem?

Mike Smith said...

Eyespiral,

Most likely you have set the Chrome to the Tips web part as "None".

Mike

Eyespiral said...

Thanks for the advice Mike.

Now I am trying to recreate this on another site collection, I can not get anything to display. I think it may be something to do with the document.all code, but I am unsure. We are operating on IE8.

It's very strange because the original page I made using your script still works, but if I create an identical one even on another web part page in the SAME site collection, I get an apparently blank condent editor web part.

Sorry to saddle this on you, but can you shed any light? Thanks!

Mike Smith said...

Eyespiral,

Try replacing the document.all("QuoteText") with document.getElementById("QuoteText").
document.all is for "older IE" browsers.

Mike

TS said...

Same problem as Eyespiral has had. Works only in Edit mode. Any advises?

Mike Smith said...

TS,

Questions:

Are hiding the title (Chrome)?

Does your SharePoint have Service Pack 1 installed?

Did you make any changes to the code?

Mike
P.s. there is an updated version of this project in my book.

I want to be MacGyver when I grow up. said...

Got your code working just fine but I'd like to have it as a random question and answer. Suggestions?
Thanks.

Mike Smith said...

MacGyver,

Set OneQuotePerVisit to false. That should make them random on each page request.

Mike

David Styles said...

thanks for a very useful post Mike. just a follow on from your comment on regarding document.getElementById versus document.all() - document all has been deprecated in Firefox 6 so no longer works.

Mike Smith said...

David,

I don't document.all has ever worked in Firefox, has it? The example above was created in a SP2007 environment where all of the users had IE6, so I got away with an old bad habit.

Just as an FYI, all of the samples in my book have been updated and tested with Firefox and newer IE versions.

Mike

Rodrigo Pessanha Chiesa said...

Great Post MAN!

Rebecca said...

In what format do you add formatting to the start of the Quotes script?
I am displaying an image, title and byline for my tip of the day webpart. Currently the image is at the top, the title is on the next line and then the byline starts immediately after the heading on the same line. What I'm after is the image on the left beside the text, with the title on the first line, and the byline beginning on the next line down. Similar to your quote of the day but with a picture immediately to the left of the text.

What code would I need to include for this to happen.

Thanks so much, great web part.

Rebecca said...

In what format do you add formatting to the start of the Quotes script?
I am displaying an image, title and byline for my tip of the day webpart. Currently the image is at the top, the title is on the next line and then the byline starts immediately after the heading on the same line. What I'm after is the image on the left beside the text, with the title on the first line, and the byline beginning on the next line down. Similar to your quote of the day but with a picture immediately to the left of the text.

What code would I need to include for this to happen.

Thanks so much, great web part.

Susan Ant said...

Hi Mike, that's was an awesome post!

Now, I've got the idea instead of update per day, change per week.

Could I use your same code and make just some mini modifications to achieve it ?
Do you have any suggestion ?

Thank you so much

Mike Smith said...

Susan,

You could make it weekly by changing the "check for a cookie" section of the code to store a second cookie with a date and checking to see if the date was more than a week ago.

Mike

CRJAngel said...

I am getting "no Quotes found in the web part (webpartname) any ideas why I am getting this? SP 2010 being used.

Mike Smith said...

CRJAngel,

Most likely issues:

1) The web part name / title is not correct
var quotesWebPartName="Quotes";

2) The first column of your view is something like an attachments column. It should be the Title column.

Mike

Anonymous said...

Hey Mike. This is a follow up to a question I posted just the other day. I was looking for a way to have all members of my team see the same quote each day all day. Well ... I figured out the solution without using any JavaScript at all. All you have to do is have a Date column that has the date you want to display the quote. So you'd have one date per quote in the future. In the view you use to display the quote that only has the one column being displayed, set the filter of the view where the column Display Date is Equal To [Today]. [Today] is the current date. That's it. Just one List View Web Part and I'm all set. I would not have worked thru to that point without your blog post here. I admire your JavaScript solution very much. Thanks for posting.

John said...

Hi. The script is identifying the Quotes web part but not finding the quotes therein -- I'm getting the same "No quotes found in the web part" message as CRJAngel, above. I have removed the attachments column in the Quotes announcements list. Can you think of anything esle it might be?

Mike Smith said...

John,

Anything special about your list?

Replace each occurance of document.all with document.getElementById to work with more modern browsers.

It won't work at all with groups and will need to be customized to work with certain styles and counts/sums.

Otherwise, make sure you count every column, including the checkbox an attachment columns. Remember the first column is column 0.

Check to see if you have the title correct. It may have extra spaces or text.

Mike

Becky said...

It's really kind of you to provide this information! I was just able to add a "Quotes that Inspire Us" section to our department's SharePoint site. Thank you very much.

Mr.Million said...

Is there a way to have it show youtube videos here?

Mr.Million said...

Is there a way to have it show you tube videos?

Mike Smith said...

Mr. Million,

Not as designed. It only selects the text from a list item and displays it.

But... With some work the JavaScript could grab a URL from the list and set it as the source of an IFRAME. Sorry, but I don't have an example of this.

Mike

Tim Roberts said...

Mike, The code works great. Is there a limit to the number of quotes you can randomize with this script? I've a pretty big list (2,500) and I seem to be getting a lot of the same quotes.

Thanks

-Tim

Tim Roberts said...

Mike, The code works great. Thanks.

Is there a limitation to the number of quotes you can randomize with this script? I've ~2,500 quotes and I am seeing a lot of the same quotes already. I've only had the script running on the site for a couple of days.

Thanks

Mike Smith said...

Tim,

No limitation, but it will only display what is in the web part's view. So if the web part by default only displays the first 20 items, then that's all that will be seen by the JavaScript.

Mike

Tim Roberts said...

Mike, That worked, but I discovered randomizing ~2500 quotes was not a wise idea :-) Slows the system down a bit too much.

Mike Smith said...

Tim,

2500 is a LOT of quotes! Maybe each month copy 100 or so into a list to be used for the Quote of the Day for the month.

Another interesting possibility would be to take a pure JavaScript/code approach. Make two web service calls, one to get the count of items in the quotes list and a second to pick one item using a JavaScript generated random number. (Not too complicated, but I don't have time right now to put together an example. I will add it to my todo list.)

Mike

Shae said...

Does this work with SharePoint 2013? It didn't for me, but I could be doing something wrong. Thought I'd ask before going too crazy with the troubleshooting.

Napster said...

I would also like to know if this works in SharePoint 2013. I used it on SP 2010 and it worked fine, but in 2013 it gives me the error "Web Part 'Web Part Name' not found!"

Robert said...

Hi Mike, i was wondering the same for SPF 2013 ? Nice work by the way:)

Louis.ani84 said...

Hi Can we use an external source for the quotes instead of an announcement list

Ben Coleman said...

Our company just moved to SP2013 .. and it does not seem to work there (migrated whole site!). Is there something we need to tweak?

Mike Smith said...

Ben and anyone else looking for 2013 version...

I have a 2013 version and will try to get it posted in the next day or two.

Mike

Mike Smith said...

The 2013 version of this article can be found here:
http://techtrainingnotes.blogspot.com/2015/06/sharepoint-2013-create-quote-of-day-web.html

Mike

Note to spammers!

Spammers, don't waste your time... all posts are moderated. If your comment includes unrelated links, is advertising, or just pure spam, it will never be seen.