Explore various locations and conceal different divs by clicking

Can someone help me figure out how to hide the placeholders when the focus changes in a form? Here is the code snippet that illustrates my problem.

Your assistance is greatly appreciated, João

var inputs = Array.prototype.slice.call(document.querySelectorAll(".inpt"));
var list = ["YOUR NAME", "YOUR E-MAIL ADDRESS", "YOUR PHONE NUMBER"];
var upholder = document.getElementsByClassName("upholder");
var lol = document.getElementById("row-normal-3");

for (i = 0; i < upholder.length; i++) {
    upholder[i].classList.add("hide");
}

inputs.forEach(function slideUp(ipt, index) {
    ipt.addEventListener("click", function slideUpTwo() {
        upholder[index].classList.remove("hide");
        upholder[index].classList.add("show");
        upholder[index].innerHTML = list[index];
    })
})
.show {
  display:flex;
}

.hide {
  display:none;
}
<div class="le-form">
                    <form method="POST">
                       <div class="le-input">
                           <div class="upholder"></div>
                           <input class="inpt" type="text" name="name" placeholder="Your name">
                       </div>
                       <div class="le-input">
                           <div class="upholder"></div>
                           <input class="inpt" type="email" name="_replyto" placeholder="Your e-mail address">
                       </div>
                       <div class="le-input">
                           <div class="upholder"></div>
                           <input class="inpt" type="text" name="phone" placeholder="Your phone number">
                       </div>
                        <input type="submit" value="Send" class="form-btn">
                    </form>
                </div>

Answer №1

To ensure a smooth transition when applying class changes to a specific input field, it is recommended to first hide all input fields before making the changes.

var inputs = Array.prototype.slice.call(document.querySelectorAll(".inpt"));
var list = ["YOUR NAME", "YOUR E-MAIL ADDRESS", "YOUR PHONE NUMBER"];
var upholder = document.getElementsByClassName("upholder");
var lol = document.getElementById("row-normal-3");

for (i = 0; i < upholder.length; i++) {
  upholder[i].classList.add("hide");
}

inputs.forEach(function slideUp(ipt, index) {
  ipt.addEventListener("click", function slideUpTwo() {
    hideAllLabels();

    upholder[index].classList.remove("hide");
    upholder[index].classList.add("show");
    upholder[index].innerHTML = list[index];
  })
})

var hideAllLabels = function() {
  for (i = 0; i < upholder.length; i++) {
    upholder[i].classList.remove("show");
    upholder[i].classList.add("hide");
  }
}
.show {
  display: flex;
}

.hide {
  display: none;
}
<div class="le-form">
  <form method="POST">
    <div class="le-input">
      <div class="upholder"></div>
      <input class="inpt" type="text" name="name" placeholder="Your name">
    </div>
    <div class="le-input">
      <div class="upholder"></div>
      <input class="inpt" type="email" name="_replyto" placeholder="Your e-mail address">
    </div>
    <div class="le-input">
      <div class="upholder"></div>
      <input class="inpt" type="text" name="phone" placeholder="Your phone number">
    </div>
    <input type="submit" value="Send" class="form-btn">
  </form>
</div>

Answer №2

It seems like you are interested in:

  • An event that is triggered when the element loses focus
  • An event that not only triggers when the user clicks on the field, but also when they press tab to enter it.

I have modified your code to utilize focus instead of click to set the tooltip and blur to remove it. The functionality works smoothly.

Explore the variety of events HTML offers: https://developer.mozilla.org/en-US/docs/Web/Events

var inputs = Array.prototype.slice.call(document.querySelectorAll(".inpt"));
var list = ["YOUR NAME", "YOUR E-MAIL ADDRESS", "YOUR PHONE NUMBER"];
var upholder = document.getElementsByClassName("upholder");
var lol = document.getElementById("row-normal-3");

for (i = 0; i < upholder.length; i++) {
    upholder[i].classList.add("hide");
}

inputs.forEach(function slideUp(ipt, index) {
    ipt.addEventListener("blur", function () {
        upholder[index].classList.add("hide");
        upholder[index].classList.remove("show");
    })

    ipt.addEventListener("focus", function slideUpTwo() {
        upholder[index].classList.remove("hide");
        upholder[index].classList.add("show");
        upholder[index].innerHTML = list[index];
    })
})
.show {
  display:flex;
}

.hide {
  display:none;
}
<div class="le-form">
                    <form method="POST">
                       <div class="le-input">
                           <div class="upholder"></div>
                           <input class="inpt" type="text" name="name" placeholder="Your name">
                       </div>
                       <div class="le-input">
                           <div class="upholder"></div>
                           <input class="inpt" type="email" name="_replyto" placeholder="Your e-mail address">
                       </div>
                       <div class="le-input">
                           <div class="upholder"></div>
                           <input class="inpt" type="text" name="phone" placeholder="Your phone number">
                       </div>
                        <input type="submit" value="Send" class="form-btn">
                    </form>
                </div>

