SharePoint and JavaScript CSOM

I'm relizing that I'm spending too much time googling the same topics over and over (on JavaScript programming), so I list here a few solution I need in a recurrent way.

 

JavaScript: how understand if page is opened in iFrame, and get its url

 

Javascript: how get url parameters

  • function to get query string parameters:
    function getURLParameter(name) {
    return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null
    }
  • source: How to get URL parameters with Javascript?

 

Javascript: function to format numbers

 

Javascript: function to format date-times

 

Javascript: how html encode strings

 

jQuery: how write a custom filter method

jQuery: creating extensions

When developing with jQuery, I often need to verify selectors, so I usually write something like this:

$('my selector').css('background-color', 'red');

To save some typing, I wanted to create a jQuery extension so I have followed the tutorial Writing Your Own jQuery Plugins and here is my extension:

(function($) {

   // This function makes the background color red (used for debug)
   $.fn.red = function() {
      this.each(function() {
         $(this).css('background-color', 'red');
      });
   };

   // This function alerts the length of the collection items (used for debug)
   $.fn.alertLength = function() {
      alert($(this).length);
   };

   // This function alerts each item in the collection (used for debug)
   $.fn.foreachAlert = function() {
      this.each(function(index, value) {
         alert('' + index + ': ' + value);
      });
   };

 }(jQuery));

SharePoint: getTagFromIdentifierAndTitle

When developing in SharePoint using the client-script object model, for sure you have met the function getTagFromIdentifierAndTitle, proposed by Microsoft and copied in many websites.

The basic implementation can be found in many websites, and the article Tags and Identifiers for getTagFromIdentifierAndTitle Function is only one of many examples.

 

But this function doesn't handle choice fields displayed as radio buttons.

So I have found another other implementation in the blog post Trigger JavaScript Events When a Choice (Radio Button) SharePoint Field Type is Clicked.

Regions in Notepad++

While editing JavaScript files with Notepad++, I have noticed that like in Visual Studio there is the nice feature to collapse function methods.

But so I thought, how to implement the "regions" that I can define in C# files?

 

I have found a nice trick in one of the answers at the question notepad++ user defined regions with folding: simply add a comment and then the opening and closure brackets.

In my example it could be:

  • ///////////////////////////////////////////////////////////////////////{ BEGIN of my region
  • ///////////////////////////////////////////////////////////////////////} END of my region