Question: Why Javascript $(document.body) does not load outside of the source file?

Question

Why Javascript $(document.body) does not load outside of the source file?

Answers 1
Added at 2016-12-30 00:12
Tags
Question

First of, a quick word about my setup.

I have a global JS file common.js, where I store all commonly used functions. This file is bundled and set to load along with _Layout.cshtml view file.

Along with that, I have a view file, which generates an html object like following:

<a class="printreport" href="#" data-reporttype="8" data-certid="1111">Print</a>

Mentioned view file loads javascript source file through extended method

@section scripts {
    @Html.LoadVersionedJavascriptFile("~/location/sourcefile.js")
}

In order to optimize my code, I decided to write a snippet function, which will make every html object with "printreport" class run it

Inside source file:

$(function(){
    //other stuff

    //Every html object that has printreport as a class will run this function
    $(document.body).on('click', '.printreport', function () {

    //get reporttype data from object
    var reportType = $(this).data('reporttype');
    var link = $("#RootDirectory").val();

    switch (reportType) {
        //other cases
        case 8:     //Certification
            var certId = $(this).data('certid');        //Get certid data from object
            link += '/Reports/ReportPopUp.aspx?report=' + reportType + '&CertId=' + certId;
            break;
        }   
    //code
    });
});

Inside the source file, it responds and works as intended. However, if I try moving that snippet from the source.js into a global common.js (I confirmed that file is loaded during execution), it simply does not respond, and clicking on link does nothing:

Inside common.js file:

//declaration of global variables

$(document).ready(function () {

}

$(document.body).on('click', '.printreport', function () {
    //code
}

Structure of common.js file is as above, it is not encapsulated into anything.

My question is: Am I loading document.body part improperly? What could be the possible cause of such unresponsiveness?

Answers
nr: #1 dodano: 2016-12-30 01:12

You should move your click handler inside $(document).ready:

$(document).ready(function () {
    $(document.body).on('click', '.printreport', function () {
        //code
    }
}

$(document).ready is an event which fires up when document is ready and since your html is interpreted from top to bottom, your elements could not be present when your jQuery code runs ($(document.body)).

Source Show
◀ Wstecz