Creating your own customizable tabs / carousel plugin for jQuery

Yesterday I was browsing the web for a tabs or carousel plugin for jQuery that fitted my needs. I wanted a simple but highly customizable control for displaying tabs which could also automatically page like a carousel. I found a lot of different plugins for JQuery but none fitted my exact needs. So I created my own in only 17 lines of javascript. this blog post describes how I did it and how you can use it on your website.

 

first of all of course is a demo. You can can check it here: http://www.vdcruijsen.net/demo/jquerycarousel/carouseldemo.html

so how does this work? We’ll start with the HTML used for the carousel:

<div id="carousel">

    <div class="carouselbody">

        <ul class="carouselcontainer">

            <li class="page"><div style="width:400px; height:300px; background-color:Green">test tab 1</div></li>                           

            <li class="page"><div style="width:400px; height:300px; background-color:Red">test tab 2</div></li>                           

            <li class="page"><div style="width:400px; height:300px; background-color:Orange">test tab 3</div></li>                           

            <li class="page"><div style="width:400px; height:300px; background-color:Blue">test tab 4</div></li>

        </ul>

    </div>

    <ul class="pager">

        <li><a class="pagerpage" href="#">&nbsp;</a></li>

        <li><a class="pagerpage" href="#">&nbsp;</a></li>

        <li><a class="pagerpage" href="#">&nbsp;</a></li>

        <li><a class="pagerpage" href="#">&nbsp;</a></li>

    </ul>

</div>

The HTML is actually pretty easy, The first div is a container with an id called carousel so the script knows what belongs to the carousel and what not. you can set a height and width on this div to size your carousel. The carousel div contains 2 main parts. the carouselbody a container for all the carousel pages and the pager where you can define your pager links. this pager can also be put before the carouselbody if you want the pager or tabs above your pages.

The carouselbody has a unordered list containing all the actual pages. all the list items are shown have a css class called page so the script knows that inside is the content for a page. in the list item I’ve put some div with inline styling to show that you can put whatever you want inside this page list item.

the pager has links which have a pagerpage class. the script will automatically match the first available pagerpage link to the first page etc.

Below is the css I used in the demo. you can customize this to set pictures for the paging mechanism or set heights, colors etc. this current css is just an example. (some display elements are needed though, its best to start of with the supplied css and change it to your likings.)

#carousel { height: 400px; overflow:hidden; }

#carousel .carouselbody { float: left; width: 400px; height: 360px; overflow: hidden; position: relative; background-color:#212020;}

#carousel .carouselcontainer { list-style: none; padding: 0px; margin: 0px;  position: absolute; left: 0; top: 0; }

#carousel .carouselcontainer li{ float: left; margin: 0px ; border-width: 0px;}

 

#carousel .pager { overflow:hidden; list-style: none; clear: both; }

#carousel .pager li { float: left; }

 

#carousel .page

{

    display:none;

}

 

#carousel .currentpage

{

    display:block;

}

 

#carousel .pagerpage

{

    margin-left:2px;

    background-image:url('/Content/images/pager2.png');

    width: 20px;

    height: 20px;

    display:block;

    text-decoration:none;

}

#carousel .currentpagerpage

{

    background-image:url('/Content/images/pager.png');

    text-decoration:none;

}

 

So now the HTML and CSS is explained its on to the actual jQuery script which makes all this magic happen. You only need 1 line to change a div to a working carousel if you also include the other script pieces somewhere on the page. the line to add in your script that is executed on document.ready is the following:

$("#carousel").carousel();

 

this method will of course only work if the carousel method is available. This is added through the following code:

