您的位置:首页 > Web前端 > JavaScript

Part 87 - What is Unobtrusive JavaScript

2016-11-13 12:23 225 查看
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')" />
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: