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

Loop through an array of elements in JavaScript and retrieve the element with the largest pixel size

I am facing a challenge with elements positioned absolutely on a web page. My goal is to iterate over these elements and identify the one with the highest top value. I attempted two different approaches: const elems = document.querySelectorAll('.ind ...

Utilizing ng-bind-html alongside ng-controller

Injecting insecure html into a <div> is part of my current task: <div class="category-wrapper" ng-bind-html="content"></div> The angularjs "code" in this html snippet ($scope.content) includes the following: <script type='text/ ...

Currently working on a script using google-apps-script, open to any suggestions or ideas

Challenge: I am working on creating arrays to store values and iterate until a specific value is reached. Ultimately, this code will be used to match one letter to another, similar to how the WWII Bombe machine functioned, but in a purely digital format. T ...

Hiding BottomTabNavigator on specific screens using React Navigation (4.x)

Looking for a way to hide the bottom tab navigator specifically in the 'Chat' screen of my React Native and React Navigation app. Here is what I have so far: const UserNavigation= createStackNavigator({ Profile:{screen:Profile}, Search:{ ...

Every time I attempt to input text into the text area, the page automatically refreshes, preventing me from completing any entries

Currently, I am working on developing a webpage that can dynamically update text inputted by users in a database. However, I have encountered an issue where the page refreshes automatically whenever I click on the textarea. If I type quickly enough, some o ...

Error message: npm command not recognized while running commands within an Electron application

While developing an electron app, I utilize shell commands with child_process.exec. One of the commands I use is npm run start, which functions perfectly in a development environment. However, upon building the application for production, all npm commands ...

Avoid Refreshing the Page When Pressing the Like Button

I've been working on code for liking a post and saving the value to a database using server-side code. However, I'm running into some issues when the page refreshes after clicking the like button. I tried using event.preventDefault() in my JavaSc ...

Creating a Mondrian-inspired design using a combination of red, blue, and yellow within an HTML table

Is there anyone who can assist me in recreating this painting using HTML <table> tag and CSS within a browser? The image to replicate: https://i.stack.imgur.com/84y4I.jpg I attempted to complete this task, but my instructor is dissatisfied with th ...

What is the best way to utilize overflow with TailwindCSS?

1. The Home Component: import React from "react"; import Title from "./Title"; import TaskInput from "./TaskInput"; import TaskList from "./TaskList"; function Home() { return ( <div className="h-scree ...

Tips for inserting text to the left rather than the right using Jquery

I recently came across this code snippet shared by some helpful users on stackoverflow and it has been working perfectly for me. However, I do have a couple of queries regarding its functionality. Firstly, how can I ensure that the current selected option ...

Utilizing jQuery to add elements to a webpage

I need to populate an empty div on my webpage using jQuery. Here's an example: <div class="content"> </div> After the first insertion, I want the markup to look like this: <div class="content"> <div class="inserted first"& ...

How can you quickly navigate to the top of the page before clicking on a link in the same window/tab?

Could someone assist me with a coding issue I am facing? I would like to be able to go to the top of the page when clicking on a link and have the link open in the same tab. I attempted to implement this functionality using the following code, however, I ...

Server time dictates the operation of Moment.js

I've been working with Moment.js and it's functioning correctly, but I can't seem to figure out how to make it run on server time instead of local time. I've tried a few things, but haven't had any luck. I'm unsure of how to ...

Utilizing Google Maps to display an infowindow upon clicking a location from a geojson file

I want to implement info windows that pop up when markers on a map are clicked. I used the sample code provided by Google (below) to create a marker map from geojson files dragged and dropped into the window. My goal is for the info windows to show text ta ...

designing the border at the bottom of the existing menu selection

I am trying to enhance the look of my current-menu-item div by adding a border at the bottom. It seems simple enough to achieve this by simply including the border in the div. However, I'm facing an issue with the width and position of the border. Ide ...

Exploring the concept of type identification in interpreted dynamic languages

How do dynamic scripting languages like Python, PHP, and JavaScript determine the datatype of a variable? /* C code */ int a = 1; int b = 2; int c = a * b; In the above C example, the compiler recognizes that 'a' and 'b' are integers. ...

The $emit method in Vue seems to be ineffective when used on the parent component, yet it functions properly when used on the

I have a component called "register" which contains an event listener @submit.prevent inside the template, and I am using $emit to send the data. When I console.log within the method of the component itself, it works fine. However, when I try to access the ...

Refresh website-wide variables after a post has been made

Within my index.js file, I am rendering a page with global variables. router.get('/index', function(req, res, next) { res.render('index', { title: 'RLH', countNumber: countNumber, countReleased: countReleased, coun ...

How can I resolve the issue of background-size not functioning properly?

Struggling to set a background-image with the 'cover' size property inside a div. Despite trying different values for background-size, the image always shows up in full size within the div. I've searched for similar answers on SO, but nothi ...

While creating a React app, Docker becomes stuck due to a hangup when checking the core-js dependency

I've hit a roadblock in the build process. I'm working on an M1 Mac Mini and have attempted to build in both arm64 and x86_64 terminals, but the outcome is consistently the same. npm info lifecycle @babel/<a href="/cdn-cgi/l/email-protection" ...