Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

Part 87 - What is Unobtrusive JavaScript

Suggested Videos 
Part 84 - Compare attribute
Part 85 - Enable client side validation
Part 86 - ValidationSummary in asp.net mvc



What is Unobtrusive JavaScript?
Unobtrusive JavaScript, is a JavaScript that is separated from the web site’s html markup. There are several benefits of using Unobtrusive JavaScript. Separation of concerns i.e the HTML markup is now clean without any traces of javascript. Page load time is better. It is also easy to update the code as all the Javascript logic is present in a separate file. We also get, better cache support, as all our JavaScript is now present in a separate file, it can be cached and accessed much faster.



Example:
We want to change the backgroundColor of "Save" button on "Edit" view to "Red" on MouseOver and to "Grey" on MouseOut.

First let's look at achieving this using obtrusive javascript.
Step 1: Implement MouseOver() and MouseOut() functions
<script type="text/javascript" language="javascript">
    function MouseOver(controlId) {
        var control = document.getElementById(controlId);
        control.style.backgroundColor = 'red'
    }

    function MouseOut(controlId) {
        var control = document.getElementById(controlId);
        control.style.backgroundColor = '#d3dce0'
    }
</script>

Step 2: Associate the javascript functions with the respective events.
<input id="btnSubmit" type="submit" value="Save" 
    onmouseover="MouseOver('btnSubmit')" onmouseout="MouseOut('btnSubmit')" />

Now let's look at making this javascript unobtrusive, using jQuery
Step 1: Right click on the "Scripts" folder in "Soultion Explorer", and add a jScript file with name = "CustomJavascript.js"

Step 2: Copy and paste the following code in CustomJavascript.js file.
$(function () {
    $("#btnSubmit").mouseover(function () {
        $("#btnSubmit").css("background-color", "red");
    });

    $("#btnSubmit").mouseout(function () {
        $("#btnSubmit").css("background-color", "#d3dce0");
    });
});

Step 3: Add a reference to CustomJavascript.js file in Edit view.
<script src="~/Scripts/CustomJavascript.js" type="text/javascript"></script>

Step 4: Remove the following obtrusive Javascript from "Edit" view
<script type="text/javascript" language="javascript">
    function MouseOver(controlId) {
        var control = document.getElementById(controlId);
        control.style.backgroundColor = 'red'
    }

    function MouseOut(controlId) {
        var control = document.getElementById(controlId);
        control.style.backgroundColor = '#d3dce0'
    }
</script>

Also, remove "onmouseover" and "onmouseout" events from the button control.
<input id="btnSubmit" type="submit" value="Save" 
    onmouseover="MouseOver('btnSubmit')" onmouseout="MouseOut('btnSubmit')" />

No comments:

Post a Comment

It would be great if you can help share these free resources