bzd91
bzd91

Reputation: 13

Javascript Function works inside HTML page but doesn't work from external .js file

I am trying to place some Javascript code inside a .js file so that I can call it from multiple HTML pages. The problem is, my Javascript code works fine if I place it in a script within the HTML page, but when placed in a external .js file, it simply does not work. I've looked at these questions quite a few times and still cannot find the error.

Here's the HTML page:

<html>
<head>
    <meta charset="utf-8" />
    <meta name="format-detection" content="telephone=no" />
    <meta name="msapplication-tap-highlight" content="no" />
    <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
    <link rel="stylesheet" type="text/css" href="css/global.css" />
    <link rel="stylesheet" type="text/css" href="css/contacts.css" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
    <script type="text/javascript" src="cordova.js"></script>
    <script type="text/javascript" src="js/index.js"></script>
    <script type="text/javascript" src ="js/contactsModule.js"></script>
    <title>Hall of Heroes</title>
</head>
<body onload = "contactsModule.getContacts();">



    <!-- Global Header Starts Here -->
    <div class="header">
        <div class="cancel">
            <img src="img/cancel.png" /><!-- if screen is triggered from onboarding, then go back to onboarding screen instead of home -->
        </div>
        <h1>My Contacts</h1>
    </div>

    <div class="wrapper">
        <h3>A</h3> <!-- letter header goes here -->

        <!-- Begin Contact Unit -->
        <div class="feed">

        </div>
        <!-- End Contact Unit -->

    </div>

   </body>

   </html>

And here is the .js file:

var contactsModule = (function($){

        function getContacts()
        {
            dbContacts();
        }

        function displayContacts(contactArray){
            window.alert('displayContacts now running!');
            var jsonObject = $.parseJSON(contactArray);
            jsonObject.forEach(function (dat) {
                //Begin Contact Unit
                $('.feed')
                    .append('<div class="feed-img"><img src="' + dat.avatarUrl + '"/>\
                    </div><div class="feed-text"><p><span class="name_highlight">\
                    ' + dat.firstName + ' ' + dat.lastName + '</span></p></div>');
                //End Contact Unit
            });
        }
        function dbContacts() {
            var avatarUrl;
            var firstName;
            var lastName;

            $.ajax({
                type: "GET",
                url: "http://www.hallofheroesapp.com/php/contacts.php",
                data: {avatarUrl: avatarUrl, firstName: firstName, lastName: lastName},
                success: function (response) {
                    window.alert('AJAX ran successfully!');
                    displayContacts(response);
                },
                error: function(response){
                    alert("Error:" + response);
                }
            });
        }
 }(jQuery));

Thank you for your help!

Upvotes: 0

Views: 1347

Answers (4)

user2628521
user2628521

Reputation:

Had the same problem. Easy thing when you research on google. Your Js code loads before the DOM loads. Which should be the other way around. So you have to use this

$(document).ready(function(){
  //only jQuery is recommended, global JavaScript functions outside!
});

Also JavaScript

document.addEventListener("DOMContentLoaded", function(event) {
  //global function outside! 
});

Only this way you can be sure that your DOM is loaded before your jquery finds your elements.

Upvotes: 0

Patrick Evans
Patrick Evans

Reputation: 42756

You aren't returning anything from your IIFE. contactsModule will then not contain anything, ie equal undefined. Also just defining functions doesn't make those functions part of some object, with the exception of globally defined functions. You have to assign them, or define them as part of an object literal

Your code should be something like

var contactsModule = (function($){
    return {
        getContacts: function() {
             /* code */
        },
        displayContacts: function(contactArray){
             /* code */
        }
        dbContacts function() {
             /* code */
        }
    };
 }(jQuery));

Upvotes: 2

Billy Moon
Billy Moon

Reputation: 58619

... change ...

<body onload = "contactsModule.getContacts();">

... to ...

<body>

... and add event handler using jquery ...

(function($){

        function getContacts()
        {
            dbContacts();
        }

        /* ... etc ... */

        // use jquery's onready handler
        $(getContacts);

 }(jQuery));

Upvotes: 0

Jeffrey Coleman
Jeffrey Coleman

Reputation: 188

How about using

$(document).ready(function(){
     ///// your code here...

});

Upvotes: 0

Related Questions