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)');
    });
</script>

get clicked element

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

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

        $('#modal_food_description').text(foodDescription);
        $('#modal_food_image').attr('src', '../../Content/images/' + foodName + '_med.jpg').attr('alt', foodName);
        $('#modal_food').modal();
    });
})
</script>

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.


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

to be continued…

my jQuery tips

jQuery basics

This is the summary of “Fundamentals of Great jQuery Development”, which is available at http://vimeo.com/18511621.

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) {
    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.

constructor
“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.
f.member1
var f = Animal(); // this makes breed and smellsLike global scope, possibly overriding other breed.

Scope
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';
}(window))

this

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.
}
foo.call({ hi: 'test' });
foo.call({ hi: 123 });

Closure
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.
jQuery basics

show ajax loader image while making ajax request with jquery

You will need an image, first. Go to ajaxload.info 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..."/>
</div>

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

<style>
div#spinner
{
    display: none;
    width:100px;
    height: 100px;
    position: fixed;
    top: 50%;
    left: 50%;
    text-align:center;
    margin-left: -50px;
    margin-top: -100px;
    z-index:2;
    overflow: auto;
}    
</style>

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

<script type="text/javascript">
    $('#spinner').ajaxStart(function () {
        $(this).fadeIn('fast');
    }).ajaxStop(function () {
        $(this).stop().fadeOut('fast');
    });

</script>

Reference: http://stackoverflow.com/questions/807408/showing-loading-animation-in-center-of-page-while-making-a-call-to-action-method

show ajax loader image while making ajax request with jquery

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 () {
    $.ajax({
        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)
    {
        filterContext.HttpContext.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
        filterContext.HttpContext.Response.Cache.SetValidUntilExpires(false);
        filterContext.HttpContext.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
        filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        filterContext.HttpContext.Response.Cache.SetNoStore();

        base.OnResultExecuting(filterContext);
    }
}

On controller, you just add the attribute.

[NoCache]
[HttpGet]
public ActionResult MJobsB(int cId, int? pg)
{
    return RenderJobListIn("_MJobsB", cId, Mode.List, pg, false);            
}
Disable browser cache for ajax request on ASP.NET MVC