The Javascript code fails to execute after other scripts have been employed

Trying to create an expanding search bar that expands upon button click and collapses when clicking elsewhere on the page. The issue I'm facing is that everything works well initially, but after the second script hides the input field on a click outside it, the first script fails to trigger when I click the button again. I've tried various code variations without success, and I feel like I don't fully grasp how JavaScript functions in this case. Any help would be greatly appreciated. Check out the codepen link below for the code.

        document.getElementById("searchButton").addEventListener("click", function(){
    
      document.getElementById("userInputWindow").classList.toggle("userInputAnimationToggle");
    
    });
    document.addEventListener("click", function(event){
      let i = document.getElementById("userInputWindow");
      let k = document.getElementById("searchButton");
    
      if(event.target !== i && event.target !== k)
      {
        document.getElementById("userInputWindow").classList.add("userInputAnimationToggle1");
      }
        
          if(event.target !== i){
            document.getElementById("userInputWindow").value = "";
        }
        });
        .searchBoxWrapper{
      position: absolute;
      margin: 40px auto;
      text-align: center;
      left: 50%;
    }
    
    button{
      position:absolute;
      width: 100px;
      height: 100px;
      margin-bottom: 5rem;
      padding: 10px;
      background-color: grey;
      border: 2px solid orange;
      border-radius: 100px;
      font-size: 1rem;
      transform: translate(-50%, 0);
      z-index: 2;
    }


    .userInput{
      position: absolute;
      display: block;
      width: 0;
      padding: 15px;
      border-radius: 40px;
      background-color: grey;
      border: 2px solid orange;
      transform: translateY(50%);
      left: 20px;
      z-index: 1;
      text-align:center;
      transition: all 1s ease;
    }
    
    .userInput::placeholder{
    font-size: 2rem;
    }
    
    .userInputAnimationToggle{
    width: 150px;
    display: block;
    }
    .userInputAnimationToggle1{
    display: none;
    }
    
 <div class = "searchBoxWrapper">
 <button class = "openSearchButton" id = "searchButton" type = "button" title = "Open Search window">Search</button>
 <input class = "userInput" value="" type = "text" id = "userInputWindow" placeholder = "     for item"/>
</div>

Link to Codepen: https://codepen.io/Mynickname/pen/jepzzX

Answer №1

To revert the search to its original state, you must remove the css class userInputAnimationToggle1 that was applied during hide and update its value. I have made changes to the userInputAnimationToggle1 css.

document.getElementById("searchButton").addEventListener("click", function(){
document.getElementById("userInputWindow").classList.remove("userInputAnimationToggle1");
  document.getElementById("userInputWindow").classList.toggle("userInputAnimationToggle");

});

document.addEventListener("click", function(event){
  let i = document.getElementById("userInputWindow");
  let k = document.getElementById("searchButton");

  if(event.target !== i && event.target !== k)
  {
   document.getElementById("userInputWindow").classList.add("userInputAnimationToggle1");
  }

  if(event.target !== i){
    document.getElementById("userInputWindow").value = "";
}
});
.searchBoxWrapper{
  position: absolute;
  margin: 40px auto;
  text-align: center;
  left: 50%;
}

button{
  position:absolute;
  width: 100px;
  height: 100px;
  margin-bottom: 5rem;
  padding: 10px;
  background-color: grey;
  border: 2px solid orange;
  border-radius: 100px;
  font-size: 1rem;
  transform: translate(-50%, 0);
  z-index: 2;
}


.userInput{
  position: absolute;
  display: block;
  width: 0;
  padding: 15px;
  border-radius: 40px;
  background-color: grey;
  border: 2px solid orange;
  transform: translateY(50%);
  left: 20px;
  z-index: 1;
  text-align:center;
  transition: all 1s ease;
}

.userInput::placeholder{
font-size: 2rem;
}
.userInputAnimationToggle{
width: 150px;
display: block;
}
.userInputAnimationToggle1{

position: absolute;
  display: block;
  width: 0;
  padding: 15px;
  border-radius: 40px;
  background-color: grey;
  border: 2px solid orange;
  transform: translateY(50%);
  left: 20px;
  z-index: 1;
  text-align:center;
  transition: all 1s ease;
}
<div class = "searchBoxWrapper">
        <button class = "openSearchButton" id = "searchButton" type = "button" title = "Open Search window">Search</button>
        <input class = "userInput" value="" type = "text" id = "userInputWindow" placeholder = "     for item"></input>
      </div>

Answer №2

Instead of introducing a new class (userInputAnimationToggle1), simply eliminate the existing class (userInputAnimationToggle).

Revise the following code snippet

document.getElementById("userInputWindow").classList.add("userInputAnimationToggle1");

to this

document.getElementById("userInputWindow").classList.remove("userInputAnimationToggle");

This way, you can do away with the userInputAnimationToggle1 class altogether

.userInputAnimationToggle1{
    display: none;
}

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

Incorporating custom CSS and HTML into the link is essential for enhancing the appearance of KnpMenu

