Below you will find pages that utilize the taxonomy term “jQuery”
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
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
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
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
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
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
$ 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
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
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
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
New functions in jQuery 1.7+ on and off
A simpler interface for event handling in jQuery. Just read Dan Wahlin’s blog.
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
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
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
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
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
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
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
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
$.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
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
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
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
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å.
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
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
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.