Count list items with JavaScript

The following JavaScript code can be used to count the list items and visualize the number on a dashboard page.

This can only be done in SharePoint 2010 by using the build-in JavaScript framework.

ExecuteOrDelayUntilScriptLoaded(CountProjecten, "sp.js");
var clientContext = null;
var web = null;

function CountItems()

clientContext = new SP.ClientContext.get_current();
web = clientContext.get_web();
var list = web.get_lists().getByTitle("Project");
var camlQuery = new SP.CamlQuery();
var q = "<View><Query><Where><Eq><FieldRef Name='Status' LookupId='True' /><Value Type='Lookup'>3</Value></Eq></Where></Query></View>";
this.listItems = list.getItems(camlQuery);
clientContext.load(listItems, 'Include(Opleiding,Title)');
clientContext.executeQueryAsync(Function.createDelegate(this, this.onListItemsLoadSuccess), Function.createDelegate(this, this.onQueryFailed));

function onListItemsLoadSuccess(sender, args) {
var count = 0;



    function onQueryFailed(sender, args) {
alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace());

Note that the count is done asynchronously so it can take a moment (depending on the amount of items in the list) before you see the result.