The Javascript file fails to function properly upon opening the HTML file in a web browser

Recently, I came across an HTML file that included linked CSS and JavaScript files. The purpose of the HTML file was to function as an address book where users could add contacts, search for contacts by name, and view all the contacts stored in the book. I found the code on a CodePen page, but when I implemented it into my own file, it failed to work properly and I'm unsure of the reason why. You can find the original code from the CodePen page here. My modified code will be available in the snippet below:

// Insert your JavaScript code here
// It will contain functions for adding, searching, and displaying contact information
// Add any custom CSS styling here
// This will control the layout and appearance of the address book interface
<html>
    <head>
        <title>Your Title Here</title>
        <link rel="stylesheet" type="text/css" href="your-styles.css">
        <script src="your-scripts.js"></script>
        </head>
<body>
<div class="container">
    <!-- Your HTML content goes here -->
  </div>
</body>
</html>

It seems that the code functions correctly within the snippet, but encounters issues when viewed on a web browser. If you have any insights or solutions to this problem, please feel free to share them. Thank you!

Answer №1

One effective solution mentioned in the comments is to move your script towards the end of the body tag to resolve the issue. However, an even more efficient approach would be to enclose the immediately called part (not the function definition) of your script within a load event listener. This event will only be triggered after all elements on your page have loaded, regardless of where your script is placed.

window.addEventListener('load', (event) => {
    console.log('page is fully loaded');
});

Your updated script should resemble the following:

window.addEventListener('load', (event) => {
    document.getElementById('search_button').addEventListener('click', searchPerson);
    document.getElementById('add_button').addEventListener('click', addPerson);
    document.getElementById('show_all').addEventListener('click', showAllPersons);
});

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

What is the best way to automatically refresh a Django page only when necessary?

After exploring how to update a Django page without reloading it on Stack Overflow, I have been utilizing JavaScript to send XMLHTTPRequests from the browser to the server in order to retrieve specific parts of the webpage that may change during my applica ...

Using checkboxes in HTML tables to display values, names, and IDs in PHP

In my current project, I am dealing with a table of checkboxes that I need to save in a database. Each checkbox needs to be saved separately with its name and value as individual records: <tr><td><input class="perm" name="feature[]" type= ...

Attempting to extract content from a specific span element

I've been struggling to extract the text within a <span> element from a webpage. Every attempt I've made that doesn't result in an error has come back empty, with no output whatsoever. Here is the code I'm using: import time imp ...

Determining the successful completion of an ajax request using jQuery editable plugin

I recently started using Jeditable to enable inline editing on my website. $(".video_content_right .project_description").editable(BASE_URL+"/update/description", { indicator: "<img src='" + BASE_URL + "/resources/assets/front/images/indicator ...

Large Quotation marks with an HTML/CSS design

Is there a way to style a quote using large quotation marks? I've tried various methods found online, such as using Blockquote with the :before and :after CSS styles. However, I'm running into issues with using an image within a div for responsi ...

The hover function stops working once the dropdown class has been removed

I am currently experimenting with a bootstrap template. In the navigation bar, there is an option for "Blog" and "Test". For the "Test" button, I decided to remove the li class="dropdown " because I wanted to create a button that changes color on hover si ...

What is the best way to eliminate a div upon component dismount in React?

Is there a way to remove a div element on component unmount using react? I created a div with the id portal in the useCallback method. Now, I want to remove it when the component unmounts. Can anyone guide me on how to achieve this? Below you can see the ...

What is the best way to navigate a carousel containing images or divs using arrow keys while maintaining focus?

Recently, I have been exploring the Ant Carousel component which can be found at https://ant.design/components/carousel/. The Carousel is enclosed within a Modal and contains multiple child div elements. Initially, the arrow keys for navigation do not work ...

Is there a way to automatically click the 'next' arrow on my image slider?

I'm currently working on a website that uses the Semplice theme in Wordpress. The built-in slider doesn't have an autoplay feature, so I attempted to use jQuery to automatically click the 'next' arrow every 5 seconds. However, I ran int ...

Determine if the JQuery change event is not triggered by a hyperlink

I have integrated the Nestable script from this source and I'm looking for a way to include clickable links in the navigation items that can be moved around. Currently, adding a link to the <li> element causes the entire navigation to behave un ...

Tips for managing the sub query in nodejs?

Developed a RESTful API in nodeJS focusing on a Post-type feature. The process involves executing two queries: 1. Initially fetching user-Id and answer details from the answers table. Upon checking the console, two user-Ids are displayed. 2. Secondly, que ...

Adjust the size of the HTML input font to decrease as additional text is entered

Is it possible to create an HTML text field that automatically adjusts the font size when the user types more characters than it can display? I know Acrobat has this feature for forms, but I'm looking to implement it in HTML. So, imagine having a te ...

What could be the reason for my React/HTML select element occasionally failing to display the default selected value?

I am currently working on creating a select element in Reactjs/HTML and I am facing an issue with setting a default value based on a component variable. Essentially, the default value of the select should be the id of a component. This is my current imple ...

Why is the column width on this Tumblr page constantly flickering?

Seeking assistance with a minor issue on my Tumblr page - the content column seems to be flickering on mouseover, shifting between full width and its original programmed width. Any insight on the CSS causing this? Much appreciated! Check it out here (Dis ...

The error message "THREE is not defined" occurred while running mocha tests for a

I am attempting to execute a basic Mocha unit test for code that utilizes the Vector3 class from THREE.js: import {Vector3} from 'three'; const a = new Vector3(0, 0, 0); When running this test using Mocha (specifically mocha-webpack, with webpa ...

Finding all elements with a specified attribute in jQuery: A comprehensive guide

While looking for an example, I came across one that searches only inputs instead of all elements: https://api.jquery.com/attribute-equals-selector/ Is there a way to modify this example so that it can search all elements in the DOM, and not just inputs ...

The result of Document.getElementById can show as "undefined" despite the presence of the element

Currently, I am tackling a project that involves extracting information from a website. I have opted to use the 'puppeteer' library in Node.Js for this task. However, I am encountering an issue where Document.getElementById is returning "undefine ...

What is the reason behind the change in size and shape of the text when using "overflow: hidden"?

Check out this interactive demo using the provided HTML and CSS: You can view the demo by clicking on this link. /*CSS*/ .header { margin: 0px; padding: 0px; width: 100%; } .headertable { padding: 0px; margin: 0px; width: 100%; border-sp ...

JQuery is facing difficulty in animating a div following the completion of a "forwards" css animation

Check out this example: http://jsfiddle.net/nxsv5dgw/ A div appears on the stage and a CSS animation is applied to it. However, when attempting to use JQuery to animate the same properties that were animated by CSS, it seems to no longer work properly. ...

Experiencing a 401 error with Node.js while integrating the PayPal REST

Hey there! Currently, I am working with nodejs and paypal-rest-sdk version "^1.6.0" alongside express 4.13.1. Encountered an issue while processing live payments, the error message I'm receiving is: { [Error: Response Status : 401] response: { ...