$.fn.carousel = function (options) {

    var defaults = {

        start: 0

    };

    var options = $.extend(defaults, options);

 

    $(this).find(".page:eq(" + (options.start) + ")").addClass("currentpage");

    $(this).find(".pagerpage:eq(" + (options.start) + ")").addClass("currentpagerpage");

 

    $(this).find(".pagerpage").bind("click", function () {

        $(this).parents(".pager").find(".currentpagerpage").removeClass("currentpagerpage");

        $(this).parents("#carousel").find(".currentpage").removeClass("currentpage");

        $(this).addClass("currentpagerpage");

        var index = $(this).parent().index();

        $(this).parents("#carousel").find(".page:nth-child(" + (index + 1) + ")").addClass("currentpage");

    });

};

 

the $.fn.carousel line makes the carousel method available in the rest of your jQuery code. I’ve added some options as an example to make the carousel start at a different page.

the first thing the script does is searching for the page on which it should start and adds the currentpage css class to this page so the page becomes visible. The script does the same for the active pager item.

after this the script binds click events to the pager links so the pager links can do their work when they are clicked. on each click event the current page is made invisible by removing the currentpage css class and after it puts the current page css class on the newly selected page.. that’s all :)

 

Hopefully this code is something you can use on your own website or otherwise learn from it or use pieces of it.

 

Geert van der Cruijsen

Share on Facebook
Kick It on DotNetKicks.com
Shout it
Post on Twitter

Virtual conference MVCConf 2011

Yesterday MVCConf 2011 was held. MVCConf is a virtual conference about ASP.NET MVC and since ASP.NET MVC 3 has shipped a few weeks ago there was a lot to talk about. The conference is organized by the community and there are a lot of speakers from the Community as well as from Microsoft.

Some videos are online already at www.mvcconf.com/live but all videos are coming online later at the www.mvcconf.com site.

Since I’m an ASP.NET MVC fanatic I’ve used my free evening to watch the sessions and will view more tomorrow.

mvcconf

Sessions I watched:

Keynote by Scott Guthrie @scottgu

Scott talked about the history of ASP.NET MVC 3 and the older versions (ofcourse everyone knows he wrote version 1 during a single flight from his home to some conference a few years ago) and held an interactive session where people could ask questions using twitter. He talked about the difference of webforms and mvc ofcourse since this is a question that is always asked when talking about mvc on a high level. He noted again that webforms, webmatrix and MVC will all exist next to each other in the future and serve different purposes. to make this more clear he gave 3 keywords for all methods of building ASP.NET applications

WebMatrix

  • Simple
  • Light
  • Fast

Web Forms

  • Familiar
  • Reusable
  • Productive

MVC

  • Powerfull
  • Extensible
  • Agile

Other things he talked about is the focus of Microsoft on JQuery. Microsoft added JQuery to the MVC 1.0 and in 3.0 they even switched completely to JQuery when you look at all examples etc. Microsoft is also actively helping in creating a new JQuery plugin for the JQuery Datatable. this is something I would really like to see!!

Scott also told us about project Orchard which is a new open source CMS project by Microsoft. this is also looking really promising. Another thing Scott talked about really quick was an Asset management system for CSS and JS functions / snippets. more to come about this in the future. (he wasn’t supposed to say anything about this.)

Finally he talked about large sites running ASP.NET MVC. He couldn’t tell a lot about this since he didn’t know which company liked him saying their technology choices. but some examples he did tell were bing.com and other microsoft sites. other examples people on twitter added are the channel 9 site, stackoverflow.com and cheezburger.com :D

Phil Haack on nuget @haacked

Phil talked on Microsoft opensource project nuget by showing how you use it in visual studio using the extension manager and the console. I think most people have already seen and used nuget but this session went deeper. phil showed us how to create packages and how to use advanced functions the console. Something that was new to me he showed us is the local repository you can add in nuget. I’m going to have another look at this later so we can use it within our company.

after this he showed us how nuget is working under the hood. All in all a really nice session for me.

Brad Wilson on “Advanced MVC 3.0” @bradwilson

Brad talked on some advanced topics of MVC 3.0. It’s hard to do a recap on this one since it’s a lot of stuff. some things were really interesting. he started off with statefull filters to show how to use filters per request, per session or per applications. after this he talked about validation with unobstructive Ajax with Jquery. very interesting!!

He also talked about how to use different kinds of objects as classes for your model and about routing constraints.

If you are a more advanced MVC developer this is a session you shouldn’t miss.

Steve Sanderson on MVC Scaffolding @stevesanderson

Steve talked about the opensource project MVC Scaffolding. The original idea for this came from the Ruby community where people wanted to generate simple crud forms and the database itself from the model classes. Steve has created a package which you can get with nuget to have this in ASP.NET MVC 3.0.

Phil showed a quick sample of this on his nuget presentation and Steve also showed an example where he automatically generated everything using the repository pattern so you get a nice decoupled scenario without typing any code. after this he showed more complex situations. for more info check this blogpost:

http://blog.stevensanderson.com/2011/01/13/scaffold-your-aspnet-mvc-3-project-with-the-mvcscaffolding-package/

Other sessions I haven’t watched yet but will do later are:

BDD in ASP.NET MVC using SpecFlow, WatiN and WatiN Test Helpers by Brandon Satrom

Quality Driven Web Acceptance Testing by amir Barylko

WebMatrix by Rob Conery

Entity Framework “Code First”: Domain Driven CRUD by Chris Zavaleta

I really enjoyed the sessions. MVCConf and all speakers thanks and hopefully I’ll be able to join MVCConf 2012 again next year.

When all video’s are up I’ll edit the post with the links to the videos

Geert van der Cruijsen

Share on Facebook
Kick It on DotNetKicks.com
Shout it
Post on Twitter

SharePoint Automatic prefilling of lookup fields in insert forms using JQuery

At my last project I was working on a SharePoint online solution and one of the requirements is to prefill some values at one of the insert forms for a list. Since this is SharePoint online and the only tool you can use to customize is SharePoint Designer I had to do this with JavaScript.

I’ll explain how to build it by an example. for example you have a list of customers and a list of customer actions. What I wanted to build was a way to make it easier to add a customer action for a specific customer. To do this I added a custom column to the customer list containing a link to the edit form with the customer id as an url variable. Of course the out of the box you can’t create links or any other html with calculated fields so I added more javascript there.

to enable html as output of a calculated field just copy this piece of javascript and put it in a content editor webpart or paste it on your master page.

var theTDs = document.getElementsByTagName("TD"); 

var i=0; 

var TDContent = " "; 

while (i < theTDs.length)

{ 

  try

  { 

    TDContent = theTDs[i].innerText || theTDs[i].textContent; 

    if ((TDContent.indexOf("<DIV") == 0) && (TDContent.indexOf("</DIV>") >= 0))

    { 

      theTDs[i].innerHTML = TDContent; 

    } 

  } 

  catch(err){} 

  i=i+1; 

} 

Thanks Marijn Somers for this piece of code. original source: http://marijnsomers.blogspot.com/2010/01/write-html-code-in-sharepoint-via.html

so now my calculated field was a link in html. what did my calculated field look like?

="<DIV><a href=’../../Lists/CustomerActions/NewForm.aspx?Customer="&[Customer ID]&"’>Add Customer Action</a></DIV>"

First a DIV element since the javascript above only replaces elements starting with a <DIV> to html, then just a plain html link to the NewForm.aspx sending the customer id as an url parameter.

 

So now the changes in the customer list are done and we only need to add some more javascript at the NewForm.aspx or again just at your masterpage to get the parameter from the url and selecting the right lookup field value at the form.

I’ve created the following code  using Jquery:

var customer = $.getUrlVar("Customer");

 

if(customer != "")

{

  $("input[title='Customer']").val(customer);

  

  $("select[title='Customer']").children("option").each(function() {

    if($(this).text() == customer)

    {

      $(this).attr('selected', 'selected'); 

    }

  });

}

