Below you will find pages that utilize the taxonomy term “JQuery”
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. Please leave feedback if you find it useful. You can also share your suggestions. We measured the performance before our code changes and after them. We had amazing results. Unfortunately I can not share any numbers, but we improved the Time to First Byte, time to load event firing in the browser, memory consumption in the clients and, perhaps, the most important, we improved the perceived performance of the Intranet, the way how users experience the speed and UI responsiveness. To do this I got many ideas of my project colleagues and branch colleagues. Here is the list of changes we’ve implemented:
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:
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 (.ps1 and psm1)
- Xml files (all the SharePoint .xml files)
Here is the powershell code that counts lines of code: [code language=“powershell”] # go to the solution folder cd #count lines in .cs files ls -include *.cs -recurse | select-string . | measure | select count #count lines in our .js files ls -include *.js -recurse ` -exclude *min.js, jquery*, _*, jsrender*, CamlBuilder*, knockout* ` | select-string . ` | measure ` | select Count #count lines in our powershell scripts ls -include *.xml -recurse | select-string . | measure | select count #count lines in our powershell scripts ls -include *.ps1, *.psm1 -recurse | select-string . | measure | select count [/code] Just a curious fact, I can’t tell you how many lines of code we have in our solution, but I can reveal the proportions. If I used the flexible box model in css3, it would look like this: There are as many lines of code written in javascript as it is in C#. The main reason that for the big js code base are the SharePoint hosted apps. The PowerShell scripts are as big the javascript code base. Xml files are 4 times bigger than C# code, and it is even bigger than the sum of all lines of code written in C#, JavaScript and PowerShell. It isn’t strange that xml is dominating, almost everything in SharePoint is defined in xml. Fortunately, there are less cases where you have to write raw xml in Visual Studio 2012/2013 and SharePoint 2013. How does it look in your project? What language is dominating in your SharePoint project?
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. The comments text box is rendered as an OnPostRender action in the blog comments display template. After debugging the javascript in hours and comparing the two environments, I just could confirm that displaytemplates are the same. There are two main javascript files that are involved:
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. Minimal Dowload Strategy or MDS is a new feature in SharePoint 2013. By now, if you read this post, you already know about it. The simplest way to see if MDS is enabled on your site, you can recognize it on the “ugly” urls. I don’t think they are so ugly. But it is a matter of taste and habit. No matter if you like MDS or not, MDS is enabled on many site templates and is a huge step towards a faster, more responsive architecture in SharePoint, I would say, towards the Single Page Application concept in SharePoint (but it is a long way to go). We have to keep the MDS in mind, when we write our customizations in javascript. SharePoint 2013 loves javascript and the probability is high that you write a lot of javascript. If it doesn’t work with MDS, your code breaks and the user doesn’t see the functionality, or the site owner must disable the Minimal Download Strategy feature. I wouldn’t like to have disabling of an improvement feature as a prerequisite for my code. In this blog post I want to dig into the techniques for getting the javascript code working with MDS. For a while ago I read a wonderful blog post in Chris O’Brien’s blog:
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
});
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. There is a Chuvash Wikipedia cv.wikipedia.org.
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:
$ 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. It is when you load jQuery to page head automatically on all pages. The Asset picker (AssetPortalBrowser.aspx) invokes $ itself and gets with jQuery in conflict without you write a single line of custom javascript code. You usually get the following error:
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.html” file and “my.css”. For now ignore my.css. app.html is something like that:
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.log("starting...");
M.focused = true;
};
M.stop = function(e) {
console.log("stopping...");
M.focused = false;
};
$(window).on({
focus: M.start,
blur: M.stop
});
M.ticker = window.setInterval(M.tick, 1000);
shorthand for jQuery(document).ready
jQuery(document).ready is used very often, why not use the shorthand variant of that?
$(function() {
// Code here
});
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.val();
if (value == "") {
var placeholder = $elem.attr("placeholder");
$elem.val(placeholder);
$elem.addClass("empty-text");
}
}
function removeHints(elem) {
var $elem = $(elem);
$elem.removeClass("empty-text");
var value = $elem.val();
var placeholder = $elem.attr("placeholder");
if (value == placeholder) {
$elem.val("");
}
}
this.find("\[placeholder\]").each(function() {
setHints(this);
});
this.on("focus", "\[placeholder\]", function(e) {
removeHints(this);
});
this.on("blur", "\[placeholder\]", function(e) {
setHints(this);
});
}
});
})(jQuery);
```Then "ensure placeholders" by running this function on a wrapper element which contains fields with the placeholder attribute:
jQuery("#form-wrapper").ensurePlaceholders();
New functions in jQuery 1.7+ on and off
A simpler interface for event handling in jQuery. Just read Dan Wahlin’s blog.
$ 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.length==1) return element;
elements.push(element);
}
return elements;
}
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);
}
});
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.push({ title: "one", t: "red" });
d.push({ title: "two", t: "green" });
$.template("red", $("#red").template());
$.template("green", $("#green").template());
function doo() {
$("#parent-template").tmpl(d).appendTo("#container");
}
</script>
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". So a little regex check will do the trick.
$(“a”).filter(function() { return /look_for/i.test($(this).text()); }
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.name”, mobile: “123456789” }; if (url.match("/\?/g") == null) { url += “?”; } else { url += “&”; } var search = “”; for(var p in params) { search += [p, params[p]].join("="); } url += search;
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. First open the html page which Excel has created in Chrome, open the Dev Tools console, load the latest jQuery into the page, and remove all unnecessary attributes and styling, remove the comments, after that you can just copy the outerHTML of the table and paste into a text editor:
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"); }
(function ($, undefined) { if ($ === undefined) { throw “Dependency: jQuery is not defined. Please check javascript imports.”; } $.extend($.expr[’:’], { // :template(name) template: function (current, index, metadata, elements) { var arg = metadata[3], d = $(current).data(“template-for”); if (d === undefined) { return false; } return arg ? arg === d : true; }, // :container(name) container: function (current, index, metadata, elements) { var arg = metadata[3], d = $(current).data(“container-for”); if (d === undefined) { return false; } return arg ? arg === d : true; } }); } (jQuery));
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.noConfict();
```So if you can, avoid invoking $ or jQuery directly. Here is the original example from [jQuery forum](http://forum.jquery.com/topic/multiple-versions-of-jquery-on-the-same-page):
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. Say, you want to pass the object from the array into a js function as a parameter to decide how it will be rendered, or if you want show a "calculated" property. The key word is...: this.data. this.data has the current object. After it has been rendered, we can access this object with $(this).tmplItem().data.
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.update();
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.svc in the SharePoint environment. Corey Roth provides a good images and sample results. For REST the “http verbs” are very important: GET, POST, PUT, DELETE.. SharePoint RESTful interface defines these verbs like that:
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.
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.push(val);
}
}
return res;
};
}
```Then let's filter on [titles](/2011/11/21/sorting-dates-in-javascript/ "See an example for Sorting with Titles"), which [start with](http://stackoverflow.com/questions/646628/javascript-startswith "See the solution for startsWith in javascript on Stackoverflow") "N":
function startsWithN(element, index, array) { return element.toLowerCase().indexOf(“n”) == 0; }
$.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.NET Data Services v1.5 CTP2, as described at dotnetmafia. If you want to know more about how to sort and filter, skip and limit results, read more at nothingbutsharepoint. If you encounter problems, follow Michaël’s blog post and download and install Windows6.1-KB976127-v6-x64.msu (if you have Windows Server 2008 R2), or NDP35SP1-KB976126-v2-x64.exe (if you have Windows Server 2008). After installing the version of the System.Data.Services.dll file is 3.5.30729.5004 (Windows Server 2008 R2), and 3.5.30729.4466 (Windows Server 2008). Allright, the remainder is pure javascript. In order to get it working you have to run the script from the same domain, meaning you can’t run javascript to retrieve the data from a html-file from your home folder. Create a webpart and add it to your page.
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.com/a/2409163/632117 "See a similar question and an answer on StackOverflow"):
$(".ms-vb-user a").each(function() { $(this).replaceWith(this.childNodes); });
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.
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).
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. **#layout-news-image img\[rel!='sp\_DialogLinkIgnore'\]** means that do not resize if there is a hidden image with rel="sp\_DialogLinkIgnore". See the [jQuery selectors](http://api.jquery.com/category/selectors/) for more info. This script can be improved by adding window resize event in javascript. I use **$(window).load** instead of the usual _$(document).ready_ because [ready-function in jQuery runs when DOM is loaded, if the page is not cached it happens before the image is loaded](http://web.enavu.com/daily-tip/daily-tip-difference-between-document-ready-and-window-load-in-jquery/). $(document).ready doesn't work.
## Comments from Wordpress.com
####
[sdfsdf](http://sdsdfsdf "sdfsdf@ssdf.sdd") - <time datetime="2012-06-28 19:28:51">Jun 4, 2012</time>
doesn't work: it's just squeeze the picture. No examples included == no possibility to check.
<hr />
####
[Anatoly Mironov]( "mirontoli@gmail.com") - <time datetime="2012-11-05 10:06:01">Nov 1, 2012</time>
Thank you Alejandro for the awesome js lib and sharing it. I will absolutely recommend it.
<hr />
####
[Alejandro Emparan (@krc_ale)](http://twitter.com/krc_ale "krc_ale@twitter.example.com") - <time datetime="2012-11-02 20:21:55">Nov 5, 2012</time>
I wrote a jQuery plugin for that: https://github.com/karacas/imgLiquid
<hr />
window.onload
Sharepoint ger en annan lösning för window.onload och jQuery(document).ready(function() {}); _spBodyOnLoadFunctionNames.push(‘gerdaRibbonInit’);"
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.UniqueId För att det ska fungera måste du köra preventDefault()
jQuery hide
Jag har alltid använt hide-funktionen i jQuery för att gömma vissa element som inte behövs i början. Det kan resultera att användaren ser skymningen av dem i laddningen av sidan. Vilket inte är så bra. Men det har visat sig, att hide behöver inte köras av jQuery. Bara göm dem med hjälp av css. jQuery show kommer funka ändå.
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.
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):
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.debug.js (som används av Sharepoint kalenderwebpart). Sedan har vi något annat javascript-bibliotek som också har MoveToDate(param). Låt oss göra det polymorfiskt. Här är koden: