Below you will find pages that utilize the taxonomy term “javascript”
Posts
MagicMirror2 and Chuvash
This post is about my setup of the popular MagicMirror2 application. I show the steps needed to set it up on a Raspberry Pi Zero W and connect it to a TV set. As a bonus, I share my thoughts on the Chuvash localization work.
MagicMirror2 is a DIY project and an open-source application, voted to number one of the best Raspberry Pi Projects. In essence, it shows information of your choice (weather, calendar, news) on a screen that is embedded in a mirror.
Posts
Filtering Azure Table Data directly in the Azure Function Binding
Instead of filtering values from an Azure Storage Table, you can do it directly in the bindings. It might not be a solution for everything, but in the right place, it is fantastic. I was very surprised to see how little code was needed after this binding change:
For that to work, define the filter attribute in the bindings: “filter”: “(PartitionKey eq ‘{package}’)”
To try it out, add a new row in a table defined in the bindings (“metadata” in my case):
Posts
Update Field.JSLink using JSOM or REST
Today I have just a little code snippet to share. This code snippet shows how to update the JSLink property for an existing field using JSOM and REST. For REST I use sharepoint-utilities. [code language=“javascript”] var updateJsLinkCsom = function(config) { var ctx = SP.ClientContext.get_current(); var web = ctx.get_web(); var lists = web.get_lists(); var list = lists.getByTitle(config.listTitle) var fields = list.get_fields(); var field = fields.getByInternalNameOrTitle(config.fieldTitle) field.set_jsLink(config.jsLink) field.update() ctx.executeQueryAsync() }; var updateJsLinkRest = function(config) { SP.
Posts
Trigger SP2010 Workflows using JSOM
Today I found out how to start workflows in JSOM (JavaScript Object Model in SharePoint). Nothing special, but since it is not documented, it took me a while to find a solution. Here is the code which I want to keep as simple as possible. What you need to start a SP2010 Workflow for a list item or a document in JSOM, you need to load SP.WorkflowServices.js and you need to create the manager and get the service, then you can trigger a workflow using the workflow name, the list guid and the guid of the list item: [code language=“javascript”] var ctx = SP.
Posts
Create and download a file in javascript
Phew, I spent a lot of time to get this to work:
Create a text based file in javascript - a simple csv or txt Download a file in Chrome and Internet Explorer Make Excel understand Unicode characters (å ä ö and many more) in csv directly. I found many solutions on the Internet that I used to find out a solution that works for me A deep diving jsfiddle about unicode encodings, bom, line endings: http://jsfiddle.
Posts
Minimal Download Strategy. Simple
There are many correct ways (1, 2, 3, 4, 5…) of making scripts work with the Minimal Download Strategy Feature (MDS) in SharePoint 2013 and 2016. But to be honest - every time I need it, I get confused. So now it is time to find a simple solution for that. Who is better at it than the developers of the SharePoint themselves? Look at the MDS code in the built-in Display Templates: Let’s keep it as simple as Item_Default.
Posts
Minimal Display Template
We want to use our own Display Templates on Non-publishing sites - our team sites. Without the Publishing Feature activated you have to create an own javascript file. Here is short and concise instructions how to install it: Display Templates on Non-publishing Sites. As described on that blog, you can make copy of an existing Item_Default.js and adjust to your needs. I also asked Elio Struyf and I got the same tip.
Posts
SharePoint Utilities - a promising JavaScript Framework
My colleagues at Bool have developed a new JavaScript framework for SharePoint - sharepoint utilities. It started on our DevDay last year - a whole free day when we could learn new things, try out new techniques or build something that was not even requested from a customer. I was not working on sharepoint utilities, so I almost forgot it until… I recently re-discovered sharepoint utilities. It is on Github, it is MIT licensed and contributions are welcome.
Posts
A tiny tool for User Custom Actions
Everybody loves User Custom Actions in SharePoint. That’s the only recommended way of customizing SharePoint. You have heard about it. Unfortunately there is no convinient way of administering them. People have their console applications or powershell scripts to add, update and delete user custom actions. It works but it is hard to open up Visual Studio or PowerShell every time you will try out an idea on a test site.
Posts
Copy SharePoint WebDav Address to Clipboard
While configuring SharePoint sites and helping users I often use File Explorer View for editing pages, resources like css and javascript. In IE there is a dedicated button in the ribbon for that. Sometimes it works, sometimes it doesn’t, because of permissions or other restrictions. Anyway, I use Firefox and Chrome while troubleshooting and developing, so I have created a bookmarklet for copying the webdav address of a site that is open in the browser.
Posts
Export Any Web Part using a Bookmarklet
My blog post about exporting any webpart from a SharePoint Page is one of the most read articles on my blog. I use this method a lot. Now what I want to do is to simplify the process. Inspired by my colleague Dan Saedén’s awesome bookmarklet for reading and updating web properties, I decided to make my own bookmarklet. That was easy. Now we can export any web part from any SharePoint page without even looking at any ids in the html markup and assembling the export url manually.
Posts
Bypass all custom jslink
Client Side Rendering (CSR) and jslink are great for customizing lists and forms in SharePoint. In my current project we use it a lot of it. A disadvantage of that path, although, is that it might occur javascript errors, during the development phase, but also in production. We do, of course, our best to leverage the best jslink code, but unfortunately we have to live with the fact that errors can occur, especially when we use it for NewForm, EditForm, DisplayForm and View (in list and grid).
Posts
Client Side Rendering with Async dependencies
Yesterday I asked a question on SharePoint StackExchange:
Client Side Rendering with Async dependencies I also asked Elio Struyf on Twitter: https://twitter.com/eliostruyf/status/540473976255152128 Good idea, Elio Struyf! Now I want to try it out.
Preparations In this case I’ll be using my example from my blog post yesterday: Drag and Drop Image using Client Side Rendering I have created a new list and added a lookup field to my previous list. What I get is a Title of the lookup item, but not my custom field called DragAndDrop.
Posts
Drag and Drop Image using Client Side Rendering
I continue my series about Client Side Rendering (CSR) and jsgrid. Today I want to try a custom field where users can drag and drop images. The inspiration comes from:
AutoUpload field written by Anton Vishnyakov and Base64 Drag and drop written by oroboto What I want to achieve is:
A custom field that is rendered with jslink Users can drag and drop small pictures (thumbnails) into the field A base64 image representation is saved as the field value Optionally implement pasting images using Clipboard API Step 1 Create a field with a custom jslink Create a field of type Note.
Posts
Disabling a column in Quick Edit
In my project I have a column called Request Status. This column is not shown in any forms, meaning users should not edit, because it is controlled through the app. Nevertheless it is editable in the Quick Edit. Yesterday I wrote about jsgrid in my blog. Now comes more. Today I’ll share a little practical solution how one can disable editing a field in Quick Edit. The field is edited in jsgrid, but to disable it, we only have set the property called AllowGridEditing to false on our column (not even touching the heavy jsgrid api).
Posts
JSGrid Basics
JSGrid is the javascript framework in SharePoint used in Quick Edit View (previously Datasheet View). There are a few very good blog posts on this topic (See below in “Sources”). Nevertheless the fact is that jsgrid and working with quick edit from a developer’s perspective is a huge undiscovered area. Articles I have seen are intended for advanced developers. The goal with my post today is to outline the very basics of working with JSGrid.
Posts
Improving the web performance of an intranet
[caption id=“attachment_3437” align=“alignnone” width=“480”] All the “small” app parts, web parts, delegate controls, user controls, and other “packages” that “must” be delivered to the users on every page load of the Start Page of your Intranet.[/caption] Recently we made an investment to improve the performance of our intranet. We made many changes in different layers: SQL, Network, Browser upgrade and code. Here I want to tell about what code changes we did to improve the web browser performance.
Posts
AppLoader Concept for SharePoint apps
In this post I want to share an unusual, nevertheless interesting conceptual idea of loading content from SharePoint 2013 apps on many pages. The original awesome concept was proposed and developed by my colleague Martin Villysson at Bool.
The problem we are trying to solve SharePoint apps are great to extend functionality in SharePoint and integrate other systems (full page apps available through Site Contents), they also provide tools to enrich the default SharePoint experience by App Parts (Client Web Parts) and Custom Actions (additional menus).
Posts
Using CAML with SharePoint REST API
Do you prefer REST over CSOM as I do? I’ll skip the whys. Andrew Connell put it already in wrtiting so nicely. Well, if you do prefer REST, then you must have discovered some shortcomings of REST, or its incompleteness compared to CSOM. I think of:
Inability to filter items based on multivalued taxonomy fields Inability to filter items based on user fields where user is added through a group, rather than directly, e.
Posts
Pragmatic Responsive Design
I have been curious about the responsive design but have not had time to try it out. To learn more I decided to make an existing website more responsive. A friend of mine drives a Chuvash Dictionary website: samah.chv.su. Today it looks like this in a mobile browser: The site is a classic 1000px-ish centered page with header and two columns. The left column is for the main content and the right column for additional “aside” information.
Posts
Count lines of code with PowerShell
Today I got a question:
How many lines of code are there in our SharePoint solution?
After a little search, I found that PowerShell is really a nice tool to count lines of code:
How do you count lines of code (stackoverflow)? I wanted to count lines for different types of code:
Code Behind written in C#, the files have .cs file extension JavaScript code (except jQuery, angular or knockout frameworks) PowerShell files (.
Posts
Debugging OOB SharePoint. Unable to post comments on SharePoint blogs (SP2013 June CU)
I have had a strange bug. The comment text box in a OOB SharePoint 2013 blog doesn’t appear. It only says: “There are no comments for this post.” In this blog post I’ll tell you how I found the bug and I’ll show you how you can temporarily bring the commenting to life. I have had luck. While it doesn’t work on the Test Environment, it does actually work on my development machine.
Posts
Log to ULS using javascript
The more javascript code is produced in SharePoint solutions, the more need we have to log information and possible errors to a central logging place in SharePoint: ULS. This blog post is about logging to ULS from javascript. For a while ago I read a blog post:
5 suggestions to implement a better logging in SharePoint The author @avishnyakov mentions the ability log to ULS from javascript. I want to dive deeper.
Posts
javascript: Alert Me on a Page
Recently I needed to add an Alert Me link on Pages. Alert Me is a well known SharePoint functionality for notifying users about changes in list or list items. It is availabe in OOB SharePoint as a command in Ribbon if you go to a list view: When you click on this ribbon command, SharePoint opens a modal dialog and takes you to layouts page: SubNew.aspx. To open a modal dialog and load a page is not a rocket science.
Posts
javascript: Remove illegal characters in url
Recently I needed to create valid urls for pages using javascript. Also this time I thought it must be some out-of-the-box code for that in SharePoint. The first thing I came up was the “Add page” dialog. I found that the actual dialog was in the _layouts virtual folder:
/\_layouts/15/CreatePublishingPageDialog.aspx ```Bingo, it does the validation in the client side. This is the responsible javascript function that resides directly in the page: \[sourcecode language="javascript"\] function UpdateUrl() { LoadTermContextInfo(); var hiddenPageUrlLabelExtensionClientId = "<%=hiddenPageUrlLabelExtension.
Posts
The CDN concept in SharePoint
How many instances of jquery are there in your SharePoint farm? [sourcecode language=“powershell”] Get-SPWebApplication http://dev ` | Select -Expand Sites ` | Select -Expand AllWebs ` | Select -Expand Lists ` | Select -Expand Items ` | ? { $_.Url -match “jquery.*.js” } ` | select Name, Url [/sourcecode] Have you more than two (jquery and jquery-ui), then you have too much. You can save much place and performance by using Content Delivery Network (CDN) links for the resources like javascript, css, fonts and icons.
Posts
Convert any web app to a SharePoint app
Have you noticed that you can right-click a web application project in Visual Studio and convert it to a provider hosted app? Well why not? Basically your own website and a SharePoint manifest is all what you need for a provider hosted app. This discovery today made me think about all legacy web apps out there that can be converted to SharePoint apps. Traditionally we had to add plain links to external applications or embed them into an IFrame by hardcoding it in an .
Posts
SharePoint Apps: "Provider Hosted First" Approach
Recently I had an exciting mail conversation with Thomas Deutsch. He came up with an idea how to fasten the development of apps. This smart approach is called “Provider Hosted First”. See Thomas’ original blog post. Here are some highlights: What you actually do is a local website which runs in grunt server:
localhost:9000 ```Then a SharePoint-hosted app is created with an SPAppIframe that refers to that local app site.
Posts
Make javascript code work with Minimal Download Strategy Part 2
I have a newer blog post about MDS, that provides a much simpler solution. Please check it before reading further.
Minimal Download Strategy (MDS) is an important feature in SharePoint 2013. It lets you download only a page delta, only changes. There is still issues with the MDS and custom scripts and almost no documentation on msdn or technet. In this blog post I want to learn more about adjusting custom scripts for MDS.
Posts
Make javascript code work with Minimal Download Strategy Part 1
I have a newer blog post about MDS, that provides a much simpler solution. Please check it before reading further.
This is a part 1 of the blog post about Minimal Download Strategy and javascript adjustments for user code. What I initially thought should be enough for one post, is not enough, so I see it as a part 1. I wrote this post after I had read Chris O’Brien’s post about JSLink Here I want investigate how we can get his accordion list view working with MDS.
Posts
REST API: Add a plain text file as an attachment to a list item
SharePoint 2013 REST API has been enhanced and extended. The old _vti_bin/listdata.svc is still there, but the new api for working with lists and list items is much more and obviously a part of a bigger api: _api/web/lists Yesterday I saw an interesting question on SharePoint StackExchange:
“500: Internal Server Error” when trying to add a simple text file as an attachment via SharePoint 2013 REST API The instructions in the MSDN resource are not so detailed, the cannot be.
Posts
SharePoint Modal Dialog as AngularJS directive
It has already become a series of posts in my blog about the combination of AngularJS and SharePoint:
AngularJS: prevent form validation in Page Edit Mode angular jQuery UI autocomplete AngularJS: sync $location.search with an input value And it will be more. Some of them are a pure angular stuff, some of them are really for SharePoint. In this post post I’ll show how to create a directive for a sharepoint modal dialog (SP.
Posts
JavaScript Localization in SharePoint
Yesterday Waldek Mastykarz published a cool post: Globalizing JavaScript in SharePoint 2013. This is a very cool technique to localize your client code in javascript and reuse your resx files in Server Side and Client Side. This is actually not new for SharePoint 2013 despite it has become more needed with the huge client focus in the new SharePoint. I have used this in SharePoint 2010 for a long time. In my blog post: ScriptResx.
Posts
AngularJS: prevent form validation in Page Edit Mode
I work on a cool project where AngularJS is used for rendering of business data in a SharePoint portal. One of the beautiful parts of AngularJS is the client validation. AngularJS understands the new html5 attributes like “required” and pattern, which makes the markup and javascript concise and semantic. Recently I ran into a problem: The SharePoint webparts which had html forms with required fields were impossible to add to a page in the web browser, neither was it possible to edit the pages with these webparts.
Posts
angular jQuery UI autocomplete
Angular JS is one of the most developed MVC frameworks in the javascript world. Angular UI is a huge UI-centric extension of AngularJS (it is more or less like jQuery UI to the jQuery). It uses much jQuery UI and Twitter Bootstrap and provides many own components like modal dialogs, maps, tooltips, masked inputs and much more. And all this is easy to implement in your code just by adding a directive: [sourcecode language=“html”][/sourcecode] Much cleaner than listening on $(document).
Posts
javascript: show only a part of a long string (ellipsis)
Ellipsis (…) is a character which indicates that the content is to wide. There are many solutions to truncate the text and show an ellipsis: in javascript and css. I want to share my humble function which extends the String.prototype: [sourcecode language=“javascript”]String.prototype.ellipsize = function(maxLength) { maxLength = maxLength || 100; if (this.length <= maxLength) { return this; } var text = this.toString().replace(/[\r\n]/g, “”), max = maxLength, min = maxLength - 20, elipsized, tryExtract = function () { var regex = new RegExp("^.
Posts
Cool presentation about web performance optimization
by Chris Love [slideshare id=15218139&doc=webperformanceoptimizationformodernwebapplications-121116224847-phpapp01]
Posts
AngularJS: sync $location.search with an input value
I have used AngularJS for a while and to me this seems to be the best MVC javascript framework. Today I wanted to implement a search which uses an input and a hash query string like in google. The input value and url have to be synced like:
index.html#?term=something To do this we have to inject $location into our angular control. See the Angular Guide about $location. Then we have to observe both the $scope.
Posts
Determine if Silverlight is installed (javascript)
For a while ago I needed to provide an alternative solution when Silverlight isn’t installed. I searched for javascript code for this and found this:
A blog post about that: Piotr Puszkiewicz’s Silverlight Blog. Determining if Silverlight is installed using Javascript. A more advanced javascript function which can even determine the version of the Silerlight can be pulled from Silverlight.js library. I didn’t need to determine the version of Silverlight, so I wrote a simplified js function (but it works in all browsers): [sourcecode language=“javascript”] var isSilverlightInstalled = function() { var installed = false; try { installed = !
Posts
JSOM: Alter a column's DisplayName
Here is another article in my JSOM series. For one month ago I showed how to alter a column’s ShowInDisplayForm property with JSOM. This time I’ll show a code sample for changing a column’s (field’s) display name. If you want to alter the displayname with Server Object Model, grab the code in the sharepoint.stackexchange.com: Change Field’s DisplayName in a List. [sourcecode language=“javascript”]var ctx = SP.ClientContext.get_current(), //SP.ClientContext field = ctx.get_web() //SP.Web .
Posts
Delete all list items with jsom
Today I needed to “clean” a list, meaning to remove all list items. For some time ago I wrote a post about different ways of removing list items in bulk: Server Object Model, SPLinq and RPC. This time I had only the web browser. So I tried the jsom way. By the way, the javascript documentation for jsom on msdn is getting really good. Don’t miss that: How to: Complete basic operations using JavaScript library code in SharePoint 2013.
Posts
TypeScript in SharePoint
By now TypeScript shouldn’t be something one has to introduce.
TypeScript is a typed superset of JavaScript that compiles to plain JavaScript.
If you haven’t already done it, go and see the intro video for TypeScript, check out a tutorial and visit the typescript playground. There are other javascript libraries which extend javascript and are compatible/compile to javascript: Dart and CoffeeScript. To be honest I had never time to try those.
Posts
GeoLocation Field in SharePoint 2013
In SharePoint 2013 Preview there is a new type of field: GeoLocation which is, like the old SPUrlField, a pair of values. The geolocation is described as longitude and latitude. Unfortunately you can’t add this field in list settings. You have to create this in code. In the provided link you can find the code C# code which uses the Client Object Model. In another link you can find an example how to create the geolocation file using Server Object Model (in FeatureActivated EventReceiver).
Posts
Callouts in SharePoint 2013 Preview
While ModalDialog is not default for editing list items in SharePoint 2013 Preview, there is a new “popup” element in SharePoint - callout or popover. I would like to recommend these two blogs when you want discover more: Andrey Markeev: Callouts (popovers) в SharePoint 2013 Preview (in Russian) Alex Boev: a three part series: 1. Custom Callouts in the SharePoint 2013 Metro UI: Part 1: Basics 2. Custom Callouts in the SharePoint 2013 Metro UI, Part 2: Actions 3.
Posts
Masked Inputs
Just a quick tip today. If you are looking after masked inputs like the old ASP.NET Ajax Control Toolkit MaskedEdit, you can try jQuery plugin called Masked Input from DigitalBush or even better jquery.inputmask.
Posts
Paging with JSOM
If there are many list items you try retrieve with javascript object model,paging could be very useful. Today I came across a wonderful blog post series about javascript object model in SharePoint: The SharePoint javascript object model - Resources and Real World Examples posted by David Mann and published on Aptilon Blog. There is an example how to achieve paging with JSOM. The key is items.get_listItemCollectionPosition() and query.set_listItemCollectionPosition() I have refactored David’s example to avoid global variables and to put into a module.
Posts
Simplify js and css development with Web Essentials (Visual Studio Extension)
If you develop much javascript and css, this is the exension to Visual Studio you just can’t live without: Web Essentials (It is even released for VS2012). You can do many things with it. Here are two examples for simple but very useful functions: 1. Show which browsers support a css attribute: 2. Collapse javascript functions and create #region areas like in C# code: There is much more, like less and coffeescript parsing.
Posts
Toastr.js and SharePoint
Have you used SharePoint javascript Notifications (SP.UI.Notify)? Are you looking for something new and fresh? Well then check out the Toastr.js - a simple, beautiful, fully responsive and light-weight javascript lib for notifications, developed by John Papa and Hans Fjällemark and released under the MIT License. By the way, toastr was one of many things I discovered and learned on John Papa’s online course by pluralsight: Single Page Apps with HTML5, Web API, Knockout and jQuery.
Posts
Multiple events listeners in jQuery
Maybe it is not so often we face this situation where we one event handler for different events in javascript. But in my project I use many custom events and in some situations it is the same handler which listens to different events. What I found you can define multiple event listeners at the same time.
function myClick() { console.log("tada"); } $(".selector").on({ "click mouseover": myClick });
Posts
JSOM: Alter a column's ShowInDisplayForm property
When you create a content type, you can define if your fields will be shown in DisplayForm, EditForm, NewForm. You can hide or show them, just as Yaroslav Pentsarsky says. If your list is already provisioned, you can change them with Server Object Model, why not in PowerShell: Technet: Setting ShowInDisplayForm, ShowInEditForm, ShowInNewForm properties with powershell. If you don’t have access to the server, then the same can be done with JSOM.
Posts
JSOM: Last Modified Date of a List
The data transfer between server and client can heavily affect the performance. One of the measures to reduce the amount data transferred from the server to the client is storing data on the client. In many modern browsers we can use html5 localStorage. Even in older browsers there are ways to store data. I would recommend a nice js lib called amplify.js. The interface is much easier, then:
amplify.store("key", { title: "value" }); ```It comes in nicely, if we have much data which we get with JSOM.
Posts
Using SharePoint tooltips
I found a great post about using sharepoint tooltips on Andrey Markeev’s (@amarkeev, omlin) blog: JavaScript ToolTip’ы для SharePoint. He describes how he found the standard sharepoint tooltips and how they can be reused. The best part of it his “research”. Andrey’s conclusion is to create an own, simplified javascript class which enables “sharepoint” tooltips. I modified it somewhat. I think there is no need to instantiate a TooltipManager…
var Takana = window.
Posts
Chuvash localization of moment.js
For three months ago I added Chuvash localization of moment.js. For 16 days ago moment.js 1.7.0 was officially released which included the Chuvash translation.
Wait a sec… What is moment.js? moment.js is the best datetime tool for javascript. It supports many languages (now even Chuvash) for displaying date and time. Another very handy functionality is showing relative time which has a simple interface: fromNow(). Here is a simple example from a web browser console:
Posts
Chuvash translation of Wikipedia Mobile
The official Wikipedia mobile app is now translated into Chuvash language and available to use: What does Chuvash mean? I am Chuvash. Chuvash is the name of an ethnicity which counts up to 2 milions peoply (mostly in Russia). Chuvashes talk the Chuvash language which is also an official language in Chuvash Republic (besides Russian). Chuvash language is a Turkic language and has a status “Vulnerable” in the UNESCO list of languages in danger.
Posts
Multiple instances of javascript webparts on the same page
Javascript has become popular among many SharePoint developers thanks to easy and fast jQuery, CSOM, SPServices and many other javascript libraries. That can make solutions modern and fast. On the other hand developers should be aware of more things (some of them at Bamboo Team Blog). One of those is scoping of javascript webparts. The problem a developer has to consider: what happens if a user creates two or more instances of the same beautiful webpart on the page?
Posts
Three ways to get the id of last created SPListItem
An interesting question came on SharePoint StackExchange: How to retrieve the guid of the last uploaded file. It is only possible in CSOM as far as I know. But if we simplify the task, how to get the id of the last item, the we can compare three ways of getting them: SPServices, jQuery + listdata.svc and CSOM.
SPServices The most easiest way, but not available in async:
$().SPServices.SPGetLastItemId({ listName: "Documents" }); listdata.
Posts
Web Application Properties as JSON
I saw an interesting question on sharepoint.stackexchange: How to access a Web application/Farm level property bag via jQuery/Javascript/ClientContext. Some time ago I tested a custom http handler, so I wanted to try a custom httphandler for this as well. It worked. Here more details: Just deploy sp-lend-id.tupsam from the solution. If you don’t have any properties in your web application, just add some:
asnp microsoft.sharepoint.powershell $app = get-spwebapplication http://dev $app.Properties.Add("Santa", "Claus") $app.
Posts
Using javascript objects passed from closed popup
It is not a rocket science to pass objects from child window (popup) to main window. The problem I encountered today was IE and passing complex objects. So it is just an IE issue as far as I know. The problem occurs when you pass some object (not a simple String or Number) to main window:
window.opener.takeAnObjectFromChild = { title: "Should even be available when I close the child" }; and you then close the child window, next time the main window tries to access the passed object:
Posts
javascript: developing for performance
Many words have been said about the importance of performance when working with javascript files. Here I want to summarize what developers can do to increase the performance related to javascript. I found many tips on blogs. Here comes my aggregated list of actions one can do to speed up sharepoint (and not only) sites with focus on javascript:
1. Load only sharepoint stuff you need Use prefetch option to only load sharepoint javascript files that needed.
Posts
nodeunit and SharePoint: unit tests in javascript
nodeunit is a (relatively) new test framework for javascript, mainly for node, but it can be run in a browser as well. The most popular framework for testing javascript is Qunit, but I’ll lab with it another time. I found nodeunit tests in moment.js - the best date handling framework for javascript and it worked very well. So first of all, why should we test? The best answer is actually: Life is to short for manual testing (it was actually the slogan at the Google London Test Automation Conference 2007.
Posts
$ in cmssitemanager.js conflicts with $ in jQuery
In SharePoint 2010 if CMSSiteManager.js library is loaded besides jQuery, then much of stuff stops working. The reason is that the dollar sign ($) is used in cmssitemanager.js as well which conflicts with jQuery. Mostly it appears on pages where you load jQuery and have an image library with thumbnails. To avoid this, just replace all $ with jQuery in your custom scripts. A more crazy situation is when avoiding $ isn’t enough.
Posts
javascript toolkit on text file
Referencing javascript libraries from Content Delivery Networks (CDN) like jQuery can have many benefits. The self-hosted javascript files are on the other hand give you more control. But in one situation it is much better with cdns: the development. Like Marc D Anderson pointed:
I didn’t realize it at the time, but this txt file has become a standard part of my toolkit already. I’ve added it to three client environments just since last week.
Posts
jQuery mobile and SharePoint
In this post I want to explore how to build a mobile app using jQuery mobile. Recently I discovered two great blog posts about this:
Building SharePoint web apps using Sencha Touch by Luc Stakenborg jQuery mobile and SharePoint by Chris Quick In my post I’ll use their findings and share some of mine thougts. I’ll focus mostly on how to get started with jQuery mobile and SharePoint. So go ahead and create your jQuery mobile app, just drag’n’drop some controls: Download it and yout get an “app.
Posts
Clone javascript objects
In javascript, if we copy objects or their properties, the reference still remains and by changing the new object the old one is changed, too. To clone or do a clean copy of an object I found a very useful solution by Jan Turoň on StackOverflow:
Object.prototype.clone = function() { if(this.cloneNode) return this.cloneNode(true); var copy = this instanceof Array ? \[\] : {}; for(var attr in this) { if(typeof this\[attr\] == "function" || this\[attr\]==null || !
Posts
clearInterval in Chrome doesn't work on window blur
If you want to reset all interval jobs when a browser tab is inactive, the best way would be to use clearInterval on window blur. But unfortunately Chrome fires window focus and window blur two times. Here is an embryo to a solution:
var M = window.M || {}; M.counter = 0; M.focused = true; M.tick = function() { if (M.focused) { console.log("tic tac " + ++M.counter); } }; M.start = function(e) { console.
Posts
shorthand for jQuery(document).ready
jQuery(document).ready is used very often, why not use the shorthand variant of that?
$(function() { // Code here });
Posts
moment.js - the best javascript tool for working with dates
Just look at moment.js. Everybody who have worked with dates in javascript are going to love it.
Comments from Wordpress.com Justin Cooney - Mar 3, 2012
Interesting, I hadn’t heard of moment.js. I’m taking a look at the site right now; it looks to have some very handy functionality for date manipulation!
The great thing with moment.js is e.g. that one can create a date object from asp.net date format like /Date(123543534)/
Posts
Kalendae - new javascript utility for calendars
An alternative to jQuery UI datepicker is Kalendae. (MIT License). Highly customizable and no dependencies to other javascript libraries. Here is the highlights:
Kalendae is an attempt to do something that nobody has yet been able to do: make a date picker that doesn’t suck. Kalendae provides the following features:
Fully portable, no dependencies. No jQuery, no Prototype, no MooTools; just add the script and the stylesheet and you’re good to go.
Posts
fallback for html5 placeholders
Placeholders are very handy in html5, we don’t need to fool with input values. But in SharePoint and IE we must provide fallback for placeholders if we want use them in other browsers. Here is an jQuery extension to do that:
(function ($) { $.fn.extend({ ensurePlaceholders: function () { var input = document.createElement('input'); var placeholderSupported = ('placeholder' in input); if (placeholderSupported) { return; } function setHints(elem) { var $elem = $(elem); var value = $elem.
Posts
SP.UI.Notify in Modal Dialog
If you open a custom page (not a list item form) in a modal dialog, your notification won’t be shown. The reason is that the notification area (#notificationArea) is inside a hidden div (#s4-ribbonrow). To show this notificationArea we must display the notification area:
var $ribbon = jQuery("#s4-ribbonrow"); if ($ribbon.is(":hidden")) { $ribbon.css({"min-height": 0, "height": "0px"}) .show().children().hide() .filter("#notificationArea").show() } Comments from Wordpress.com Jens Malmberg - Jan 3, 2013
Thanks a bunch again, your solution was the only good information i found quickly.
Posts
private variables in javascript
Found a nice post about private variables and “methods” in javascript. Consider this example:
function Pizza() { var price = 0; this.setPrice = function(p) { price = p; }; this.getPrice = function() { return price; }; } ```Every variable and function inside the main function is private unless it is appended to "this".
Posts
javascript: Umbrella pattern
There are two great patterns for organizing javascript code: Prototype and Module pattern. More about them later in this post. But in reality I still see much of spagghetti Just an example: SharePoint 101 code samples. They are indeed very simple and isolated examples. And many projects use this simple way in mind when they begin. But when javascript code grows, it becomes a monster. Have you seen this biest? How is this monster created?
Posts
Hello world in node.js
I know, node.js has been present for a while. But I actually had no time to try it. I was surprised that now it is very straight forward to start with node.js. Allright, everything begins with Hello world. Eventhough it is available for allmost all combinations of operating systems and servers, the easiest way to test it was actually Ubuntu. To install just run:
sudo apt-get install nodejs ```Then make a new directory and create the hello.
Posts
New functions in jQuery 1.7+ on and off
A simpler interface for event handling in jQuery. Just read Dan Wahlin’s blog.
Posts
cross browser console.log
console.log is the best tool for debugging javascript. In Firefox Firebug and Chrome Dev Tools you can even log objects which are represented as tree nodes of properties. If Firebug or Dev Tools in Chrome and IE9 are not opened, all these messages are ignored. But IE8 doesn’t understand console (if Dev Tools are closed) and raises an error: To avoid these errors, just declare an empty function just for IE8–:
Posts
javascript: passing arguments from popup to main window
To show a popup, we just have to invoke “window.open”, and provide some options to prevent opening this in a new tab:
var wnd = window.open('', '\_blank', 'width=750, height=400, location=no, resizable=1, menubar=0, scrollbars=0'); wnd.document.write(''); wnd.document.close(); wnd.document.close(); wnd.focus(); To communicate between parent and child we can refer to parent as window.opener. We can even invoke a function from parent window. Let’s create the most useful function:
foo = function() { console.log("foo"); } ```Then just click on "hej" in the popup, and see the console.
Posts
javascript: serialize as xml
Why should we need to serialize javascript objects as XML. I don’t know. It is of course more a server side need. And there actually a need for javascript serialization as xml in node.js. To serialize as json is very simple: JSON.stringify(myobjects). I was just curious if there was a tool for xml serialization in javascript. There is a nice javascript tool called XMLWriter, developed by Ariel Flesler. Consider you have articles and want to serialize them as xml, let’s create a function for serializing:
Posts
Enable Save in IE9 mode
Wouldn’t it be nice to use html5 and css3 in SharePoint? No problems, there is actually v5 master out there, created by Kyle Schaefer. Or just use h5ml5 and css3 right away in your webparts and pages. But there is a big problem. It doesn’t work in IE9–. One of the issues (even listed by Kyle) is that “save” doesn’t work in modal dialogs where Rich Text Editor is used. Especialy it is for modal dialogs.
Posts
$().SPServices is best for SOAP
SPServices is a great tool, really nice work, Marc Anderson (@sympmarc). It has been there all the time I have developed for SharePoint. But the fact that you work with XML and you must parse the attributes (!) was the reason why I prefered listdata.svc and Client Object Model, where you get objects in JSON or you have a nice API to get objects and their properties. But there is an area where SPServices are really the best tool: SharePoint Web Services which only understand SOAP like SocialDataService.
Posts
$ and jQuery in SharePoint
Do you still use $ for jQuery? Well, don’t. If your code with $ resides with a SharePoint Images webpart, it will stop working. You’ll get errors like
Uncaught TypeError: Cannot call method 'empty' of null The reason is that SharePoint uses $ in its own javascript code: CMSSiteManager.js function $() {ULSjlC:; var elements=new Array(); for (var i=0; i < arguments.length; i++) { var element=arguments\[i\]; if (typeof element=='string') element=document.getElementById(element); if (arguments.
Posts
onchange isn't firing in IE
I don’t know why, but (not always, just sometimes) IE doesn’t fire the onchange event (which is added as an attribute on an html element). A better “workaround” is to add an eventlistener in javascript. Or a lazy workaround is to use the onclick event even for checkboxes.
Posts
ScriptResx.ashx in SharePoint
In my previous post I showed a little proof-of-concept for an httphandler which I want to use to dynamically get the localization resources from SharePoint as javascript object. But wait a moment. How does SharePoint handle localization on client? When you look in Script tab in Chrome dev tools, you’ll find:
ScriptResource.axd It is added to the server when deployed. See a good introduction to WebResource.axd and ScriptResource.axd by Brian Chavez.
Posts
Custom HttpHandler in SharePoint for getting dynamic javascript code
Sometimes I want to add some dynamic javascript code. E.g. I had an idea to get javascript code for localization dynamically. Kirk Evan provides a very clean approach to add ASP.NET HttpHandler to SharePoint. This is just a little lab: Create a SharePoint empty project. I call it Jerkelle. Create a class called Resx2JsHandler and implement the IHttpHandler interface Add the mapped folder Layouts and create Jerkelle.ashx file Here is the project.
Posts
XMLHttpRequest the hard way
$.ajax is great, it hides much of the complexity. But sometimes we need to work with “raw” javascript :) So let’s look behind the scenes. The XMLHttpRequest (or just XHR) is used to open a connection to a server without a page reload. Internet Explorer calls it ActiveXObject and it differs in IE versions. Wikipedia article gives a good example how to create one constructor for all browsers: [sourcecode language=“javascript”]if (typeof XMLHttpRequest == “undefined”) XMLHttpRequest = function () { try { return new ActiveXObject(“Msxml2.
Posts
Loading notification
When you load some data with ajax, you will probably want to show the users in some way, that data is loading. To show the text “loading…” would be enough. Another, very common way to do it to show a spinner, a rotating image. In sharepoint we can use the built-in gif which can be found in /_layouts/images/loading16.gif. Well, it is actually not so good, because this image is not so beautiful.
Posts
javascript trim()
String.trim() is quite useful in many situations. Unfortunately not all browsers have this function on String prototype (e.g. IE8): I see many people use jQuery.trim(), but isn’t it better to just use String.trim and provide a backup function if it is not implemented, like we did with Date.toISOString:
if(!String.prototype.trim) { String.prototype.trim = function() { return this.replace(/^\\s+|\\s+$/g, ""); } } ```EDIT: [found this solution on SO](http://stackoverflow.com/a/8522376/632117). Did we think the same?
Posts
Push a copy of Resources to client in javascript
In one of my previous posts I told about pushing a copy of an object into client. Now I’ll try to copy my resource values into client. The problem is often that we must create multiple localization resources: first as resx-file. If we use much ajax and client side rendering, we must provide some localization there, too. If they are different subsets of localization resources, it isn’t a problem. But when you get overlapping, it becomes more difficult to manage and sync them.
Posts
Simple select unselect all
I have a simple html table, every row in tbody has a checkbox. thead has a checkbox. When it is checked/unchecked, all checkboxes have to be selected/ unselected. Here is a very simple javascript to achieve this:
$("#mytable thead :checkbox").live({ change: function () { var checked = $(this).is(":checked"); $("#mytable tbody :checkbox").attr("checked", checked); } });
Posts
Nested templates in jQuery.tmpl
I have used jQuery tmpl for a while and it is really awesome. Now I want to use some nested templates. And the thing is: it is very simple to do it: Here is the code to achieve this:
<div onclick="doo()">test</div> <div id="container"></div> <script id="parent-template" type="text/html"> <li> {{tmpl t }} </li> </script> <script id="red" type="text/html"> <span style="color:red">{{= title}}</span> </script> <script id="green" type="text/html"> <span style="color:green">{{= title}}</span> </script> <script type="text/javascript"> var d = \[\]; d.
Posts
jQuery: select elements with a specific text
There are situations when you want to select only dom elements which only have a specific content. jQuery provides a beautiful selector :contains:
$("a:contains(Pages)") ```But what if it isn't enough to just get all the elements which contain some word? Let's check what we get if we traverse all anchors on http://sv.wikipedia.org containing "wiki": $(“a:contains(wiki)”).each(function(i) { console.log($(this).text()); });
[![](https://sharepointkunskap.files.wordpress.com/2012/02/jquery-contains-wiki.png "jquery-contains-wiki")](https://sharepointkunskap.files.wordpress.com/2012/02/jquery-contains-wiki.png) There is another, a generic way, to filter out elements, and it is called "filter".
Posts
Knockout.js!
[youtube http://www.youtube.com/watch?v=DnhGqcKEPiM&w=640&h=360] See an example what you can with it SharePoint, written by Thorsten Hans.
Posts
Parameterize a javascript object and create url
If you want to add some parameters to an url which you want to open, you can use jQuery.param function:
var url = "some\_url"; var params = { name: "Setner", email: "setner@narspi.name", mobile: "123456789" }; var search = "?" + $.param(p); url += search; ```It is handy, indeed. In an environment without jQuery (are there some?:) ) you can just iterate an object and join properties: var url = “some_url”; var params = { name: “Setner”, email: “setner@narspi.
Posts
Save an excel sheet as a clean table
To save an excel sheet as a html table is very easy. Just select the needed area, then go to Save as and check the selection and choose html as output format. It works fine. It even looks like it did in Excel. But what if you don’t want all this junk, you want only the plain html table (e.g. for pasting into WP). When I saved my permission levels to html, I used this javascript code.
Posts
Datetime in ASP.NET javascript and $.ajax
In one of my previous blogs I wrote about serializing of javascript objects. You can do it with JSON.stringify or Sys.Serialization.JavaScriptSerializer.serialize. Both methods work fine… almost. There is a big difference when it comes to datetime objects. MS treats dates a little bit different (like RegEx and much more). Let’s try this one:
var writer = { name: "Ajgi", birthdate: new Date(1934, 8-1, 21) }; var json = JSON.stringify(writer); var msjson = Sys.
Posts
Simple stopwatch in javascript
If some javascript code takes too much time to execute, you probably want to see what time your code or a part of the code takes to run. I found an idea in Dave Cranes Ajax in Action. The book is a little bit old and the code provided below has been changed and simplified:
var stopwatch = {}; stopwatch.watches = \[\]; stopwatch.getWatch = function(id, startNow) { var watch = stopwatch.
Posts
Get url parameters with javascript
There is a question in Stackoverflow and this one, too. There is a fine solution for jQuery. The only thing we need is window.location.search. Say we have http://domain.com?q=hello&a=good#home, then it takes only ?q=hello&a=good, and leaves #home and the main url. Anchors can be retrieved with hash. Here are all properties of window.location: Google Chrome provides a fine function: window.location.getParameter: I like the name of this function. So why not to use it or create this one if a browser doesn’t have it?
Posts
Reload page in js: RefreshPage
There are many ways to reload / refresh a page in javascript. One of them is as in discoveringsharepoint.wordpress.com describes:
window.location.reload() ```Today I found some tools which are shipped with ASP.NET/SharePoint to reload a page. The big advantage of them they are designed to work with SharePoint and take all possible aspects of page life cycle into account. The javascript function to refresh a page is just called, guess..: **RefreshPage** and it resides in init.
Posts
Run javascript code except it is inside a modal dialog
Want to run some javascript code everywhere, but not in a modal dialog. Because errors are occured, or this code is unnecessary i dialogs. Well here is a solution I have found after some experiments:
$(document).ready(function() { if (!window.location.href.match(/isdlg=1/i)) { onDocumentReadyExceptItIsInDialog(); } }); function onDocumentReadyExceptItIsInDialog() {} ```This code checks with Regular Expressions if the url of the parent window contains IsDlg=1, if so nothing happens. In the usual case (not inside a dialog), the javascript code runs.
Posts
Simplifying jQuery tmpl interface
In one of my previous posts I showed a simple example how to retrieve data from a web service and render it with jQuery tmpl. To render this I used an id for a template and the container:
<script id="contactTemplate" type="text/html"> <div> Name: {{= Name }} <br> Phone: {{= Phone }} </div> </script> <div id="contactContainer"></div> ```To render we select the template and container with jQuery selectors: function onSuccess(data) { $("#contactTemplate").tmpl(data.d.results).appendTo("#contactContainer"); }
Posts
listdata.svc vs CSOM for retrieving and manipulation of list items
What is better and where and when… I’ll try to find out.. This post will be updated soon. Take a look at this so far: http://sharepoint.stackexchange.com/questions/23209/sharepoint-2010-javascript-client-object-model-cross-site-collections
Posts
String.format for javascript
sprintf is actually the best javascript implementation of sprintf (string.format). But wait, shouldn’t it be some more .NET-like stuff in SharePoint environment? Indeed there is! (Well, not only in SP, but ASP.NET) String.format(“Hello {0}”, “world”) does exactly the same thing as on server side. Wow, it opens for many opportunities, e.g. in jQuery tmpl: String.format validates arguments, and if all is OK, it invokes another function String._toFormattedString:
function String$\_toFormattedString(useLocale, args) { var result = ''; var format = args\[0\]; for (var i=0;;) { var open = format.
Posts
Batch remove
To add items to a list in bulk, or remove them in bulk. Well to do that you can use SPLinq, Server Object Model and … web.ProcessBatchData, which is the most effective. I did an experiment today. I created 1000 tasks in my task list three times and removed all items in three different ways and took time. First I put 1000 items with ajax and listdata.svc:
function pad(n) { if (n >= 10000) return n; if (n >= 1000) return '0' + n; if (n >= 100) return '00' + n; if (n >= 10) return '000' + n; return '0000' + n; } var s; var counter = 0; var title = "task " function foo() { counter++; if (counter > 10000) { window.
Posts
use two different versions of jQuery on the same page
jQuery is very popular. The chance that you’ll get two or more jQuery files loaded on the same page is very high. As long as it doesn’t conflict, it is fine. But what if there are differences, and another version of jQuery destroys your functionality. To solve it we can ensure that we invoke “our”, the right version of jQuery. To do so, create a pointer to your jQuery:
var myJq = jQuery.
Posts
this.data in jQuery tmpl
In jQuery tmpl we can render properties with {{= SomeProperty }}. Here is an example:
<script type="text/javascript"> Writer = function (firstName, lastName) { this.firstName = firstName; this.lastName = lastName; }; Writer.prototype = { getFullName: function () { return this.firstName + " " + this.lastName; } }; $(document).ready(function () { var writers = \[\]; writers.push(new Writer("Gennady", "Ajgi")); writers.push(new Writer("Mišši", "Şeşpĕl")); writers.push(new Writer("Ille", "Tuktaš")); writers.push(new Writer("Kĕştenttin", "Ivanov")); $("#tmpl").tmpl(writers).appendTo("#writers"); }); </script> <script id="tmpl" type="text/html"> <li> {{= firstName }} {{= lastName }} </li> </script> <div id="writers"></div> ```It will render like: * Gennady Ajgi * Mišši Şeşpĕl * Ille Tuktaš * Kĕştenttin Ivanov But what if we want to access the object itself, not one of the properties.
Posts
format javascript date in ISO 8601
There is a solution in StackOverflow:
/\* use a function for the exact format desired... \*/ function ISODateString(d){ function pad(n){return n<10 ? '0'+n : n} return d.getUTCFullYear()+'-' + pad(d.getUTCMonth()+1)+'-' + pad(d.getUTCDate())+'T' + pad(d.getUTCHours())+':' + pad(d.getUTCMinutes())+':' + pad(d.getUTCSeconds())+'Z'} var d = new Date(); print(ISODateString(d)); // prints something like 2009-09-28T19:03:12Z ```But there is already a function for this: toISOString, it came with ecmascript 5. [Unfortunately, not all browsers support this](http://kangax.github.com/es5-compat-table/ "See the best comparision for ecmascript 5 support"), to solve this problem, we can provide our own prototype function for Date if it doesn't exist: if (!
Posts
javascript Module pattern
Want organize your js code in a kind of namespaces, or modules, then use the module pattern. I’ll take the dummy example for getting the current anchor. Let’s look how it would be if the prototype based approach is used:
var Contoso.Utils = function() {}; Contoso.Utils.prototype = { getCurrentAnchor: function() { var url = window.location; var anchor=url.hash; //anchor with the # character var anchor2=url.hash.substring(1); //anchor without the # character return anchor2; } }; var util = new Contoso.
Posts
Get the current anchor in javascript
To get the current anchor, we can use hash property::
var url = window.location; var anchor=url.hash; //anchor with the # character var anchor2=url.hash.substring(1); //anchor without the # character
Posts
Pass arguments from/to Modal Dialog
To pass arguments from a ModalDialog is easy. Provide some buttons and invoke close function:
SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.OK, someValue); ```The first argument is result, [it is a enumeration with three alternatives](http://msdn.microsoft.com/en-us/library/ff409060.aspx): cancel, invalid and OK. The value you pass back to the main window can be a simple string, or a complex javascript object. In this example I'll create a html element which is hidden (id="modal-form" [class="s4-die"](/2011/10/14/s4-die/)): Pass arguments to Modal Dialog and use it In options you pass to SP.
Posts
Get current user and handle a success callback
In my previous post I needed the accound id of the current user for posting new list items. To retrieve the id, we can push this to the client from the code behind, or get the current user using Client Object Model. To provide a more generic way we can write a js function which get the current user. But we must even provide some callback functionality, otherwise we don’t know if the operation was successful or not.
Posts
jQuery tmplItem and no ids
tmplItem() works even without ids. To get the current data:
$(this).tmplItem().data; ```If you want to remove, just invoke the ajax and remove with [$.parents](http://api.jquery.com/parents/): $(this).parents(“li”).remove();
##### Updating data inside tmplItems If you want to achieve some fancy dependency tracking, consider [knockout.js](http://knockoutjs.com/). But if you just want to update the data object inside a tmplItem, just change the object and call update: var t = $(this).tmplItem(); var obj = t.data; obj.Address = “hello avenue”; t.
Posts
Update list items with listdata.svc
In one of my previous posts I showed how to retrieve data from listdata.svc with jQuery $.getJSON method. Getting data is very simple, listdata.svc provides a powerful restful interface with filtering, expanding and other features. Read the best and short introduction to listdata.svc by Suneet Sharma or a more detailed and technical article about filters, functions and operators by Mike Flasko at Microsoft with short examples here. Now back to listdata.
Posts
The cleanest auto resize for a textarea
The cleanest way to auto-resize a textarea while typing (like wall post on Facebook) is George Papadakis solution. It uses only standard javascript and provides eventlisteners for IE (attachEvent) and other browsers (addEventListener): [sourcecode language=“javascript”] window.onload = function() { var t = document.getElementsByTagName(’textarea’)[0]; var offset= !window.opera ? (t.offsetHeight - t.clientHeight) : (t.offsetHeight + parseInt(window.getComputedStyle(t, null).getPropertyValue(‘border-top-width’))) ; var resize = function(t) { t.style.height = ‘auto’; t.style.height = (t.scrollHeight + offset ) + ‘px’; } t.
Posts
javascript load callback for UpdatePanel
Using asp:UpdatePanel isn’t so easy with jQuery(document).ready() or jQuery(window).load(). The jQuery selectors can’t find elements which are not shown in the beginning. All other elements which are loaded dynamically are difficult to catch. I found a solution in forums.asp.net. A user called germanz creates an jQuery event listener AjaxReady, he uses the ASP.NET built-in PageRequestManager. If there only few usages of it it can be invoked directly from a PageRequestManager instance:
Posts
jQuery UI Datepicker
As an alternative to asp:Calendar we can use the fancy jQuery UI Datepicker:
$(document).ready(function () { $.datepicker.setDefaults($.datepicker.regional\["sv"\]); $("#").datepicker({ changeMonth: true, changeYear: true, yearRange: "-120:+0" }); }); ```I found this a much simple and best solution for an [birthdate input](http://stackoverflow.com/questions/339956/whats-the-best-ui-for-entering-date-of-birth). We can set [international options](http://stackoverflow.com/questions/1865091/jquery-datepicker-language-problem), [year range](http://stackoverflow.com/questions/269545/jquery-datepicker-years-shown), [year](http://stackoverflow.com/questions/3164898/jquery-ui-datepicker-next-and-previous-year) and [month navigation](http://jqueryui.com/demos/datepicker/dropdown-month-year.html). Other options I have tried are asp:Calendar, ajaxtoolkit:CalendarExtender and DateJs. jQuery UI is the most simple much more than datepicker and works smoothily with SharePoint.
Posts
Push a copy of an object to client
To reduce postbacks and database calls, a copy of the current object(s) can be pushed down to the client in JSON format. Say a webpart renders information about a person, another webpart shows related information which is retrieved dynamically (like web services). Instead of getting the current person from the database in the second webpart again, we can reuse the same person object from the first webpart. To do so we must provide a DataContract for the Person class:
Posts
json serializer in Sharepoint
There is a very handy JSON lib for serializing javascript objects. It is hosted on github under douglas crockford. Download json2.js and serialize with JSON.stringify function: EDIT: There is actually this function in core javascript. It exists since javascript 1.7 and ecmascript 5. So you don’t have to add anything to get this functionality:
var t = { name: "dev", city: "new york" }; JSON.stringify(t); ```There are actually built-in goodies for serializing javascript objects in [ASP.
Posts
Load Profile Image with javascript
See a great post in “Learning Sharepoint” with an example how to get a picture of user with Client Object Model and javascript.
Posts
jQuery timeago and the localization
If you have used SPUtility.TimeDeltaAsString you must know how useful it is. There is also the jQuery plugin that can perform counting of time deltas and (!) translate it. jQuery timeago is available for many languages, Swedish among others:
// Swedish jQuery.timeago.settings.strings = { prefixAgo: "för", prefixFromNow: "om", suffixAgo: "sedan", suffixFromNow: "", seconds: "mindre än en minut", minute: "ungefär en minut", minutes: "%d minuter", hour: "ungefär en timme", hours: "ungefär %d timmar", day: "en dag", days: "%d dagar", month: "ungefär en månad", months: "%d månader", year: "ungefär ett år", years: "%d år" }; ```The code is hosted on [Github](https://github.
Posts
Filtering in javascript
The simplest and the best way to filter an array is to extend the Array.prototype as described here:
if (!Array.prototype.filter) { Array.prototype.filter = function (func) { var len = this.length; if (typeof func != "function") throw new TypeError(); var res = new Array(); var thisp = arguments\[1\]; for (var i = 0; i < len; i++) { if (i in this) { var val = this\[i\]; if (func.call(thisp, val, i, this)) res.
Posts
Extend an event in javascript
If you use jQuery, you don’t need it. But if you for some reason must use javascript you must beware of adding events. The most dangerous is window.onload. Consider this scenario:
function doSomethingGreat() {}; window.onload = doSomethingGreat; ```It works fine if you are the only person who writes window.onload handler. But on such platforms like SharePoint you can't know which events exist. And if you just write **window.onload = doSomethingGreat;** you override all other window.
Posts
Sorting Dates in javascript
To sort an array in javascript, just run sort():
array = \["skåne", "blekinge", "halland"\]; array.sort(); ```To [perform a more intelligent sorting](http://stackoverflow.com/questions/3859239/sort-json-by-date "See the original answer in stackoverflow") we can define our sorting logic. What if an array has objects with different properties? For example, an object has title and lastupdated. We want to sort on lastupdated. Just create a function for this with two parameters: function custom_sort(a, b) { return new Date(a.
Posts
$.getJSON, jQuery.tmpl and _vti_bin
Javascript is very fast, responsive and unburdens the cpu at the server. Here I show a little example how to use jQuery.getJSON, jQuery.tmpl (wonderful plugin for rendering repeating data, repo hosted on Github) and REST-based service listdata.svc from /_layouts/_vti_bin/ folder. For this example I created a generic list “Contacts”, added two text fields Name and Phone. Add some phone numbers and try to go to /_vti_bin/ListData.svc/Contacts If you get 404-error, install a ADO.
Posts
Remove links to user profiles on list with javascript
Well, if you need remove links to user profiles, you can iterate all td-elements with class ms-vb-user using jQuery each function and remove a elements. Here is a little script:
$(document).ready(function() { $(".ms-vb-user a").each(function() { var text = $(this).text(); var span = document.createElement("span"); var user = document.createTextNode(text); span.appendChild(user); var parent = $(this).parent()\[0\]; parent.removeChild(this); parent.appendChild(span); }); }); ```EDIT 2012-02-05 A much more better way to do it is [to use replaceWith in jQuery](http://stackoverflow.
Posts
Reset favicon cache
Favicon is one of the hardest. Ctrl-F5 doesn’t help. You can of course see the source, find the location of the favicon, click on it (if you use Firefox or Chrome), otherwise copy the url and paste it in the address bar. When you load it separately, the favicon cache is renewed. It works. But if you want to make it easier for your users, set a version to your favicon file in the masterpage:
Posts
Go back in javascript
Add link for “Go Back” in javascript (inspired by Webmasters tips):
<a href="javascript:location.href=document.referrer;">Back</a> ```If you have access to the code behind you can [do the same](http://www.beansoftware.com/ASP.NET-FAQ/Referrer-URL.aspx) with: Request.UrlReferrer.ToString() ```If you want to go to site collection root, it is simple, too: <SharePoint:SPLinkButton runat="server" NavigateUrl="<% $SPUrl:~SiteCollection/%>">Start</SharePoint:SPLinkButton>
Posts
Auto-resize the main container in master page
If you have a master page with fixed size (perhaps in a centered layout). Here is a simplistic js-script to auto-resize:
$(window).load(function(){ $wider = false; $pagecontainer = $("#pagecontainer"); $elementsToCareAbout = $("#ctl00\_MSO\_ContentDiv > \*, #ctl00\_MSO\_ContentDiv table") $elementsToCareAbout.each(function(){ if($(this).width() > $pagecontainer.width()) { $wider = true; } }); if ($wider) $pagecontainer.width(1200); }); Any improvement ideas and suggestions are more than welcome.
Posts
Check if an html element is hidden using jQuery
Well, sometimes we need to calculate width and so on. In my next post I will write about how to fix auto-resize on fixed sized master pages. But now: a very nice stuff: how to check if an element is hidden or not:
$("#s4-leftpanel").is(":visible") ```It is a pure poetry. It reminds me of the beauty of [symbols in Ruby](http://rubylearning.com/satishtalim/ruby_symbols.html).
Posts
MongoDB shell, learn directly in browser
Are you also curious about NoSQL databases. Well, MongoDB is one of the most known ones. MongoDB has a javascript syntax (json), I like it. Try out the interactive shell at the mongodb site. Quickstart on Ubuntu To test it on Ubuntu, just install an existing apt-package:
sudo apt-get install mongodb Create the default folder and change permissions:
sudo mkdir -p /data/db/ sudo chown \`id -u\` /data/db ```Then jump directly into mongo db shell: mongo
Posts
Good pattern for javascript files
SP.js exists in two variants in debug mode and in modified. When you develop it is better to use debug mode. When it goes to production it is better to use minified files. The same you can do with your files. Wictor Wilen explains how to do minify your custom javascript files. I think it is a good pattern to create javascript files and call them something-something**.debug.js**. Then when you are done, run the custom tools to minify them.
Posts
Show html in ModalDialog
We can use ModalDialogs to show not only pages, but some html:
var htmlElement = document.createElement('p'); var helloWorldNode = document.createTextNode('Hello world!'); htmlElement.appendChild(helloWorldNode); var options = { html: htmlElement, autoSize:true, allowMaximize:true, title: 'Test dialog', showClose: true, }; var dialog = SP.UI.ModalDialog.showModalDialog(options);
Posts
Resize image with jQuery to fit the div
There are many interesting jQuery plugins for resizing and cropping of images. Among them are jrac and image scale. I have tested the latter: It works very fine
$(window).load(function() { var $imgContainer = $("#layout-news-image"); var $newsImg = $("#layout-news-image img\[rel!='sp\_DialogLinkIgnore'\]"); $imgContainer.css("width", $imgContainer.parent().width()); if ($newsImg.length > 0) { if ($newsImg.width() < $imgContainer.width()) { $imgContainer.width($newsImg.width()); } if ($newsImg.height() < $imgContainer.height()) { $imgContainer.height($newsImg.height()); } $newsImg.imgscale({ parent : '#layout-news-image', center: "true", scale: "fill" }); } }); ```This script checks if the original image is lesser than container div and doesn't resize if it is so.
Posts
Show a presence bubble
There is no built-in sharepoint control for the presence bubble. If you want to add this functionality on your pages you have to add it as html. Here is a sample:
private static int \_COUNTER = 0; private const string PresenceBubble = "<a class='ms-imnlink' href='javascript:;'>" + "<img width='12' height='12' id='imn\_pawn\_{0}' onload=\\"IMNRC('{1}')\\" alt='My SID' " + "src='/\_layouts/images/imnoff.png' border='0' " + "showofflinepawn='1' sip='{2}'></a> {3}"; private static string FormatUser(SPUser user) { \_COUNTER++; return string.
Posts
less.js
Det finns ett intressant projekt som kan hjälpa att strukturera css-filer. Du skriver regler i en kombination av css och javascript. Det omvandlas med hjälp av js till css. Projektet heter less.js, läs mer om detta på sharepointoverflow.
Posts
window.onload
Sharepoint ger en annan lösning för window.onload och jQuery(document).ready(function() {}); _spBodyOnLoadFunctionNames.push(‘gerdaRibbonInit’);"
Posts
jQuery validation with asp.net
De kan var lite jobbigt att få till jQuery validate att funka ihop med aspnetForm…
$(document).ready(function () { newsLetterForm = $("#aspnetForm"); newsLetterForm.validate({ onsubmit: false, rules: { "<%= emailTextBox.UniqueID %>": { required: true, email: true } } }); $("#<%= sendButton.ClientID %>").live("click", function { var isValid = newsLetterForm.valid(); if (!isValid) { e.preventDefault(); } }); }); jQuery validate kräver name på elementen inuti formen. För att ta reda på name, måste man använda Control.
Posts
Vänta tills sp.js laddats
Här är en funktion som man kan använda för att vänta till sp.js laddats och köra sin funktion:
ExecuteOrDelayUntilScriptLoaded(myjsfucntion, "sp.js"); Eftersom det kan vara så att sp.js laddas med lazy loading:
<SharePoint:ScriptLink Name="SP.js" runat="server" OnDemand="true" Localizable="false"
Posts
Uppdatera web med js
Här är ett litet exempel:
function updateTitle() { var ctx = new SP.ClientContext.get\_current(); this.web = ctx.get\_web(); web.set\_title('Examensarbete 2011'); this.web.update(); ctx.executeQueryAsync( Function.createDelegate(this, this.onUpdate), Function.createDelegate(this, this.onFail)); } function onUpdate(sender, args) { alert('title updated'); } function onFail(sender, args) { alert('failed to update title. Error:'+args.get\_message()); }
Posts
Registrera javascript i feature
Om det inte passar att javascript i masterpage eller egen webpart, registrera det som customaction och aktivera feature. Läs mer här. Här är ett exempel:
<CustomAction Location="ScriptLink" ScriptSrc="~sitecollection/\_layouts/MyProject/awesome.js" Sequence="101"> </CustomAction>
Posts
Aktivera intellisense för javascript i VS
Det finns ett sätt att aktivera intellisense för javascript i VS: Klistra in det i ditt js-fil eller aspx:
/// <reference name="MicrosoftAjax.js" /> /// <reference path="file://C:/Program Files/Common Files/Microsoft Shared/Web Server Extensions/14/TEMPLATE/LAYOUTS/SP.core.debug.js" /> /// <reference path="file://C:/Program Files/Common Files/Microsoft Shared/Web Server Extensions/14/TEMPLATE/LAYOUTS/SP.debug.js" /> ```Men tyvärr [kommer det inte funka om du har installerat Resharper](http://devnet.jetbrains.net/thread/297493). Eller lägg till vanliga script-taggar som beskrivet i boken Sharepoint As Developer Platform: <asp:PlaceHolder ID=“PlaceHolder1” runat=“server” Visible=“false”> </asp:PlaceHolder>
Posts
javascript API i Sharepoint
Det är supersmidigt. Här är ett exempel: function createAnnouncement(title, body) { var ctx = new SP.ClientContext.get\_current(); var list = ctx.get\_web().get\_lists().getByTitle('Meddelanden'); var itemCreationInfo = new SP.ListItemCreationInformation(); this.newListItem = list.addItem(itemCreationInfo); this.newListItem.set\_item("Title", title); this.newListItem.set\_item("Body", body); this.newListItem.update(); ctx.executeQueryAsync( Function.createDelegate(this, this.onSucceededCallback), Function.createDelegate(this, this.onFailedCallback)); } function onSucceededCallback(sender, args) { SP.UI.Status.addStatus("Info", "It worked!",true); } function onFailedCallback(sender, args) { SP.UI.Status.addStatus("Info", "It didn't work!",true); } Comments from Wordpress.com westerdaled - Feb 0, 2013
Thanks, I gather I can pass OnSucceedCallback as a delegate.
Posts
Validera din form på klienten
Det finns ett mycket bra jQuery-tillägg som kan validera din data i en formulär på ett enkelt sätt. Se en demo. Referera till validate.js och ange rätt css-klasser på dina inputs: “required”, “error”, “url”, “valid”. Mycket smidigt.
Posts
cloud9 web ide
Skapa javascript-appar i din webbläsare. Mycket smidigt. Direkt kontakt till github.
Posts
Ladda jQuery dynamiskt till din sida
Vill du ändra innehåll, testa olika javascript-funktioner på din sida, prova något direkt i webbläsaren (utan att behöva deploya om), så är DevTools i Chrome, eller Firebug i Firefox väldigt bra verktyg. Om du har jQuery på din sida, så är det ännu bättre. Men om du inte har det, så ladda det i efterhand genom att öppna konsolen (Ctrl-Shift-J i Chrome) och kör följande rader kod (klistra in dem på en gång, och tryck på Enter):
Posts
Get coordinates from Google Maps
To get longitude and latitude can be tricky at the first time. There are many ways to do this, e.g. getlatlon.com. Good enough, but not so practical if you want to collect many coordinates. You can’t search after street names, you only can scroll and drag. Another way is to use javascript to show the longitude and latitude. See this example. This works in all web browsers.Just find your object in Google Maps and paste this javascript in URL bar: javascript:void(prompt('',gApplication.
Posts
Undvika postback i button
Äntligen har jag kommit på hur man kan skippa oönskad postback i button. Det finns många olika lösningar. Här är ett intressant inlägg på stackoverflow om det. Men det enklaste sättet är egentligen bara lägga till
return false; ```i onclick... Här är lösningen using System.Web.UI.HtmlControls; … HtmlButton HtmlButtonSendMail; protected override void CreateChildControls() { … #region Configure Send Email HtmlButtonSendMail = new HtmlButton(); HtmlButtonSendMail.InnerText = “Send Email”; HtmlButtonSendMail.ID = “HtmlButtonSendMail”; string script = “”; script += “SP.
Posts
JSFiddle
Vill du snabbt testa javascript, css och sånt, då är JSFiddle rätt för dig. Skapa ett konto där och njut.
Posts
Polymorfi och javascript
En skräckscenario: du använder två javascript-bibliotek. Men de har var sin funktion som har samma namn. Det spelar även ingen roll om antalet inparametrar är olika. Så det blir samma sak som myfunc(param1, param2) och myfunc(param1). Grejen är att funktionen som laddas sist är den som kommer köras. Katastrof! Men det finns lösningar. Börja läsa här om hur man kan simulera polymorfi i javascript på about.com. Säg vi har en funktion som heter MoveToDate(strdate, ctxid) den ingår i init.
Posts
Felsök på clientsidan med Chrome DevTools
Här är en väldigt bra video som berättar om nya devtools i Google Chrome 10. Den visar 12 tricks hur man kan underlätta felsökning av html, css och javascript. Att kunna ändra html,css och js on-the-fly är faktiskt häftigt. För mig som länge har använt Firebug i Firefox (som nu inte funkar på FF4 RC) känns devtools väldigt bra. [youtube http://www.youtube.com/watch?v=nOEw9iiopwI&w=530&h=335]
Comments from Wordpress.com Ändra utseendet på sidan direkt i webbläsaren « Sharepoint.
Posts
Använd inbyggd ModalDialog
Vill du visa någon formulär, eller längre information kan du använda en snygg (snygg och snygg?) ruta som är default i Sharepoint. Den är i alla fall användbar. Här är ett litet enkelt exempel, för att illustrera:
var options = { url: "http://sverigesradio.se", width: 800, height: 600, allowMaximize: false }; SP.UI.ModalDialog.showModalDialog(options); Det finns även möjlighet att ha OK-knappen, alltså som alert i javascript. Kolla den här länken.
Posts
Visa en popup-ruta
Visst är det fint med en formulär eller ruta som dyker upp medan ursprungssidan blir mörklagd. I grunden så ändras opacity på hela sidan, blir mörkare. En iframe med högre z-index dyker upp. I den iframe finns en annan sida. Hur gör man för att ta fram den rutan? Här berättar jag lite om det:
Posts
javascript i Webpart
Här är en bra länk hur man kan använda javascript: http://dotnetslackers.com/articles/aspnet/JavaScript_with_ASP_NET_2_0_Pages_Part1.aspx
this.Page.ClientScript.RegisterStartupScript(this.GetType(), "ButtonSendMailConfirm\_Click", "alert('mail skickat!')", true);