Show a component when there is no input value, then conceal it when an input value is present

Recently, I attempted to position a paragraph absolutely in relation to an input element.

My goal is to conceal the paragraph when the input has a value, and reveal it when the input is empty.

Here is the code snippet I created, however, it doesn't seem to be functioning as expected. Any advice on how to improve this? Thank you.

var x = document.getElementById("searchBtn").value;

document.getElementById("searchBtn").addEventListener("focus", myFunction3);

function myFunction3() {
  if (x == "") {
    document.querySelector(".mypara").style.visibility = "visible";
  } else {
    document.querySelector(".mypara").style.visibility = "hidden";
  }

}
<input id="searchBtn">
<div class="mypara">mypara</div>

Answer №1

Make sure to use the input event instead of focusing.

To retrieve the value, use e.target.value.

document.getElementById("searchBtn").addEventListener("input", myFunction3);

function myFunction3(e) {
  let x = e.target.value
  document.querySelector(".mypara").style.visibility = x === "" ? "visible" : "hidden";
}
<input id="searchBtn">
<div class="mypara">mypara</div>

Answer №2

To ensure constant detection while typing, switch focus to keyup. Additionally, include x within myFunction3 to receive an updated value.

document.getElementById("searchBtn").addEventListener("keyup", function(e) {
  var x = e.target.value;
  document.querySelector(".mypara").style.visibility = x == "" ? "visible" : "hidden";
});
<input id="searchBtn">
<div class="mypara">mypara</div>

Answer №3

Make sure to declare x within the event listener so that the variable gets updated every time:

document.getElementById("searchBtn").addEventListener("focus", myFunction3);

function myFunction3() {
  var x = document.getElementById("searchBtn").value;
  if (x == "") {
    document.querySelector(".mypara").style.visibility = "visible";
  } else {
    document.querySelector(".mypara").style.visibility = "hidden";
  }

}
<input id="searchBtn">
<div class="mypara">mypara</div>

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

AngularJS modal behaving oddly when checkboxes are used

My Angular app is available in this plunker. Upon clicking the button, a modal dialog opens displaying a list of items. Two of these items are pre-checked based on conditions set in the checkbox table input. The following function handles pushing and spl ...

Combining PageObjects with non-angular pages: is it possible?

I am currently working on writing protractor tests for our application. One specific challenge I have encountered is dealing with a non-angular page within an angular page as an iframe. The issue I am facing is that I cannot properly map fields from the n ...

Alter the top property of CSS using JavaScript

Hey there! I'm currently working on a project where I want to gradually change the background when a button is clicked on my website. Below you'll find snippets of JavaScript and HTML code that I'm using for this purpose. Can you take a look ...

Is it possible to create a responsive Material UI tab design?

How can I make the Material UI tab react component responsive? Check out the documentation for MATERIAL UI TAB here If I have multiple tab items with a search bar like shown below, how can I ensure that the input component stretches the whole width of th ...

Unexpected display issue with Bootstrap-vue navbar component

I am currently working with bootstrap-vue and trying to implement a navbar component within my application. I followed the first example provided in the documentation at this link. All the necessary dependencies are installed as per the bootstrap-vue instr ...

Angular sends a POST request using $http to open in a new tab

In my Angular application, I am trying to send a POST request to a URL ./makeFile.php. This request will create a file with contents retrieved from a database query based on the data provided in the POST. When using PHP, the browser automatically opens a ...

Adjusting grids in Bootstrap according to device orientation

I have a vision for a webpage layout that will feature two columns in landscape mode and switch to one column in portrait mode. Here is an outline of what I have in mind: Landscape: <body> <div class="container-fluid"> <div cl ...

How to store data in MongoDB without relying on specific request bodies

I realize that I can simplify the code: var event = new EventModel(req.body); event.save....... If the input names match the attribute names in my database, mongoose can save by simply passing req.body. However, there is an issue with handling dateO sep ...

I require the CheckBox to be repositioned slightly lower

https://i.sstatic.net/xIi8m.png I'm trying to center align the checkbox between the Input and Button elements. I attempted using the "align-center" class in the "form-check" div, but it didn't work as expected. Could someone please provide me wi ...

I'm looking to replicate this navigation layout using Vuetify's 'navigation drawer' component. How can I go about doing this?

I'm currently utilizing Vuetify and implementing the Navigation Drawer component. I am attempting to replicate a similar navigation layout found here. The fixed menu on the left should maintain its width even when resizing the browser window. Upon ...

I'm trying to create a transparent v-card, but for some reason it's not turning out the way I want

How can I make the v-card transparent while keeping its content opaque using CSS? card.vue <v-card class="cardColor"> <v-card-text> TEXT </v-card-text> <v-card-actions> <v-btn color="prima ...

Utilizing the Google Geocode API to handle a promise with a substantial array

My Objective To efficiently process a large array using the .map method and interact with the Google Geocoder API through promises to get location data. The goal is to utilize Promise.all to store results in a .json file upon completion of the operation. ...

JavaScript - Combining nested arrays of JSON data into a single object

I'm looking to convert a nested JSON structure into a single object with dynamic keys. I attempted the code below, which only works for one level. I need help writing a recursive function to handle n levels of nesting. Any advice would be appreciated. ...

Utilize Angular functions in every controller in your application

Currently, I have important functionality code within app.run(function... in Angular: app.run(function($rootScope, $window) { // Obtain window dimensions $window.width = angular.element($window).width(); $window.height = angular.element($window).he ...

Tips for closing two nested Material-UI popovers when a button is clicked or when clicked elsewhere

Trying to create a menu with nested popovers from Material-ui has presented a challenge. I want all the popovers to close when I click on a menu option, rather than having to close them individually. Additionally, it would be more user-friendly if the popo ...

Experimenting with Vuejs by testing a function that delivers a Promise upon the execution of the "Created" hook

In my Vuejs application, I have the following script written in Typescript: import { Foo, FooRepository } from "./foo"; import Vue from 'vue'; import Component from 'vue-class-component'; import { Promise } from "bluebird"; @Component ...

What are the best practices for dynamically handling variables in JavaScript?

I am looking to dynamically work with variables and store their references in a collection. My first question is: How can I save a variable reference (not its value) in a collection? For example: var apple = "A delicious fruit"; var banana = "A yellow f ...

Having trouble displaying the output on my console using Node.js

Hey there, I'm new to this community and also new to the world of nodejs technology. I have encountered a problem that may seem minor to you but is quite big for me. Here's what's going on: In my code snippet, I want a user to input 3 value ...

Expanding the width of Material UI Javascript Dialog Box

Currently, I am utilizing the dialog feature from Material UI in my React JS project and I am looking to expand its width. After some research, I discovered that there is a property called maxWidth which allows you to adjust the width of the dialog. Howe ...

Reveal covert web data table

I am encountering difficulties while attempting to extract information from a table that does not seem to be visible. The specific table can be found on this page, within the 'Code History' section highlighted in light purple. Login credentials ...