a developer's notes – a semi-technical web development BLOG

May 13, 2015

Javascript Namespace Function Expression Sample

Filed under: Javascript / JQuery — Duy Nguyen @ 12:05 pm
Tags: , ,

A sample of how to structure your JS file per page. This works good for organizational purposes and it will avoid name clashing.

var PageName = {

// define your functions as variables.
    bindCheckBox: function () {
        $("#mycheckbox").on("click", function () {

    enableConfirmButton: function (bool) {
        if (bool)
            $("#mybutton").attr("disabled", "disabled");

    checkboxClick: function () {
        if ($("#mycheckbox").is(":checked"))

// Start of document.ready in jquery
$(function () {
    // calling the global variable you created.

If you want to use an Immediately Invoked Function Expression (IIFE)

(function() {
     // This creates a function that invokes itself with NO GLOBAL FUNCTIONS.

January 22, 2014

JQuery doesn’t work with ASP.NET MVC 4 Application. $ is not defined

Filed under: ASP.NET MVC — Duy Nguyen @ 11:29 am
Tags: , , , , , , , ,

Why is JQuery Referenced In the Body Tag with a default ASP.NET MVC 4 Application?

In short, script loading and executing, blocks the rendering of a web page. So it is recommended to move script references in the body tag. So Microsoft decided to move the @Scripts.Render in the body tag as the default location for _Layout.cshtml. If you’re using jquery’s onReady() function in your View, make sure you declare your script tag within a scripts @section like this:

@section Scripts {
    <script type="text/javascript">

    $(function () { //Same as $(document).ready()

If you declare a traditional <script> tag outside of “@section Script{}” at either at the beginning or end of your View file, you will get an error, $ is not defined. This is because the _layout view calls @RenderBody() before the jquery script bundle.

But if you still want to declare your <script>tags and not use @section Script{}, for whatever reason, remember to comment out or delete the


reference in the body tag in the _Layout.cshtml file and move it to the head tag.

Here is a sample _Layout.cshtml.

<!DOCTYPE html>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    @Scripts.Render("~/bundles/jquery") @*--Need to move this to the <head> section otherwise you will get '$ is undefined.'*@

    @*-- Commenting out the default location because we are not using @section Scripts {} section. By default, Microsoft added all script rendering in the <body> tag for better performance. But this will only work if you define your script tags within @section Scripts {}.*@
    @RenderSection("scripts", required: false)

Create a free website or blog at WordPress.com.