Ways to access a global JavaScript object in a separate .js file

How can I access an object that was initialized in my HTML document?

This is what my HTML document looks like:

    ...

<script type="text/javascript" id="controller">var controller = false;</script>

    ...

<body onload="controller = new CTRLclass()">

    ....

What is the best way to call controller.doAMethod() in an external JavaScript file using DOM operations or similar techniques?

Edit: Hey everyone, I have multiple .js files and my controller creates an instance of another class in its constructor. In this newly created instance of the class, I need to access the controller in order to call an update function. For example: The controller creates an instance of a class and the class needs to call controller.update(). How do I access the controller in the 'class' - That's all!

Thank you!

Answer №1

Eliminating the need for the onload tag to start onload tasks is simple. Just include the following in your external javascript file:

let control = false;
function Initialize(){
    control = new ControllerClass;
}
function registerEvent(element, eventType, callback, useCapture) {
    let useCapture = useCapture || true;
    if (element.addEventListener) {
        element.addEventListener(eventType, callback, useCapture);
        return true;
    } else if (element.attachEvent) {
        return element.attachEvent('on' + eventType, callback);
    } else {
        element['on' + eventType] = callback;
    }
}
registerEvent(window, 'load', Initialize);

Answer №2

It's a bit puzzling as to why one would want to carry out the aforementioned steps. The solution is quite simple: remove all the JavaScript code as shown below:

...

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

...

<body>

....

Then, in the 'myjsfile.js', implement something like this:

window.onload = function(){
    var controller = new CTRLclass();
}

If it needs to be global, you can relocate it outside of the 'onload' function, like so:

var controller = false
window.onload = function(){
    controller = new CTRLclass();
}

Opting for jQuery would add more sophistication to the implementation and reduce the risk of overriding any existing 'onloads':

var controller = false
$(document).ready(function(){
    controller = new CTRLclass();
});

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

React Chart.js allows for consistent spacing for x-axes by displaying dates in a well-organized

After incorporating displayFormats in scales.x, I noticed that my xAxes labels are spaced differently based on the data object they contain. How can I adjust my xAxes labels to have equal spacing? The code snippet is displayed in the following image. Pleas ...

Using CSS to customize the appearance of the preview in CKEditor

After successfully integrating CKEditor into my website CMS, I am facing an issue with the Preview button not using stylesheets (CSS). Despite editing the preview.html file located in: Website/ckeditor/plugins/preview/ It appears that the CSS is being ig ...

Errors occur when using jQuery Autocomplete alongside Angular HTTP

I have implemented an ajax autocomplete feature for my database using the jQuery-Autocomplete plugin. Below is my current code setup: HTML: <input ng-keyup="searchCustomer()" id="customerAutocomplete" type="text"> Angular $scope.searchCustome ...

Adaptable images - Adjusting image size for various screen dimensions

Currently, my website is built using the framework . I am looking for a solution to make images resize based on different screen sizes, such as iPhones. Can anyone suggest the simplest way to achieve this? I have done some research online but there are t ...

Textures in ThreeJS that are of type transparent PNG and have

Having trouble understanding an issue I encountered with ThreeJS. There's a basic cube on a page and I've got a PNG image of a white question mark, with the rest of the image transparent. When I apply the texture to the cube; cubeGeometry = new ...

Sending data with React using POST request

Currently in my React application, I have a form that includes fields for username and password (with plans to add "confirm password" as well). When submitting the form, I need it to send JSON data containing the email and password in its body. The passwo ...

Unable to simultaneously execute TypeScript and nodemon

Currently, I am in the process of developing a RESTful API using Node.js, Express, and TypeScript. To facilitate this, I have already installed all the necessary dependencies, including nodemon. In my TypeScript configuration file, I made a modification to ...

What is the method for importing the merge function from "lodash/merge" in TypeScript?

When using ES6, it's possible to import only a single function from a library in order to reduce the overall bundle size. For example: import merge from "lodash/merge" But in TypeScript, the statement above can trigger a compile error: Cannot find m ...

Dealing with Uncaught Type Errors in the Fixed Data Table

I am attempting to implement a fixed data table using the following code snippet. var MyCompi = React.createClass({ getInitialState: function() { return { rows : [ {"id":1,"first_name":"William","last_name":"Elliott","email":"<a ...

The creation of the Angular project was unsuccessful due to the outdated circular-json dependency

After attempting to create a new Angular project with the command: ng new hello-world I encountered an error message: npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b5d6dcc7d6c0d9d4c798dfc6dadbf5859b809b8 ...

The Electron BrowserWindow turns dark post execution of the .show() method

Revision: After some tinkering, I discovered that the issue was related to the order in which I created the windows. Previously, my code looked like this: app.whenReady().then(() => { createWindow(); spawnLoadingBlockWindow(); spawnGenerati ...

Utilizing NodeJS and Express to enhance the client side for showcasing an uploaded file

My knowledge of nodeJS, AJAX requests, and routing is still in its infancy. After following a tutorial on nodejs and express examples, I managed to get everything working on the server-side. However, I'm facing difficulty displaying the uploaded file ...

Concluding the dialogue once the post request has been successfully processed

My tech stack includes React, Redux, NodeJS, and ExpressJS. For the front-end, I'm utilizing material-ui. Within my application, I have implemented a dialog that allows users to input information and sign up. Upon clicking submit, a POST request is in ...

I am looking to obtain a value through a JavaScript function that sums values upon clicking. The result is satisfactory, but I am seeking a way to limit the value

I only need 2 decimal values, not large ones. Can someone please help me achieve this? <script> $(function() { $("#isum, #num1, #num2, #num3, #rec1, #rec2, #rec3, #difnum1, #difnum2, #difnum3").on("keydown ke ...

Managing the uploading of files when a new property is included directly from the JavaScript File Object

When processing files using the POST method, I am able to access the default information such as name, type, size, tmp_name, and error through PHP. However, the file being sent contains additional data that I need PHP to extract. For instance, in the scre ...

Exporting NativeModules for npm package in React Native

I'm attempting to convert my React Native App into a node module. The issue I'm facing is that the module consists mainly of a NativeModule. Thus, my index.js file appears like this: import { NativeModules } from 'react-native'; expo ...

The ID value did not pick up the number 0 when passed to the next blade after the initial reading

When passing an ID value to another blade file, I encountered an issue where the other blade file did not read the number 0 at the beginning. For example, if I pass the value of 006, when I console log the value in the other blade view, it only shows 6. H ...

Using an anonymous function in Javascript to change the background color of a div on mouse-over directly from the HTML code

I came across this code snippet in the provided link and as a beginner in JavaScript, I am unsure how to call the JavaScript function from the HTML code. Due to them being anonymous functions, I am struggling to invoke them. Can someone guide me on how to ...

Ensure that the vue-router guard waits for the completion of the axios API call in Vuex before proceeding

I am currently working with a django-rest-axios-vuejs application stack, and I have a specific task that involves the vue-router. Within the beforeEach guard of the vue-router, I am checking permissions by verifying something in the me object within the v ...

How can you achieve three layers of nested quotes in Dynamic HTML?

Working on an app that utilizes JQuery and JQTouch for iOS. The issue I'm facing involves dynamically generated HTML lists where the user clicks a row that needs to be highlighted. However, achieving this has proven tricky due to nesting 3 sets of quo ...