Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alert Message with external js file

Tags:

jquery

I have a external test.js file with code:

$(document).ready(function() {
    alert("I am an alert box2!");   
});


function show_alert()
{
    alert("hihi");
}

In my .html, I have included test.js, jquery file and there is a button. When click on it, show_alert() function will be called and it works. However, The message "I am an alert box2!" is not fired.
Also, if I put the document.ready function in my .html with <script>... </script>. It works. What wrong with my code? External file not support?

like image 738
red23jordan Avatar asked Jan 02 '12 14:01

red23jordan


3 Answers

One of the following:

  1. You have included test.js before jquery.js in your Head.
  2. You have an error that stops your javascript before it gets to the ready functions.
like image 169
Rodik Avatar answered Nov 11 '22 08:11

Rodik


It works for me,

Here the code:

function show_alert()
{
    alert("hihi");
}

$(document).ready(function() {
    alert("I am an alert box2!");

    $('.button').click(function() {
        show_alert();
    });
});

Put jQuery.min.js before test.js in your HTML code.

like image 2
Andrea Turri Avatar answered Nov 11 '22 08:11

Andrea Turri


You can keep the function testAlert in test.js. but, document.ready should be between script tag Only.

function testAlert(){
alert("I am an alert box2!");
}

Above function can be in test.js.

$(document).ready(testAlert); should be in script tag of present page to check the availabiliy of DOM.

Acutally, Above is not mandatory but ideal way to write jquery, because it helps to debug easily :)

like image 1
Umesh Patil Avatar answered Nov 11 '22 09:11

Umesh Patil