Pages

6/16/2015

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

(Updated 11/24/17 to allow use in a Publishing page.)

This is a 2013 version of the 2007 and 2010 article found here: http://techtrainingnotes.blogspot.com/2010/10/sharepoint-create-quote-of-day-web-part.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

You could display a picture or product of the day:

image


This web part is another simple Content Query Web Part solution similar to the ones found in my SharePoint 2010 Customization book. But… this one is for 2013!

  • 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, pictures or other content that you can add to a SharePoint rich text editor column.


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 Settings (gear) and click Add an App.
  2. Find and 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.  (I.e., don't click Advanced Options and add a description!)
  5. Click Create.
  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 announcement" or New from the ITEMs ribbon. You can use all of the rich text formatting options if you like. (Bold, colors, etc.)
  8. Create a new view by clicking the Create View link in the LIST ribbon.
  9. Create the view as a Standard view and name it something like “QuoteView”. Un-checkmark all columns except for “Quote” column (the “Body” column if using an announcements list).
  10. Expand the Tabular View section (scroll down to find it) and uncheck "Allow individual item checkboxes".
  11. Click OK.

You now have the list that will store the quotes. You will now add two web parts to a page. One which is the list of quotes, and the other which is a Content Editor Web Part with the JavaScript and HTML code.


Add the Quotes list web part to the page

  1. Go to the page where you want to add the “Quote of the Day”, most likely your home page. 
  2. Click Settings (gear), Edit Page.
  3. Click where you would like to add the quotes.
  4. In the INSERT ribbon click Web Part and add the web part for the quotes list.
  5. In the web part click dropdown arrow and then Edit Web Part.
  6. Select the view you created above (“QuoteView”).
  7. Click OK.

This web part will be hidden when the JavaScript runs.


The JavaScript and HTML file

  1. Open Notepad or your favorite HTML editor.
  2. Copy the sample code from below and paste into your editor.
  3. Either delete my sample <style> block (it displays the quote in red) or customize your own style.
  4. Find the line with "var quotesWebPartName=" and change "Quotes" to your list's name.
  5. (Optional) Find the line with "var OneQuotePerVisit = false" and change it to true so the user can only see one quote per day.
  6. Save the file.
  7. Upload the file to a library where all of your users have at least Read or View access. "Site Assets" is a good choice.
  8. Find the URL of the uploaded file by clicking the "…" next to the file name. Copy the URL so we can paste it into the CEWP below.


The Content Editor Web Part

  1. Add a Content Editor Web Part (CEWP) and move it so it is near the quotes web part. While the list web part can go anywhere, the CEWP must go where you would like to display the quote of the day. 
  2. Click the CEWP’s dropdown menu and select Edit Web Part.
  3. Paste the URL you copied earlier into the Content Link box.
  4. In the Appearance section add a title for the web part (perhaps “Quote of the Day”).
  5. At the bottom of the web part properties box click OK.
  6. Save your page and test! Refresh the page to see if the quote changes.



The JavaScript

Copy and paste the following JavaScript into Notepad or your favorite HTML editor. (see above)

<!-- add your own formatting here... (optional)-->
<style type='text/css'>
  #TTNQuoteText { color:red }
</style>


<!-- Quote will be displayed here -->
<span id="TTNQuoteText"></span>



<script type="text/javascript">

function TTNShowQuote()
{
// another CEWP trick from http://TechTrainingNotes.blogspot.com
// http://techtrainingnotes.blogspot.com/2010/10/sharepoint-create-quote-of-day-web-part.html

// 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;

  var TTNTables = document.getElementsByTagName("TABLE");
  var i=0;
  for (i=0;i<TTNTables.length;i++) 
  {
    if (TTNTables[i].summary)
    {
    if (TTNTables[i].summary == quotesWebPartName)
    {
      // Get the table with the quotes
      QuoteList = TTNTables[i].getElementsByTagName("tbody")[0];

      // hide the links list web part, but only if not in edit mode
// 11/25/17 update to allow use in a Publishing page.
if ( typeof PageState == 'undefined' || (PageState.ViewModeIsEdit != "1") )
{ QuoteList.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.style.display="none"; } break; } } } if (!QuoteList) { document.getElementById("TTNQuoteText").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++; //} } if (quoteCount==0) { document.getElementById("TTNQuoteText").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.getElementById("TTNQuoteText").innerHTML= QuoteList.getElementsByTagName("TR")[QuoteArray[id]].childNodes[0].childNodes[0].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(); } } // add our function to the SharePoint OnLoad event _spBodyOnLoadFunctionNames.push("TTNShowQuote"); </script>


Only have about 100 more of these to update from 2007/2010 to 2013!



.

17 comments:

Shae said...

Hi Mike! Thanks for another great post. I was looking for something just like this and this did the trick.

Maybe I had some other javascript on the page that was interfering, but I had to make a tweak to this to get it to work on my site.

For me the javascript code hid the "stop editing" button in the ribbon, making it hard to save or edit the page. I worked around that by removing the if block following the comment "hide the links list web part, but only if not in edit mode." Then I hid the web part in question by using the layouts menu on its web part pane.

Thanks again, this was a fantastic solution!

Unknown said...

Hi Mike!

I followed your instructions, but the CEWP showed the words "undefined" instead of a rotating list of quotes :(

I double checked the webpart name and it was correct. Is there anything else we needed to do to the script to get it to work? I even tried taking the script and embedding it directly into the CEWP using the new embed code feature in 2013 and it was the same result. I'm not a coder, but I've been able to use scripts in the past from websites and blogs such as yours by cutting and pasting :)

Any help would be appreciated!

Thanks,

Jonathan

Mike Smith said...

Jonathan,

The only thing I can think of is if the web part name is capitalized correctly.

Mike

Unknown said...

Hi Mike,

I rechecked the name and retried it. Now the webpart no longer says "undefined" but still doesn't show anything from the list. Is the webpart name the only thing we have to input into your code?

Thanks!

Anonymous said...

Hello Mike,

I'm having an odd issue. Your script works great when I go into the list view Web Part (SharePoint Online) and select the view by name, but as soon as I click save, it stops working, I think because it becomes " instead of "QuoteView" I looked through the code and didn't see a reference to the view name, am I missing something or do you know a solution to this?

Thanks for helping out a JS newbie!

Mike Smith said...

Anonymous,

Part of your question around "instead of" is missing. I don't think I have enough info to help.

Mike

Baehre said...

I'm a bit of a novice but I found your information very straight forward. I tested this in my dev environment and everything looked great. I had a couple of my developers go to the dev site and they saw something completely different. They saw the list and not the quote. I'm sure it's a permission issue and since we have had issues with our dev and user accounts I thought I would try it in our production environment on another page. I received the same response back that Jonathan received 'undefined' and you could still see the list.

I'm not sure what to try next. I have repeated the steps over and over both in dev and production and get the same results on both.

Your assistance would be greatly appreciated.

Mike Smith said...

Baehre,

The fact that other users did not see the same result implies a permissions issue or a file or page that was checked out, but not checked back in.

Do your testers have read permission to the library that holds the JavaScript file, and was both the page and the file checked in?

Mike

Jody said...

Hello,

I am having the same issue as Baehre. Users who are in the owner/admin group can see it. Visitors cannot. Everything is checked in and they have read permissions to the JavaScript file. I'm stumped. Any other ideas?

Thank you!
Jody

Mike Smith said...

Jody,

Does this site have the publishing features enabled? Make sure the page is checked in and published.

The same applies to the JavaScript file. Do all of the users have at least read permissions to the file? (and is it checked in?) Go to the library with the JavaScript file, select the file, and check the permissions for the file.

Where is the JavaScript file stored? In the same library as the page?

Mike

Anonymous said...

Hi Mike,

The quote displays in the CEWP as intended when editing, but once I publish the page, the quote no longer shows in the CEWP. Am I missing something?

Mike Smith said...

Anonymous,

Are you adding this to a page in a site with the Publishing feature enabled?

If you added the JavaScript directly to the CEWP, then SharePoint may delete the code when saved. You should place the code in a Notepad file, save it to SitePages, SiteAssets, etc. and then link to it from the CEWP. If you placed this file in the Pages library, make sure that it is checked in and published.

Mike

Unknown said...

Hi Mike

I followed you instructions (Very detailed and easy to follow) and I am getting "Undefined" when I save the CEWP.

I have done the following to validate:
Publishing feature is enabled
Permissions granted to the site assets where .txt doc is
document is checked in

Is there anything I am missing?

Shaun

Mike Smith said...

Shaun,

I could not duplicate an error that resulted in "Undefined". I did find a problem with using this code with a Publishing page. After publishing a page, the quotes are simply not displayed. To fix this change the following line in the code.

from:
if ( PageState.ViewModeIsEdit != "1" )
to:
if ( typeof PageState == 'undefined' || (PageState.ViewModeIsEdit != "1") )

All I can recommend for the "Undefined" error is to copy and paste the code into Notepad again and upload the file again, just to see if anything got missed in the original copy.

Mike

Emily said...

Hello Mike,
Thank you very much to your sharing this great post, I manage to get my page working by using your guide.
by the way , can I have the quote of the day to keep changing in 10sec ? instead of when page reopen etc.
Thank you very much for your help in advance.
Hope to hear from you soon.

Regards,

Mike Smith said...

Emily,

Sorry for the late response... the blog stopped sending me emails about new posts!

You could with a little more JavaScript. Just after the "_spBodyOnLoadFunctionNames.push("TTNShowQuote");" line add "setTimeout(TTNShowQuote, 10000);"

Mike

Anonymous said...

I followed the instructions step by step, however the content editor webpart shows "Select of deselect this item" in a red font. The Announcement list remains on the page (the direction says it should disappear when the JavaScript runs). When i refresh the page, i see the quote of the day for a very few seconds & the quote of the day list webpart disappears, then it goes back to the message "Select or deselect this item". I am not sure where i went wrong, please assist.

Thank you!

Post a Comment

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.