Wednesday 5 March 2014

jQuery: How to use JavaScript/jQuery with ASP.NET Master Page

At first check javascript is enable on your computer.
The proper way to use the javascript in ASP.NET Master page:

In the Site.Master page, add reference to javascript file in the HeadàPlaceHolder section:

<asp:PlaceHolder runat="server">
        <%: Scripts.Render("~/bundles/modernizr") %>
        <script type="text/javascript" src="scripts/JavaScript-local.js"></script>
        <script type="text/javascript" src="scripts/jquery-1.10.2.min.js"></script>
           <script type="text/javascript" src="jquery-1.10.2.js"></script>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</asp:PlaceHolder>

In the body section, call the JavaScript function or write the JavaScript function using the script tagIf you want to call the javascript script from the normal <script type="text/javascript">
             $(document).ready(function () {
                 alert("Job done.");
             });
        </script>e, just add them inside the asp:content section:

<body>
    <form runat="server">
        <script type="text/javascript">
            $(document).ready(function () {
                changeASPMenuColor();
            });
        </script>
       <nav>
                <ul id="navigation">
                    <li><a href="Default.aspx">Home</a></li>
                    <li><a href="BusinessConsultancy.aspx">Business consultancy</a></li>
                    <li><a href="MarketingConsultancy.aspx">Marketing consultancy</a></li>
                    <li><a href="StudentConsultancy.aspx">Student consultancy</a></li>
                    <li><a href="ITConsultancy.aspx">How it works</a></li>
                    <li><a href="Contact.aspx">Contact</a></li>
                </ul>
            </nav>



Now in the javascript file, create the function to change the color of the selected menu item.

function changeASPMenuColor()
{
   
    //$("ul#navigation li:eq(0) a").click(function (event) {
    //    event.preventDefault();
    //    var car = $("nav ul#navigation li:eq(0) a").attr("href");
    //    alert(car);
    //});
    // store url for current page as global variable
    current_page = document.location.href;
    // apply selected states depending on current page
//g is switch for search continuing after first match, i is switch for case-sensitive //search
    if (current_page.match(/Default/gi)) {
        $("ul#navigation li:eq(0)").addClass("active");
    }
    else if (current_page.match(/Business/)) {
        $("ul#navigation li:eq(1)").addClass("active");
    }
    else { // don't mark any nav links as selected
        $("ul#navigation li").removeClass("active");
    };

}

No comments:

Post a Comment