my jQuery tips

A collection of jQuery examples and tips

adding background image to an element

<script type="text/javascript">
    $(function () {
        $('.hero-unit').css('background-image', 'url(/Content/images/sky.jpg)');

get clicked element

<script type="text/javascript">
$(function () {
    $('.thumbnail').click(function (e) {

        var foodName = $(this).attr('data-food-name');
        var foodDescription = $(this).attr('data-food-description');

        $('#modal_food_image').attr('src', '../../Content/images/' + foodName + '_med.jpg').attr('alt', foodName);

Selecting an element with multiple classes

When you select an element with a class you do $(‘.claasname’). Then how would you do with multiple classes? you add the additional class without space.

$('').attr('class', 'item');

to be continued…

jQuery basics

This is the summary of “Fundamentals of Great jQuery Development”, which is available at

javascript is a functional language, not in a useful way, but because it treats function as its first-class citizen. It is also Object-oriented language, as it treats everything as object.

function declaration
This is what people use most of the time.

function foo(p1) {

function expression
This doesn’t have name and is anonymous.

foo(function () {});

function expression with name

foo(function f1(), "test" {});

json literals

var o = {
    foo: 1,
    bar: "test",
    alpha: {
        damian: function () { }

Here o is an object.

“new” means you create a new object based on its protytype.
If you mean a class, capitalise the first letter as convention.

function Animal() {
    this.breed = "domestic tabby";
    this.smellsLike = "candy";
Animal.prototype = {
    member1: function() { },
    member2: ""

var f = new Animal(); // create a new animal based on the prototype.
var f = Animal(); // this makes breed and smellsLike global scope, possibly overriding other breed.

In javascript, a variable’s scope is function-level. A variable is accessible within a function, even though it is declared within a block

function () {
    var i = 0;
    for (var j = 0; j <= 10; j++) {
        var x = 'test'; 
    x = 20; //this x is visible outside of the for block
x = 20: // x is not visible outside of function

Global variable or function is bad, because you cannot guarantee that only your javascript would run in the browser. You have multiple javascript from 3rd party, grease-monkey plugins, …

So, don’t declare a function in the global scope. Instead, create anonymous function and immediately execute it.

(function() {
    var i = 'test'; //as long as you use 'var', it is safe.
    this.alert('hi'); // this is global window

//If you want to pass window object
(function (w) {
    var i = 'test';


function foo() {
    this //this is an global object

function Foo() {
    this // not an global object, but this function.
var f = new Foo();

//this can be resued depending on the context.
function foo() {
    alert(this.hi); //In this case, this becomes the function, not global.
}{ hi: 'test' });{ hi: 123 });

A closure is a function that references a variable that isn’t contained within its own immediate scope.

// this variable is out of the scope;
function foo() {
    var myVar = 1;

    return function() { 
        return myVar.toString();

var myFunc = foo();
myFunc(); //This access myVar, which is outside of the function boundary. This looks trivial, but event handler takes advantage of closure.

show ajax loader image while making ajax request with jquery

You will need an image, first. Go to and get one you like.

Put the html for the loader in the page.

<div id="spinner">
    <img src="/jobadmanager/Content/images/ajax-loader-big.gif" alt="Loading..."/>

Style the div element to position it on the centre of the browser.

    display: none;
    height: 100px;
    position: fixed;
    top: 50%;
    left: 50%;
    margin-left: -50px;
    margin-top: -100px;
    overflow: auto;

Now, use javascript to fade it in and out, when an ajax request starts.

<script type="text/javascript">
    $('#spinner').ajaxStart(function () {
    }).ajaxStop(function () {



Disable browser cache for ajax request on ASP.NET MVC

The application reloads the list of jobs, if any job is reposted or expired. We display different labels, such as “reposted”, “expired”, depending on the action. It worked well with browsers but IE 8.

Simply, IE was cacheing the part of html. Though we request the partial view by post.

update: function () {
        type: "GET",
        url: "MJobsB?p=" + list.cPg(),
        contentType: "text/html; charset=utf-8",
        dataType: "html",
        success: function (data) {
            $('#ct #cnt').html(data);
        error: function () { alert("Error Loading Jobs"); }

So, we brought in NoCache attribute. And made the action not cached on IE. We made it with attribute, as we want to cache other stuff, especially images.

This is NoCache attribute.

public class NoCacheAttribute : ActionFilterAttribute
    public override void OnResultExecuting(ResultExecutingContext filterContext)


On controller, you just add the attribute.

public ActionResult MJobsB(int cId, int? pg)
    return RenderJobListIn("_MJobsB", cId, Mode.List, pg, false);