I'm working with the KnpMenuBundle and I need to customize a link that has the route 'uri'=>'#'. How can I achieve this? The desired link should be styled like this: <a href="#" class="js-sub-menu-toggle"> &l ...

Navigating a Frame and Clicking a Link with Puppeteer: A Step-by-Step Guide

I am facing an issue with clicking on an anchor link within a page that is supposed to open a new tab for exporting a PDF. The problem arises because this link is located inside a frame within a frameset structure as shown below: https://i.stack.imgur.com ...

React Native's NativeBase checkbox component: Overlapping text causing the content to extend beyond the confines of the screen

I am having trouble getting the text inside a checkbox (using nativebase) to shrink. Does anyone know why this is happening? Do I need to add some flex properties? import React from "react" import {Box, Center, Checkbox, Heading, NativeBaseProv ...

I continuously encounter "undefined" when attempting to retrieve collections

Despite my best efforts, I am unable to retrieve the data from the server using the snapshot docs. I have verified that the collection is named "creaciones" in lowercase. There is one document in the collection with existing data. I have double-checked fo ...

What is the solution using high-order functions?

I am struggling with a problem I came across on the internet. The task at hand is to identify all unique elements in an array that are less than 10, calculate the sum of these elements, and then multiply each element in the array by this sum. I have heard ...

Combining PHP and HTML: Utilizing nested foreach loops with interspersed HTML code

Attempting to create a layout of items using an Accordion arrangement (from Bootstrap) has led me to retrieve data from a pgsql db. Fortunately, the data retrieval process is successful. The challenge lies in displaying this data, as I am encountering an ...

I have noticed that the Javascript code is being loaded prior to the completion of my HTML/CSS page for some unknown

I am completely new to the world of web development. I'm encountering an issue where my JavaScript code (specifically alerts) is loading before my HTML/CSS page has fully loaded. I've been using sample alerts to test this out, and ideally, they s ...

Issues with TypeScript arise when transferring arguments between functions

Encountering a TypeScript error due to this pattern: Error message: 'Argument of type '(string | number)[]' is not assignable to parameter of type 'string[] | number[]' function foo(value: string | number) { return bar([va ...

Redis data retrieval is successful on the second attempt

I am utilizing a Redis database along with express routing to create an API. My stack includes node.js and ioredis as well. The process involves connecting to Redis, fetching keys related to a specific date, and then retrieving the data associated with th ...

Share JSON data across functions by calling a function

I am currently working on a project where I need to load JSON using a JavaScript function and then make the loaded JSON objects accessible to other functions in the same namespace. However, I have encountered some difficulties in achieving this. Even after ...

splitting up the lengthy list into manageable chunks according to the screen dimensions

How can I make the blue color row-based list (the divs inside a div with id phrase) break on the next line based on the screen size? Any suggestions on additional changes needed in the following CSS? #phrase { color: #fff; position: ...

A guide to building a versatile dropdown component with Material UI or MUI in a React application

Is there a way to create a reusable dropdown component using Material UI or MUI in React? ...

Troubles with showcasing icons on a website

I need some help with a minor issue that I'm stuck on. I'm trying to display an information icon that, when clicked, opens a pdf. The strange thing is that the icon doesn't show up on the page even though it exists on the server. However, wh ...

Why isn't my Vue2 data updating in the HTML?

Starting my journey with Vue, I have been finding my way through the documentation and seeking support from the Vue community on Stack Overflow. Slowly but steadily, I am gaining a better understanding of how to create more complex components. The issue I ...

Using the scroll feature in the selectyze plugin allows for smooth

The jQuery plugin selectyze from https://github.com/alpixel/Selectyze serves to replace the standard selectbox (dropdown), but there is a small issue that can be quite irritating. I am hoping someone out there may have a solution. Annoying Situation Here ...

Firefox returns a "null" error when attempting to access the Vimeo API, whereas there are no errors reported when accessing the YouTube API or when

I tried researching this issue on multiple platforms, including Google and other forums, but I am still unable to resolve it. I recently transitioned from a proxy request approach (using AJAX to communicate with a server-side script that then interacts wit ...

How can permissions for video and audio be configured in Next.js?

When the button is clicked, I want to set permissions. This is how I'd like the scenario to play out: first, the method works initially and allows permission when the button is pressed. Here is my code: <button onClick={requestPermission} classN ...

JavaScript Functions for Beginners

I'm currently facing some challenges with transferring the scripts and HTML content from the calendar on refdesk.com. My task involves moving the JavaScript to a separate stylesheet and utilizing those functions to replicate the calendar on an HTML pa ...

Utilizing Unidirectional Binding within an AngularJS Directive

I have a directive set up here: myApp.directive('stoplight', function() { return { restrict:'E', transclude: true, scope: { value: '@' }, link: function(scope, element) ...

My React JS page suddenly turned blank right after I implemented a setState() function within my functional component

I was working on my code and everything seemed fine until I tried to incorporate the setState function with setcategory and setvalue. However, after making this change, my react page suddenly went blank. Can anyone help me identify what went wrong and pr ...