locked
Content Editor Issue RRS feed

  • Question

  • I tried Javascript in Content Editor inside Sharepoint 2010 and encountered some issues. For example, I have this code which prints out today's date.

    <script language="JavaScript">
    <!-- Hide content from non Javascript browsers
     var Today  = new Date();
     var ThisDay = Today.getDate();
     var ThisMonth  = Today.getMonth() + 1;
     var ThisYear  = Today.getFullYear();
     var DaysLeft;
     var DayName = Today.getDate();
     document.write("Today is " + ThisMonth + "/" + ThisDay + "/" + ThisYear + "<br>");
     // End of hiding JavaScript code from old browsers --></script>

    First time, it works fine and it prints today's date. The issue arises when you try to edit the page. Each time you try to edit the page, today's date is displayed as many number of times.

    For example, the content editor displays after 2 page edits
    Today is 2/10/2010
    Today is 2/10/2010
    Today is 2/10/2010

    And if I look at the HTML source, it is as follows.
    <script language="JavaScript">
    <!-- Hide content from non Javascript browsers
     var Today  = new Date();
     var ThisDay = Today.getDate();
     var ThisMonth  = Today.getMonth() + 1;
     var ThisYear  = Today.getFullYear();
     var DaysLeft;
     var DayName = Today.getDate();
     document.write("Today is " + ThisMonth + "/" + ThisDay + "/" + ThisYear + "<br>");
     // End of hiding JavaScript code from old browsers --></script>Today is 2/10/2010<br/>Today is 2/10/2010<br/>Today is 2/10/2010<br/>

    Wednesday, February 10, 2010 3:37 PM

Answers

  • I think the issue you are having here is that the javascript you inserted is getting executed in a few different places.

    Specifically, when you close the "edit source HTML" dialog, the CEWP is re-rendered with your changes (which includes printing "Today is XX/XX/XXXX"). But because you are still in Edit Web Part mode, when the javascript runs it prints that text *inside the Content Editor Web Part Rich Text Editor*). So now, when you save the web part, you are saving "Today is XX/XX/XXXX" in text along with your javascript. When you view the page in View mode, Javascript appends "Today is XX/XX/XXXX" to it.

    So, you'll need to be really careful each time you close the edit Source HTML dialog to DELETE the text that Javascript prints into the Rich Text Editor before saving the web part.

    Suggested:
    Edit Source HTML > Add your javascript > click "OK"
    Delete "Today is XX/XX/XXXX" from RTE > click "OK" in Web Part Tool Pane (or if you are on a Web Parts Page, click "Stop Editing" in the Ribbon Page Tab)
    Thursday, February 11, 2010 9:47 PM