none
Embedding javascript function in a basic web part for SharePoint 2010

    Question

  • Hello,

    New SharePoint developer here finally getting some experience with "Hello World!" web parts.

    I had a question about the next step in the piece I was training on, which is to add a live ticking clock to a basic web part.

    The clock I built with a javascript tutorial that works pretty well, and luckily is pretty simple.

    <script type="text/javascript">
    <!--
        function updateClock() {
            var currentTime = new Date();
            var currentHours = currentTime.getHours();
            var currentMinutes = currentTime.getMinutes();
            var currentSeconds = currentTime.getSeconds();
            currentMinutes = (currentMinutes < 10 ? "0" : "") + currentMinutes;
            currentSeconds = (currentSeconds < 10 ? "0" : "") + currentSeconds;
            var timeOfDay = (currentHours < 12) ? "AM" : "PM";
            currentHours = (currentHours > 12) ? currentHours - 12 : currentHours;
            currentHours = (currentHours == 0) ? 12 : currentHours;
            var currentTimeString = currentHours + ":" + currentMinutes + ":" + currentSeconds + " " + timeOfDay;
            document.getElementById("clock").firstChild.nodeValue = currentTimeString;
        }
    // -->
    </script>
    <body onload="updateClock(); setInterval('updateClock()', 1000 )">
    <span id="clock">&nbsp;</span>
    </body>

    .. I have to figure out a way to embed this script in a basic webpart (currently not a visual webpart) so it can display the clock just by adding the webpart to a page, instead of calling on a separate .js file.

    The super basic web part code is here:

    using System;
    using System.ComponentModel;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using Microsoft.SharePoint;
    using Microsoft.SharePoint.WebControls;
    namespace Sample.DisplayMessage.DisplayMessageWebpart
    {
      [ToolboxItemAttribute(false)]
      public class DisplayMessageWebpart:WebPart
       {
        private string customMessage = "Hello, world!";
        [WebBrowsable(true),
        WebDescription("Displays a custom message"),
        WebDisplayName("Display Message"),
        Personalizable(PersonalizationScope.User)]
        public string DisplayMessage
       {
         get { return customMessage; }
         set { customMessage = value; }
       }
        protected override void CreateChildControls()
        {
         base.CreateChildControls();
         LiteralControl message = new LiteralControl();
         message.Text = DisplayMessage;
         Controls.Add(message);
        }
      }
    }

    I have visited tutorials I have found from searching the web, so far they are a bit confusing as I see some code.. but not code being implemented on a C# page similiar to mine, or I see it done in a "Visual" web part instead, whereas I need to see it done in a basic web part.

    Does anyone have a moment to offer insight and direction on this issue? (no other .NET mentor-types in my shop right now, self-teaching)

    Thursday, April 12, 2012 5:22 PM

All replies

  • You can use the ASP.NET script manager to register javascript code on the page. The script manager is included on every page in SharePoint, because it is included in the standard master pages.

    This sample code should give you an idea about how to integrate it in the web part.

    protected override void CreateChildControls()
        {
            string script = @"
            function ToggleItem(id)
              {
                var elem = $get('div'+id);
                if (elem) 
                {
                  if (elem.style.display != 'block') 
                  {
                    elem.style.display = 'block';
                    elem.style.visibility = 'visible';
                  } 
                  else
                  {
                    elem.style.display = 'none';
                    elem.style.visibility = 'hidden';
                  }
                }
              }
            ";
    
            ScriptManager.RegisterClientScriptBlock(
                this,
                typeof(Page),
                "ToggleScript",
                script,
                true);
        }


    http://msdn.microsoft.com/en-us/library/bb350750(v=vs.90).aspx


    SharePoint Developer | @zeemanj | Blog

    • Marked as answer by Marcus.B Thursday, April 12, 2012 7:01 PM
    • Unmarked as answer by Marcus.B Monday, April 16, 2012 8:38 PM
    Thursday, April 12, 2012 6:16 PM
  • Thank you very much, this helps a lot!
    Thursday, April 12, 2012 7:02 PM
  • Ok, I was hoping to revive this thread a bit without creating a new one.

    After following the advice here and doing more studying.  I decided to go the route of "Visual Web Part" instead of "basic" web part.

    I plugged in the Javascript code in the .ascx portion of the webpart and am having troubles making it display as it would on any other html page.

    I understand that I'm probably missing some code behind or certain markup probably doesn't work on a visual web part, as they are different animals.

    Does anyone have a good tutorial out there or any insight in to my issue?  I'm sorry for the simple questions but I'm doing a LOT of self teaching and net searching..

    Monday, April 16, 2012 8:38 PM
  • That is the way to go in my opinion. A visual webpart, you can add your javascript right into the .ascx file. 

    Using this method you can create standard webpart properties in the .cs file and retrieve them in your javascript code.

    Like for example this piece of javascript in my .ascx file 

                jQuery(document).ready(function() {
                    $(".BandrVideoPlayerScroll").jCarouselLite({
                        btnNext: "#BandRVideoPlayer .next",
                        btnPrev: "#BandRVideoPlayer .prev",
                        visible: <%= Convert.ToInt32(WebPart.NumberOfItems)  %>
                    });
    
                });

    in the .ascx.cs  codebehind i reference the webpart like so

            public VideoPlayer WebPart { get; set; }
    
            protected void Page_Load(object sender, EventArgs e)
            {
                this.WebPart = this.Parent as VideoPlayer;
    }
    

    And that connects to the videoplayer.cs file

    private string _numberOfItems = "3";
    
            [System.Web.UI.WebControls.WebParts.WebBrowsable(true),
            System.Web.UI.WebControls.WebParts.WebDisplayName("Number of Items"),
            System.Web.UI.WebControls.WebParts.WebDescription(""),
            System.Web.UI.WebControls.WebParts.Personalizable(
            System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared),
            System.ComponentModel.Category("Configuration"),
            System.ComponentModel.DefaultValue("")]
            public string NumberOfItems
            {
                get { return _numberOfItems; }
                set { _numberOfItems = value; }
            }


    -tom daly

    Tuesday, April 17, 2012 2:39 AM
  • Thanks a lot Tom!

    This also really gets me going in the right direction, I really appreciate it!

    If I have some javascript to display a ticking clock, which I can place in the .ascx, any recommendations to display it?

    <script type="text/javascript">
    <!--
        function updateClock() {
            var currentTime = new Date();
            var currentHours = currentTime.getHours();
            var currentMinutes = currentTime.getMinutes();
            var currentSeconds = currentTime.getSeconds();
    currentMinutes = (currentMinutes < 10 ? "0" : "") + currentMinutes;
    currentSeconds = (currentSeconds < 10 ? "0" : "") + currentSeconds;
    var timeOfDay = (currentHours < 12) ? "AM" : "PM";
    currentHours = (currentHours > 12) ? 
    currentHours - 12 : currentHours;
    currentHours = (currentHours == 0) ? 12 : currentHours;
         
    var currentTimeString = currentHours + ":" + currentMinutes + ":" + currentSeconds + " " + timeOfDay;
    document.getElementById("clock").firstChild.nodeValue = currentTimeString;
        }
    // -->
    </script>

    I tried using a <span id="clock"> and filling it in, but that didn't quite work..  I hope they hire an experienced SP developer in my shop soon. 
    • Edited by Marcus.B Tuesday, April 17, 2012 2:18 PM
    Tuesday, April 17, 2012 2:01 PM