Having trouble connecting the HTML file with the JavaScript file

This is my unique HTML file

<!DOCTYPE html>
<html>
    <head>
        <script src="ll.js"></script>

    </head>
    <body>
        <link rel="stylesheet" href="home.css">
        
        <h1><span>Customized</span> and <span>sortable</span> drop-down list</h1>

        <form>
            <input class="chosen-value" type="text" value="" placeholder="Type to filter">
            <ul class="value-list">
              <li>Alabama</li>
              <li>Alaska</li>
              <li>Arizona</li>
              <li>Arkansas</li>
              <li>California</li>
              <li>Colorado</li>
              <li>Connecticut</li>
              <li>Delaware</li>
              <li>Florida</li>
              <li>Georgia</li>
              <li>Hawaii</li>
              <li>Idaho</li>
              <li>Illinois</li>
              <li>Indiana</li>
              <li>Iowa</li>
              <li>Kansas</li>
              <li>Kentucky</li>
              <li>Louisiana</li>
              <li>Maine</li>
              <li>Maryland</li>
              <li>Massachusetts</li>
              <li>Michigan</li>
              <li>Minnesota</li>
              <li>Mississippi</li>
              <li>Missouri</li>
              <li>Montana</li>
              <li>Nebraska</li>
              <li>Nevada</li>
              <li>New Hampshire</li>
              <li>New Jersey</li>
              <li>New Mexico</li>
              <li>New York</li>
              <li>North Carolina</li>
              <li>North Dakota</li>
            </ul>
          </form>


</body>
</html>

The CSS is properly linked. JavaScript file (ll.js):

const inputField = document.querySelector('.chosen-value');
const dropdown = document.querySelector('.value-list');
const dropdownArray = [... document.querySelectorAll('li')];
console.log(typeof dropdownArray)
dropdown.classList.add('open');
inputField.focus(); // Demo purposes only
let valueArray = [];
dropdownArray.forEach(item => {
  valueArray.push(item.textContent);
});

const closeDropdown = () => {
  dropdown.classList.remove('open');
}

inputField.addEventListener('input', () => {
  dropdown.classList.add('open');
  let inputValue = inputField.value.toLowerCase();
  let valueSubstring;
  if (inputValue.length > 0) {
    for (let j = 0; j < valueArray.length; j++) {
      if (!(inputValue.substring(0, inputValue.length) === valueArray[j].substring(0, inputValue.length).toLowerCase())) {
        dropdownArray[j].classList.add('closed');
      } else {
        dropdownArray[j].classList.remove('closed');
      }
    }
  } else {
    for (let i = 0; i < dropdownArray.length; i++) {
      dropdownArray[i].classList.remove('closed');
    }
  }
});

dropdownArray.forEach(item => {
  item.addEventListener('click', (evt) => {
    inputField.value = item.textContent;
    dropdownArray.forEach(dropdown => {
      dropdown.classList.add('closed');
    });
  });
})

inputField.addEventListener('focus', () => {
   inputField.placeholder = 'Type to filter';
   dropdown.classList.add('open');
   dropdownArray.forEach(dropdown => {
     dropdown.classList.remove('closed');
   });
});

inputField.addEventListener('blur', () => {
   inputField.placeholder = 'Select state';
  dropdown.classList.remove('open');
});

document.addEventListener('click', (evt) => {
  const isDropdown = dropdown.contains(evt.target);
  const isInput = inputField.contains(evt.target);
  if (!isDropdown && !isInput) {
    dropdown.classList.remove('open');
  }
});

I'm trying to figure out how to link them properly. I've attempted adding

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

at different locations like within the form tag and body tag but it hasn't worked. When testing JS, HTML, and CSS on JsBin, everything functions perfectly except for linking the files together.

Answer №1

You have the option to:

Insert after the closing `<body> .. </body><script>...` tag. or

<script src='ll.js' defer></script>

In essence, you must defer the running of your javascript.

Answer №2

Make sure to include the javascript file before the closing body tag in your HTML code, as this can help solve any issues you may be experiencing. Additionally, consider renaming the file from 11.js to something more descriptive like main.js for better organization.

Your updated file structure should look like this:

<!DOCTYPE html>
<html>
    <head>


    </head>
    <body>
        
        <h1><span>Styled</span> and <span>filterable</span> select dropdown</h1>

        <form>
            <input class="chosen-value" type="text" value="" placeholder="Type to filter">
            <ul class="value-list">
              <li>Alabama</li>
              <li>Alaska</li>
              <li>Arizona</li>
              <li>Arkansas</li>
              <li>California</li>
              <li>Colorado</li>
              <li>Connecticut</li>
              <li>Delaware</li>
              <li>Florida</li>
              <li>Georgia</li>
              <li>Hawaii</li>
              <li>Idaho</li>
              <li>Illinois</li>
              <li>Indiana</li>
              <li>Iowa</li>
              <li>Kansas</li>
              <li>Kentucky</li>
              <li>Louisiana</li>
              <li>Maine</li>
              <li>Maryland</li>
              <li>Massachusetts</li>
              <li>Michigan</li>
              <li>Minnesota</li>
              <li>Mississippi</li>
              <li>Missouri</li>
              <li>Montana</li>
              <li>Nebraska</li>
              <li>Nevada</li>
              <li>New Hampshire</li>
              <li>New Jersey</li>
              <li>New Mexico</li>
              <li>New York</li>
              <li>North Carolina</li>
              <li>North Dakota</li>
            </ul>
          </form>

          <script src="main.js"></script>