My customer actions list contained a Customer field which is a lookup to the Customer list by Customer ID. The script above gets the Customer ID from the url parameters first and then tries to set the lookup item. SharePoint renders lookup items in 2 different ways. as a select box when there are less then +/- 25 items and as a auto complete textbox when there are more then 25 items in the lookup list. Because of that I firs try to set the textbox to the right value and after that the select. I’m using the title attribute to locate the right input field because it gets the same name as the field from SharePoint by itself.

Now when I open the newform.aspx?customer=1234 my customer lookup field is automatically prefilled with 1234

 

Geert van der Cruijsen

Share on Facebook
Kick It on DotNetKicks.com
Shout it
Post on Twitter

Combined power of SharePoint and JQuery part 2: Changing the SharePoint webpart edit menu position

Have you ever had the problem using SharePoint 2007 that when you create small webpart zones that the edit button disappeared because the title of the webpart was to long? I ran into this problem at my current project and instead of shortening down the titles i came up with the idea of changing the position of the edit button to be on the left of the title. when the button is on the left and the title is on the right the title will be trimmed automatically since the webpart zones have a fixed length.

In your server side code it’s really hard to change these kinds of things because this is standard SharePoint functionality and you can’t change it server side. So the solution is to fix it using javascript and to make that easier I’m using JQuery.

first I’ll show you the results below and then how I did it using a small JQuery script.

before:

sharepointjquery1

after:

sharepointjquery2

Below is the JQuery script to change the position of the edit menu to the left. the only thing you have to do is save this code to a js file, include the reference to the js file and a reference to the JQuery library js file on your masterpage and you’re done.

   1: $(document).ready(function() {

   2:     SPEditMenuFix();

   3: });

   4:  

   5: function SPEditMenuFix() {

   6:     $(".ms-WPHeader").each(function() {

   7:         var first = $(this).children("td:first").clone(true);

   8:         var last = $(this).children("td:last").clone(true);

   9:         $(this).children("td:first").replaceWith(last);

  10:         $(this).children("td:last").replaceWith(first);

  11:     });

  12: }

Enjoy!

Geert van der Cruijsen

Share on Facebook
Kick It on DotNetKicks.com
Shout it
Post on Twitter

Combined power of SharePoint and JQuery part1: Changing the SharePoint Image Picker

Wow… long time since i blogged. Thank god I’m going to the Dutch DevDays to see Scott Hanselman’s session called “How to make your blog suck less” :)

So here is an update of mine about how to use JQuery in SharePoint to do some fancy tricks. I’ll post some more of these tricks later on and I’ll try to be more active as a blogger again. (In which I’ll probably fail)

Have you ever tried to change some of SharePoint’s default controls like the image picker?

Well I have. My customer wanted a image picker that worked exactly like the normal one except for 1 change. It shouldn’t show the selected image as an image but it should only show the URL of the selected image. I tried to change this at server side first by inheriting from the default SharePoint image picker control. This was a rather annoying job as i didn’t seem to get the right result this way. you cannot extend the rich image picker from sharepoint but only the default image picker that doesn’t have the image library function behind it.

When i was looking at the html that was rendered by SharePoint i thought it would be easier to change the html with jquery as with serverside code and this is the result. just save this source to a .js file and include it into your masterpage or aspx page and all selected images in the image picker will be changed to only show the url of the image.

///<reference path="jquery-1.3.2.min-vsdoc.js" />

 

$(document).ready(function() {

    HideImages();

});

 

function HideImages() {

    $("span[id $= '_RichImageField_ImageFieldDisplay']").each(function() {

        var url = $(this).find("img").attr("src");

        $(this).find("a").hide();

        $(this).append("<span class='imgurl'>" + url + "</span>");

        $(this).find("a").each(function() {

            $(this).find("img").each(function() {

                $(this).load(function() {

                    $(this).parent().hide();

                    var imgurl = $(this).attr("src");

                    $(this).parent().parent().find(".imgurl").text(imgurl);

                });

            });

        });

    });

}

It’s as easy as that.

More JQuery fun to post in the future.

Geert van der Cruijsen

Share on Facebook
Kick It on DotNetKicks.com
Shout it
Post on Twitter