Invoking a function from an external JavaScript file

Looking for a way to call a function from an external JavaScript file?

Here are the specifics:

  • Within the head tag, include the following script:

<script type="text/javascript" src="JScript/FontSize.js"></script>

  • The FontSize.js file you want to call contains these functions:

    function checkCookie()
    
    function setCookie(c_name, value, expiredays)
    
    function getCookie(c_name)
    
    function increaseFontSize()
    
    function decreaseFontSize()
    
  • The FontSize.js is located in the ~/Jscript/ directory

To make the call to the function from the external JavaScript file, include something like this in the body onload attribute:

<body onload="/JScript/Fontsize.js/checkCookie()">

If things aren't working as expected, it could be because of how the call to a function in an external JS file is made.

Answer №1

You can simply refer to it as if it is local :)

<body onload="checkCookie()">

Alternatively, you can handle it in a script:

window.onload = checkCookie;

When you define a function without being within another object or namespace, it becomes globally accessible. You can call it as if it was defined right before your current code. By default, these functions will be associated with the window object. You can view a short demonstration here.

For instance (it doesn't matter where this function is defined, whether internal or external):

function myFunc() { alert('hi'); }
myFunc();
window.myFunc(); // same invocation, unless there's another myFunc in a more immediate scope

Answer №2

  <html>
        <head>
            <script type="text/javascript" language="javascript" src="app.js"></script>
        </head>
        <body>

    <!--The included app.js file contains xyz() function.. -->
            <script>
              <!--    xyz(); -->
            </script>
        </body>
    </html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a JSON representation of a complete graph from NEO4J using JavaScript

I am having trouble finding a complete working code example for apoc.export.json.data. It seems like the MATCH query could be used to retrieve any graph: MATCH g=(someNode)-[someRel]-() RETURN g CALL apoc.export.json.data( g ) Hopefully, this APOC functi ...

React table row render error

I am facing an issue with my React code: var PostRow = React.createClass({ render: function(){ var loading = <tr><td>one row</td></tr>; return( {loading} ) } }); An error message is bein ...

Identify when an ajax request is completed in order to trigger a subsequent ajax request

Within my project, I am faced with a challenge involving select option groups that dynamically load ajax data based on previous selections. The issue arises when I attempt to replicate this functionality for another select option group. Here is the scenar ...

Unexpected event in Coffeescript and Express framework: a tangled web of mysteries

Currently, I am working on developing an app using Express.js and Coffeescript. My code can be found here: https://github.com/findjashua/contactlist However, upon trying to run the application, I encounter the following error: app.coffee:11:24: error: un ...

How to Call a Nested Object in JavaScript Dynamically?

var myObj = { bar_foo : "test", bar : { foo : "hi there"; }, foo : { bar : { foo: "and here we go!" } } } How can we achieve the following: var arr = [["bar", "foo"], ...

How can I create a full screen button in WebGL with HTML and JavaScript?

How can I create a WebGL full screen button using HTML and JavaScript? I've done multiple searches on this topic but couldn't find a suitable solution. However, I did manage to find a button that works for putting my page in full screen mode. &l ...

Having trouble accessing the properties of an undefined variable (reading 'VSCODE_TEXTMATE_DEBUG')

Encountering an error while attempting to use Shiki in Nuxt3. The cause is unknown, even after trying to add the environment variable with no success. Here's a recreation of the error: https://stackblitz.com/edit/github-whzftm?file=pages%2F%5B...slug ...

The `res.download(filepath)` function seems to be failing to initiate a download request on the user's

I'm currently working on a project involving image compression using node and react. The issue I'm facing is that when the server sends the image to the client using res.download(filepath), the download doesn't trigger on the client side. Ho ...

Ways to transfer update panel data to an Excel spreadsheet

<asp:UpdatePanel ID="updatePanel" runat="server"> <ContentTemplate> <table>......Lots of data......</table> <asp:Timer ID="timerAutoRefresh" runat="server" OnTick="timerAutoRefresh_Tick"> ...

My goal is to display the information retrieved from my AJAX response within my jQuery data table

I am attempting to display my AJAX response in a jQuery data table. The structure of my table is as follows: <div style="margin: 20px;"> <table id="example" class="display" style="width:100%"> ...

Creating unique jQuery objects by comparing specific object properties

I am looking to create an array of unique objects by removing duplicate objects with specific property values. For example, consider the following code snippet where event1 and event2 have identical titles and start values, while event3 and event4 share th ...

Get the image data from a Nuxt 3 REST API endpoint

I've developed a straightforward API that fetches an image, performs transformations on it, and is supposed to return the modified image. Currently, I can only return a base64 string representation of the image. However, I'm unsure how to return ...

Saving IConfiguration in the latest version (Microsoft.Framework.ConfigurationModel in Asp.Net Mvc 6.0.0-beta4)

Our current approach involves: private Configuration _configuration = new Configuration(); We then retrieve parameters from a file using: SomeConfig= _configuration.Get<string>("SomeConfig"); Afterwards, we update these variables, potentially ch ...

Ways to ensure certain code is executed every time a promise is resolved in Angular.js

Within my Angular.js application, I am executing an asynchronous operation. To ensure a smooth user experience, I cover the application with a modal div before initiating the operation. Once the operation is complete, regardless of its outcome, I need to r ...

Angular - the utilization of expressions in view templates

Exploring Angular for the first time and attempting to create a Single Page Application (SPA). I have included the route module, which seems to be functioning properly. However, the templates are not interpreting Angular expressions as expected - for examp ...

Obtaining a Comprehensive Response (not limited to just the body) through Angular 4 HTTP Requests

I am currently working on getting a full response from my HTTP calls. Following the guidelines in the Angular documentation, I have set my HTTP call options as {observe: 'response'} However, when I implement this, I encounter the following error ...

How can I refresh a DataList that is bound to a database in ASP .NET?

My website features a DataList connected to an SQLDataSource that retrieves a stored procedure value representing the maximum identity value within a table. In addition, I have a DetailsView on the same page for adding new records to the table. The issue ...

Understanding the method of recovering a nested promise

I am facing an issue with returning the result parameter from the getColumn function. Despite my attempts, it keeps logging as undefined. The connection function establishes a connection to a SQL database and retrieves a data set through a query. Is ther ...

jquery detecting changes and enabling readonly attribute

I need to trigger an event with the "on change" functionality for a read-only input using jQuery. After that, I want to add some HTML content below it. Essentially, whenever the read-only input is modified, the HTML code should be appended. Please take a ...

Tips for creating a toggle menu using JavaScript

I am trying to create a toggle menu using CSS and JavaScript, but I have encountered an issue where clicking on the bars displays the navbar, but then the bars disappear and there is no option to close the navbar. <a href="#" class="fas ...