Answer №3

Conceal all the placeholder texts before revealing the specific focus element's placeholder text. To achieve this, simply include the forloop within the click function.

var inputs = Array.prototype.slice.call(document.querySelectorAll(".inpt"));
var list = ["YOUR NAME", "YOUR E-MAIL ADDRESS", "YOUR PHONE NUMBER"];
var upholder = document.getElementsByClassName("upholder");
var lol = document.getElementById("row-normal-3");

for (i = 0; i < upholder.length; i++) {
  upholder[i].classList.add("hide");
}

inputs.forEach(function slideUp(ipt, index) {
  ipt.addEventListener("click", function slideUpTwo() {

    for (i = 0; i < upholder.length; i++) { //hide all upholder
      upholder[i].classList.add("hide");
    }
    upholder[index].classList.remove("hide");
    upholder[index].classList.add("show");
    upholder[index].innerHTML = list[index];
  })
})
.show {
  display: flex;
}

.hide {
  display: none;
}
<div class="le-form">
  <form method="POST">
    <div class="le-input">
      <div class="upholder"></div>
      <input class="inpt" type="text" name="name" placeholder="Your name">
    </div>
    <div class="le-input">
      <div class="upholder"></div>
      <input class="inpt" type="email" name="_replyto" placeholder="Your e-mail address">
    </div>
    <div class="le-input">
      <div class="upholder"></div>
      <input class="inpt" type="text" name="phone" placeholder="Your phone number">
    </div>
    <input type="submit" value="Send" class="form-btn">
  </form>
</div>

Answer №4

To ensure a clean interface, consider hiding all existing placeholders prior to displaying the relevant one in relation to the selected input. The implementation of a function such as "hideAllUpHolders" can streamline this process. Additionally, having a separate function dedicated to hiding upholders when focus shifts to an external element can further enhance the user experience, if deemed necessary.

Answer №5

Here is an alternative approach utilizing Array.Map().

If we look at the code snippet for upholder, the change can be made from:

var upholder = document.getElementsByClassName("upholder");

to (Converting HTML Node Collection to Array):

var upholder = [].slice.call(document.getElementsByClassName("upholder"));

In regard to the click event, the modification is made from:

upholder[index].classList.remove("hide");
upholder[index].classList.add("show");
upholder[index].innerHTML = list[index];

to:

upholder.map(function (el, i) {index === i ? 
        (el.classList.add("show"), el.innerHTML=list[index]) : 
        (el.classList.remove("show"), el.innerHTML="")});

Comprehensive solution:

window.onload = function () {
var inputs = Array.prototype.slice.call(document.querySelectorAll(".inpt"));
var list = ["YOUR NAME", "YOUR E-MAIL ADDRESS", "YOUR PHONE NUMBER"];
var lol = document.getElementById("row-normal-3");
var upholder = [].slice.call(document.getElementsByClassName("upholder"));

inputs.forEach(function slideUp(ipt, index) {
ipt.addEventListener("click", function slideUpTwo() {
upholder.map(function (el, i) {index === i ? 
                            (el.classList.add("show"), el.innerHTML = list[index]) :
    (el.classList.remove("show"), el.innerHTML = "")
});
})
})
}
<style type="text/css">
.show {
display: flex;
}

.hide {
display: none;
}
</style>

<div class="le-form">
<form method="POST">
<div class="le-input">
<div class="upholder"></div>
<input class="inpt" type="text" name="name" placeholder="Your name">
</div>
<div class="le-input">
<div class="upholder"></div>
<input class="inpt" type="email" name="_replyto" placeholder="Your e-mail address">
</div>
<div class="le-input">
<div class="upholder"></div>
<input class="inpt" type="text" name="phone" placeholder="Your phone number">
</div>
<input type="submit" value="Send" class="form-btn">
</form>
</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

issues with padding in the main content section

When I try to search for something that isn't on the page, a strange margin or padding issue occurs. I have thoroughly reviewed the code but can't seem to pinpoint the problem. The unwanted 30pxish margin after the footer should not be present wi ...

View content from a text file on a webpage

Hi everyone, I could really use some assistance with a project I'm currently working on. As someone who is new to programming, I am facing a challenge. My goal is to showcase the contents of a plain text file on a webpage. This text file, titled titl ...

Ways to implement a filter pipe on a property within an array of objects with an unspecified value

