Part 87 - What is Unobtrusive JavaScript

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')" />

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值