</body>
</html>

Answer №3

The issue arises because your JavaScript code is trying to access elements in the document before they are fully loaded. To resolve this, it's recommended that you place your script at the end of the body section.

Alternatively, you can utilize the DOMContentLoaded event to ensure that your script runs only after all elements have been loaded:

document.addEventListener("DOMContentLoaded", function(){
  // Your script
})

Once you've made these changes, you can safely link your JS file in the head of the document without any problems.

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

Ways to contrast HTML without considering whitespace?

I'm currently testing an HTML builder through unit testing. My goal is to confirm that the output content matches the expected content, while allowing for some leniency when it comes to white space. More specifically, I am not concerned with whether ...

Getting the ng-model value from a Directive's template and passing it to a different HTML file

When working with my name directive, I am unable to retrieve the value of ng-model from the template-url. team-two.html <form name="userForm" novalidate> <div name-directive></div> </form> <pre>{{userForm.firstname}}< ...

Utilizing properties from the same object based on certain conditions

Here's a perplexing query that's been on my mind lately. I have this object with all the styles I need to apply to an element in my React app. const LinkStyle = { textDecoration : 'none', color : 'rgba(58, 62, 65, 1)', ...

What is the most efficient way to retrieve key pair values of separate elements in an array with just one API request?

The API I am working with returns an array of elements, each containing multiple key-value pairs. An example of a similar API response can be seen here: , where an array of poems is returned. [ { "title": "...." "content": "..." "url" : "..." } ...

Learn the process of updating an Xero invoice seamlessly with the xero-Node integration

After successfully integrating Xero with my app for accounting and billing purposes, I am now looking to update a previous invoice that was created in the past on Xero. Is there a solution available for this? Any suggestions would be greatly appreciated. ...

Using Javascript to create bold text within a string

I have noticed that many people are asking about this issue, but it seems like a clear and simple answer is hard to come by. Currently, I am working with Vue and trying to display text from an object in a component. My goal is to highlight the price port ...

Errors encountered while running `npm install discord.js`

I am currently facing an issue while trying to install discord.js. Unfortunately, I keep encountering the following errors: npm ERR! cb() never called! npm ERR! This is an error with npm itself. Please report this error at: npm ERR! <https://npm.co ...

CSS from the parent page is not being applied to AJAX-injected content

I recently added AJAX functionality to a new website to dynamically load and insert Wordpress page content using AJAX. However, I encountered an issue where some CSS styles that were supposed to be loaded in the page head were not being applied. This resu ...

Error message: "Unable to locate jQuery file within the node.js + Express application running on Heroku platform."

My current setup involves a node.js application with Express and express-handlebars deployed on Heroku. However, whenever I run the app, the console displays a 404 error for the jquery file, leading to subsequent failures for dependent libraries like Boots ...

Vue Component, switching state

Feeling like I'm losing it, this should be really simple but it's not working... The idea is that when the link is clicked, the display property toggles between true and false. However, it's not working as expected. Vue.component('d ...

Performing addition operations on numbers entered through an HTML input field using PHP

I am looking to create a feature where the numbers entered in an input form are added together. I need to store these numbers in an array and have them display in a new line when a button is clicked. Here is the HTML code for the input field and button: ...

Tips for updating parameters that are defined in a controller within a promise

Currently, I am developing a single page application using Angular and TypeScript. I am facing an issue with updating the parameter value (_isShowFirst) of the controller inside a promise function. It seems like nothing is recognized within the promise blo ...

Storing a collection of items in an array using jQuery

Looking to organize list items from multiple lists of the same class into an array. For example: <ul class="myList"> <li>item 1</li> <li>item 2</li> </ul> <ul class="myList"> <li>i ...

How can I effectively implement a withAuth higher order component (HOC) in TypeScript within Next.js?

Currently, I am working on a Next.js application and implementing the next-auth package. My goal is to develop a Higher Order Component (HOC) that can determine if the component has an active session or not. Along with this, I am utilizing eslint for code ...

Need help inserting an image into the div when the ngif condition is true, and when the ngif condition is false

Essentially, I have a situation where I am using an *ngIf condition on a div that also contains an image. This is for a login page where I need to display different versions based on the type of user. However, I'm facing an issue where the image does ...

The CORS middleware seems to be ineffective when used in the context of Node.js

I have set up my REST API on a Raspberry Pi server and connected it to the public using localtunnel. I am trying to access this API from a localhost Node.js application. The Node application is running on Express and includes some static JS files. However, ...

Tips for integrating AngularJS into a webpage

I am currently developing a NodeJS application and I am looking to integrate AngularJS for the client side scripting. After downloading AngularJS via NPM, I encountered an issue where my require statement is not functioning as expected. Can anyone provide ...

The final piece left in stitching together an array

Issue I have been struggling with this code for some time now and I can't seem to figure out the solution. I am receiving 3 values from inputs and trying to remove all the empty spaces "" in the array, but when I execute the code, it displays the foll ...

Resolving issues with JavaScript caused by Polymer updates

I am a novice when it comes to working with Polymer. From what I have gathered, there seems to be compatibility issues with Mozilla and Safari. After researching on StackOverflow, I found that adding addEventListener('WebComponentsReady', funct ...

Issue with mouseMove function not aligning correctly with object-fit:contain CSS property

My current code allows users to select a color from an image when hovering over the pixel with the mouse. However, I am encountering an issue where the colors do not map correctly when using object-fit: contain for the image. The script seems to be treatin ...