Currently, I'm tackling a project in Angular 8 and my data consists of an array of objects with various values: let studentArray = [ { Name: 'Anu', Mark: 50, IsPassed: true }, { Name: 'Raj', Mark: 20, IsPassed: false }, { Na ...

Guide on setting the dropdown's selected index through JavaScript

Is there a way to use javascript to set the selected value of a dropdown? Here is the HTML code I am working with: <select id="strPlan" name="strPlan" class="formInput"> <option value="0">Select a Plan</option> </select> I am ...

NextJs application displaying empty homepage and preventing redirection

After successfully deploying my nextjs app on netlify, I encountered a strange issue. When I visit the base url of my website, instead of seeing the homepage, all I get is a blank screen. Oddly enough, if I navigate to specific pages on my site, they load ...

Prevent the user from selecting an option if the value is already present

In the process of creating a library membership form, I am utilizing an ajax request to populate the student list in a select option. The goal now is to disable the options for students who are already members of the library. View of the Form <div cla ...

Encountering issues with jQuery AJAX POST request

I'm currently facing an issue while attempting to send a post request to parse JSON formatted data into my webpage. Here's an example of the query: $("#click").click(function () { $.ajax({ type: "POST", url: "http://ut-pc-236 ...

Using Angular.js to Make a $http.get Request from a Different Controller

I am utilizing an HTTP resource that provides a JSON list of top 10 entities from a database by calling it in this manner: var filter= "john"; var myApp = angular.module('myApp', []); myApp.controller('SearchController', [&apo ...

Encountering a problem with GraphQL API fetching in Next.js: receiving the error message "React functionality 'useContext' is not supported in this environment."

Currently, I have developed a Next.js 14.2.3 application with a GraphQL API endpoint (which I replaced with localhost for StackOverflow). For data fetching, I am utilizing "@apollo/client": "^3.10.3" and "graphql": "^16.8.1". The product page path has been ...

Classify the JavaScript objects according to the array of object lists

Struggling to find a solution for converting this list of objects based on the group array. The challenge lies in iterating through the group Array and applying the object to multiple places when there are several groups. Additionally, trying to disregard ...

Troubleshooting issues with static serving in Express.js

I'm facing an issue while trying to apply a bootstrap theme to a file created using Jade. The error message indicates that it cannot GET the file. Main JavaScript code snippet: const express = require('express'); const app = express(); ap ...

Update the dropdown field selection to the color #333 with the help of javascript

I am facing an issue with a dropdown field that has placeholder text and options to select. Initially, both the placeholder text and the options were in color #333. However, I managed to change the color of the placeholder text to light grey using the foll ...

HTML5 for Bulk Video Upload

Is it possible to use the html5 api to record and upload video content directly from the browser? I am facing an issue in a project where the video recordings can be very long or large, causing extended upload times for users. Ideally, I would like the vi ...

Creating a custom navigation bar that elegantly fades away with a smooth animation as you scroll down the page is a must-have

How can I create a navigation bar that disappears when scrolling, with a smooth animation? This is the progress I have made so far. HTML: <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="css/style.css" type="tex ...

Validation of PO Box Addresses Using Regular Expressions

I'm having trouble getting the alert to work with my code. $(document).ready( function (){ $("[id*='txtAddress1S']").blur(function() { var pattern = new RegExp('\b[P|p]*(OST|ost)*\.*\s*[O|o|0]*(ffice|FFICE)*& ...

Displaying JSON with AngularJS HTTP Get request won't work in my project

As I delve into the world of AngularJS, I find myself caught up in a puzzle that has consumed my entire evening. My goal is to fetch JSON data from a random generator and display it in the view using a service. While {{ main.title }} seems to be working ju ...

Creating the document.ready function in Angular2 with JQuery

I am seeking assistance to modify the JQuery function so that it can run without the requirement of a button click. Currently, the function only executes when a button is clicked. Code declare var jQuery: any; @Component({ selector: 'home-component ...

Troubleshooting VueJS's Dilemma with Quotation Marks

When I try to parse a string containing either double quotes or single quotes, an error is being thrown: JSON Unexpected token. Is there a way to properly parse and bind it to a variable in Vue.js? PHP $arr = array(); $arr[0]['description'] = ...

Problem with onblur and onchange events not being triggered in input tag

After encountering this issue, I came to the realization that the events onblur and onchange function properly. However, I noticed that if your page contains only ONE <input type="text" onblur="loadXMLDoc()"> Change Content</input> The behav ...

What steps can be taken to remove a server-side validation error message once the user has inputted the correct value?

I'm facing an issue with server-side validation messages on my form, which includes fields for Name, Mobile, Email, and Message. While JQuery validation works fine, clearing the error message after user input is causing a problem. Using AJAX to submi ...