admin管理员组

文章数量:1290956

Is it possible to call a function declared in a .js file from the body of the HTML. I'm assuming the reason it won't work is because the .js file is called after the function has been called in the HTML body. Is there a way around this.

I've had a look at some answers here, but can't seem to find what I'm looking for. My apologies if it's staring at me as a beginner I may not be using the correct terminology.

jqueryfunctions.js:

function someFunction() {
    // do.something;
}



index.html:

<html>
    <head>
     <script type="text/javascript" src="//code.jquery/jquery-1.8.3.js"></script>
    <script src="jqueryfunctions.js"></script>  
    </head>
    <body>
        <script>
            someFunction();
        </script>
    </body>
</html>

Here is the full/actual .js file returnedMessage() is the function I was reffering to as someFunction().

The console error I'm getting is "returnedMessage() is not defined".

$(function(){
    var timer = null;
    function appendmessageBox() {
        $('body').append('<div id="messageBox" class="datamessagebox"> </div> ');
    }
    // just before body tag.
    appendmessageBox(); 

    // makes MessageBox Disappear on MouseOver
    $('#messageBox').on('mouseover click', function(){
        $(this).fadeOut(300);
    });

    function returnedMessage(message) {
        if (timer) {
            clearTimeout(timer); //cancel the previous timer.
            timer = null;
        }
        $( '#messageBox' ).css('display', 'inline-block');
        timer = setTimeout(function(){ 
            $( '#messageBox' ).fadeOut( 499 );
        }, 5000);
        $( '#messageBox' ).append('<msg>'+message+'<br /></msg>').fadeIn( 200 );
        $( '#messageBox > msg:last-of-type' ).delay(3000).fadeOut( 3000 );
        setTimeout(function(){ 
            $( '#messageBox > msg:first-of-type' ).remove();
        }, 5999);
    }

            // This test message bellow works correctly.
            returnedMessage('hello world - test 1'); 


});

Is it possible to call a function declared in a .js file from the body of the HTML. I'm assuming the reason it won't work is because the .js file is called after the function has been called in the HTML body. Is there a way around this.

I've had a look at some answers here, but can't seem to find what I'm looking for. My apologies if it's staring at me as a beginner I may not be using the correct terminology.

jqueryfunctions.js:

function someFunction() {
    // do.something;
}



index.html:

<html>
    <head>
     <script type="text/javascript" src="//code.jquery./jquery-1.8.3.js"></script>
    <script src="jqueryfunctions.js"></script>  
    </head>
    <body>
        <script>
            someFunction();
        </script>
    </body>
</html>

Here is the full/actual .js file returnedMessage() is the function I was reffering to as someFunction().

The console error I'm getting is "returnedMessage() is not defined".

$(function(){
    var timer = null;
    function appendmessageBox() {
        $('body').append('<div id="messageBox" class="datamessagebox"> </div> ');
    }
    // just before body tag.
    appendmessageBox(); 

    // makes MessageBox Disappear on MouseOver
    $('#messageBox').on('mouseover click', function(){
        $(this).fadeOut(300);
    });

    function returnedMessage(message) {
        if (timer) {
            clearTimeout(timer); //cancel the previous timer.
            timer = null;
        }
        $( '#messageBox' ).css('display', 'inline-block');
        timer = setTimeout(function(){ 
            $( '#messageBox' ).fadeOut( 499 );
        }, 5000);
        $( '#messageBox' ).append('<msg>'+message+'<br /></msg>').fadeIn( 200 );
        $( '#messageBox > msg:last-of-type' ).delay(3000).fadeOut( 3000 );
        setTimeout(function(){ 
            $( '#messageBox > msg:first-of-type' ).remove();
        }, 5999);
    }

            // This test message bellow works correctly.
            returnedMessage('hello world - test 1'); 


});
Share Improve this question edited Jul 31, 2017 at 14:10 denski asked Jul 31, 2017 at 13:38 denskidenski 2,0404 gold badges23 silver badges41 bronze badges 11
  • 2 Have you tried your code? It is working... – Jonas Wilms Commented Jul 31, 2017 at 13:39
  • 1 What goes wrong? Yes you can do that; if you're having a problem you'll have to post the error(s) you're getting in order for anybody to help. – Pointy Commented Jul 31, 2017 at 13:40
  • Are jqueryfunctions.js and index.html in the same directory level? Check in your inspector tool under the Network if your JS file has been successfully loaded. – Ivan Commented Jul 31, 2017 at 13:57
  • @ivan they're not, but for the sake of this example I didn't include the /js/ directory. I can confirm they're working though – denski Commented Jul 31, 2017 at 14:07
  • Ok your code is working fine alone, are you sure the file is loaded? Something like that: image.ibb.co/jQyHKk/network.png – Ivan Commented Jul 31, 2017 at 14:13
 |  Show 6 more ments

3 Answers 3

Reset to default 4

EDIT:

you should define your function like so:

var someFunction = function() {

   // do something

}

Or like so

function someFunction() {

   // do something

}

But always use the function word. More information on function definition in Javascript.


More about JS file import

Javascript code is inserted between <script> tags in an HTML file

<script>
  console.log("Hello World!");
</script>

You usually place those script tags inside the <head> tag. However it's remended you put them after your <body>. This way you allow the DOM to load before you run your JS script. This is important for exemple when you want to select elements in the DOM. If you put the JS code before the actual HTML that creates this element, then JS will not find the element you would be looking for because it doesn't yet exist.

Now it's not really efficient to work with script in your HTML code so it's helpful to write JS in .js files and then import them in you HTML file like you would for a CSS file. Use the <script> to do so:

<script src="myScript.js"></script>

You can use multiple <script> tags to pull in multiple JS files. But you need to be careful of the order you write them. For instance you have a functions.js file that holds all your functions, and a menu.js that handles the menu on your application. You're using functions from the code functions.js in menu.js so you need to import the files in this order:

<script src="functions.js"></script>
<script src="menu.js"></script>

First declared, first loaded.

You can write own function like this:

Here you can see simple example: https://jsbin./munowupipo/edit?html,output

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Define a Function in jQuery</title>
<script src="https://code.jquery./jquery-2.1.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    $.fn.myFunction = function() { 
        alert('You have successfully defined the function!'); 
    }
    $(".call-btn").click(function(){
        $.fn.myFunction();
    });
});
</script> 
</head>
<body>
    <button type="button" class="call-btn">Click Me</button>
</body>
</html>          

Maybe you want to take the function on document is ready, so you must to write:

<script>
$(document).on("ready", function() { yourfunction(); });
</script>

本文标签: javascriptCall function in js file from htmlStack Overflow