Invoking a JavaScript class using a script tag

In my code, I have a class declaration in a script that is imported before the body tag:

$(document).ready(function(){

  var FamilyTree = function() {
  };
  FamilyTree.prototype.displayMessage=function() {
    alert("test");
  }
});

Then, within the body of the HTML document, I have the following code inside a script tag:

$(document).ready(function(){
    var famtree= new FamilyTree();
    famtree.displayMessage();
});

However, when I load the page, Firefox shows this error message:

ReferenceError: FamilyTree is not defined

Even though the class is defined before it is called, for some reason it is inaccessible. What could be causing this issue?

Answer №1

The focus of FamilleTree is restricted to the closure contained within document.ready. Once you try to access the variable from another function, it goes out of scope. To tackle this issue, consider declaring FamilleTree outside of $(document).ready like shown below:

var FamilyTree = function(tree) {
  this.tree = tree;
};

$(document).ready(function(){

  FamilyTree.prototype.drawTree = function() {
    $('#tree1').tree({
        data: this.tree,
        dragAndDrop: true
    });
  }
});

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

Troubleshooting Azure typescript function: Entry point for function cannot be determined

project structure: <root-directory> ├── README.md ├── dist ├── bin ├── dependencies ├── host.json ├── local.settings.json ├── node_modules ├── package-lock.json ├── package.json ├── sealwork ...

I am experiencing difficulties with my focusin not functioning properly for the input element that I added

I am working on a program that includes a dynamic table with the following structure: <table id="selectedItems"> </table> I plan to use jQuery to append elements to it like so: var i=0; $("#selectedItems").html(''); $("#sel ...

Changing the size of an image in an HTML5 canvas

I have been attempting to generate a thumbnail image on the client side using Javascript and a canvas element. However, when I reduce the size of the image, it appears distorted. It seems as though the resizing is being done with 'Nearest Neighbor&apo ...

When the window is fully loaded, JavaScript executes

Can someone help me set up this script to start running when the page loads? I want the vat field to automatically show up if the company name has been entered. Thank you! //--></script> <script type="text/javascript>//-- $('.colorbox ...

Execute the script when the document is fully loaded

Is there a way to show a dialog in jQuery when the document loads without using <body onload="showdialog();">? Can the javascript code be placed in the main div or footer div to work like the onload event? <body onload="$('#dialog').sli ...

What could be the reason for the absence of the loading sign in Chrome, even though it appears when the code is run on Firefox?

I implemented a function to display a loading screen on my HTML page with Google Maps integration. However, when I called the function popUpLoadingScreen() and dismissLoadingScreen() to show and hide the loading message while rendering map markers, the loa ...

I'm curious about the process by which custom hooks retrieve data and the detailed pathway that custom hooks follow

//using Input HOOK I am curious to understand how this custom hook operates. import { useState } from "react"; export default initialValue => { const [value, setValue] = useState(initialValue); return { value, onChange: event =&g ...

Delivering XML in response to a webmethod call

While working with an ajax PageMethod to call an asp.net webmethod, I encountered an issue when trying to pass a significant amount of XML back to a callback javascript function. Currently, I am converting the XML into a string and passing it in that form ...

Optimizing the performance of J2EE web applications

I am currently working on enhancing the performance of my web application. The application is java-based and is hosted on an Amazon cloud server with JBoss and Apache. One particular page in the application is experiencing a slow loading time of 13-14 sec ...

Successive pressing actions

I am struggling to grasp a unique Javascript event scenario. To see an example of this, please visit http://jsfiddle.net/UFL7X/ Upon clicking the yellow box for the first time, I expected only the first click event handler to be called and turn the large ...

Executing a cURL request using Node.js

Looking for assistance in converting the request below: curl -F <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1a777f7e737b275a73777b7d7f34706a7d">[email protected]</a> <url> to an axios request if possible. ...

Is it possible to retrieve a variable from a geojson file using Vue 3 and Vite?

For my Vue 3 project, I am trying to import a variable from a geojson file. However, when I use import line from '@static/line.geojson', my page goes blank and it seems like Vue stops working. If I use import line from '@static/line.json&ap ...

Having trouble sending a function as a prop to a child component in React

Something odd is happening, I'm confident that the syntax is correct, but an error keeps popping up: Error: chooseMessage is not a function // MAIN COMPONENT import React, { useState } from 'react' export default function LayoutMain(prop ...

Guide to rearranging the sequence of items in a selected jQuery collection

I have created a JavaScript filter that targets elements with the class .single: There are numerous divs with the class .single, each containing multiple text elements. The filter has already been set up to hide all .single elements that do not contain an ...

Does the react-google-login library utilize the services provided by Google Identity?

Currently incorporating the react-google-login library (https://www.npmjs.com/package/react-google-login/v/5.2.2) in my JavaScript codebase to grant users access to my website. Can anyone confirm whether this library utilizes "Google Identity Services" or ...

What is the process for displaying all cookies in node.js?

I recently wrote some node.js code to retrieve cookies for a specific route. router.get('/', function (req, res, next) { var cookies = req.cookies; res.render('cartoons', { Cookies: cookies, }); }); In my cartoons Jade file, the ...

A guide on sending a post request with Axios to a parameterized route in Express

Recently, I set up an express route router.post('/:make&:model&:year', function (req, res) {   const newCar = {     make: req.params.make,     model: req.params.model,     year: req.params.year   }   Car.create(newCar);   res ...

Most Effective Method for Switching CSS Style Height from "0" to "auto"

After coming across a question with no answer that suited my needs, I decided to share the solution I created. In my case, I had a hidden generated list on a page which was initially set with a CSS height of "0" and then expanded upon clicking by transit ...

What is the method for configuring environment variables in the Lumber framework?

Installing Lumber CLI npm install -g lumber-cli -s Next, lumber generate "adminpanel_test" --connection-url "mysql://root@localhost:3306/admin-dev" --ssl "false" --application-host "localhost" --application-port "3310" Error: lumber is not recognized a ...

Discover the method to determine the total count of days in a given week number

I am developing a gantt chart feature that allows users to select a start date and an end date. The gantt chart should display the week numbers in accordance with the ISO standard. However, I have encountered two situations where either the start week numb ...