Is there a method to preserve the pressed/focused state when moving from one input box to the next?

While creating a form for a client, I encountered a requirement where the input box should change once clicked and retain that change even after it has been filled and the user moves to the next input box. Is there a way to achieve this using only HTML & CSS without any JavaScript? If incorporating JS is necessary, we are open to that as well.

https://i.stack.imgur.com/HG1rf.png

https://i.stack.imgur.com/bbMHg.png

https://i.stack.imgur.com/ogJYs.png

If needed, I can provide the code. What I really want to know is if there's a method to maintain the state of the input boxes when moving to another state.

Pic 1 shows how the form looks empty. Pic 2 demonstrates the desired appearance after filling the form and moving to the next field. Pic 3 illustrates the look when advancing to the subsequent input box.

Here's the provided code:

<!DOCTYPE html><!--  This site was created in Webflow. http://www.webflow.com  -->
<!--  Last Published: Wed Oct 13 2021 17:42:31 GMT+0000 (Coordinated Universal Time)  -->
<html data-wf-page="61660acbd4da295dda70c6e3" data-wf-site="61660acbd4da29651970c6e2">
<head>
  <meta charset="utf-8">
  <title>CCEC Tool Enrollment</title>
  <meta content="width=device-width, initial-scale=1" name="viewport">
  <meta content="Webflow" name="generator">
  <link href="css/normalize.css" rel="stylesheet" type="text/css">
  <link href="css/webflow.css" rel="stylesheet" type="text/css">
  <link href="css/ccec-tool-enrollment.webflow.css" rel="stylesheet" type="text/css">
  <script src="https://ajax.googleapis.com/ajax/libs/webfont/1.6.26/webfont.js" type="text/javascript"></script>
  <script type="text/javascript">WebFont.load({  google: {    families: ["Michroma:regular","Roboto:100,300,regular,500,700,900"]  }});</script>
  <!-- [if lt IE 9]><script src="https://cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv.min.js" type="text/javascript"></script><![endif] -->
  <script type="text/javascript">!function(o,c){var n=c.documentElement,t=" w-mod-";n.className+=t+"js",("ontouchstart"in o||o.DocumentTouch&&c instanceof DocumentTouch)&&(n.className+=t+"touch")}(window,document);</script>
  <link href="images/favicon.ico" rel="shortcut icon" type="image/x-icon">
  <link href="images/webclip.png" rel="apple-touch-icon">
</head>
<body class="body">
  <div class="wf-section">
    <div class="w-container">
      <h1 class="heading">CCEC NEW TOOL ENROLLMENT</h1>
      <div class="w-row">
        <div class="w-col w-col-6">
          <div class="w-form">
            <form id="email-form" name="email-form" data-name="Email Form" method="get"><label for="name" class="field-label">TOOL NAME</label><input type="text" class="textfield w-input" maxlength="256" name="name" data-name="Name" placeholder="" id="name"></form>
            <div class="w-form-done">
              <div>Thank you! Your submission has been received!</div>
            </div>
            <div class="w-form-fail">
              <div>Oops! Something went wrong while submitting the form.</div>
            </div>
          </div>
        </div>
        <div class="w-col w-col-6">
          <div class="w-form">
            <form id="email-form-2" name="email-form-2" data-name="Email Form 2"><label for="name" class="field-label-3">TOOL DESCRIPTION</label><input type="text" class="textfield w-input" maxlength="256" name="name-2" data-name="Name 2" placeholder="" id="name-2"></form>
            <div class="w-form-done">
              <div>Thank you! Your submission has been received!</div>
            </div>
            <div class="w-form-fail">
              <div>Oops! Something went wrong while submitting the form.</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <script src="https://d3e54v103j8qbb.cloudfront.net/js/jquery-3.5.1.min.dc5e7f18c8.js?site=61660acbd4da29651970c6e2" type="text/javascript" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
  <script src="js/webflow.js" type="text/javascript"></script>
  <!-- [if lte IE 9]><script src="https://cdnjs.cloudflare.com/ajax/libs/placeholders/3.0.2/placeholders.min.js"></script><![endif] -->
</body>
</html>

.body {
  border-top: 1px solid #2b2b2b;
  background-color: #2b2b2b;
  color: #fff;
}

.form-block {
  width: 1100px;
  margin-top: 198px;
  margin-left: 122px;
}

.text-field {
  border: 1px none #000;
  opacity: 1;
}

.text-field-2 {
  border-style: none none solid solid;
  border-width: 1px 1px 2px;
  border-color: #000 #000 #fff;
  background-color: #2b2b2b;
  background-clip: border-box;
  -webkit-text-fill-color: inherit;
}

.heading {
  font-family: Michroma, sans-serif;
  font-size: 30px;
  font-weight: 400;
  text-align: center;
}

.field-label {
  font-family: Roboto, sans-serif;
  font-size: 18px;
  font-weight: 500;
}

.field-label-2 {
  font-weight: 400;
}

.field-label-3 {
  font-family: Roboto, sans-serif;
  font-size: 18px;
  font-weight: 500;
}

.textfield {
  border-style: none none solid;
  border-width: 1px;
  border-color: #000 #000 #fff;
  background-color: #2b2b2b;
  font-family: Roboto, sans-serif;
  color: #fff;
  font-size: 18px;
  font-weight: 300;
}

.textfield:active {
  border-style: none;
  background-color: #a6a8ab;
  color: #000;
  font-weight: 500;
  background-clip: border-box;
  -webkit-text-fill-color: inherit;
}

.textfield:focus {
  border-style: none;
  border-color: #000 #000 #fff;
  background-color: #a6a8ab;
  color: #000;
  font-weight: 500;
  -o-object-fit: fill;
  object-fit: fill;
}

.text-field-4 {
  border-style: none none solid;
  border-width: 1px;
  border-color: #000 #000 #fff;
  background-color: #2b2b2b;
}

.texty:focus {
  background-color: #000;
  color: #fff;
}

.contact-form {
  padding-top: 100px;
  padding-bottom: 100px;
}

.contact-form-grid {
  display: -ms-grid;
  display: grid;
  margin-top: 40px;
  grid-auto-columns: 1fr;
  grid-column-gap: 20px;
  grid-row-gap: 20px;
  -ms-grid-columns: 1fr 1fr;
  grid-template-columns: 1fr 1fr;
  -ms-grid-rows: auto;
  grid-template-rows: auto;
}

@media screen and (max-width: 767px) {
  .contact-form {
    padding: 40px 20px;
  }

}

Answer №1

Utilize the :valid and :focus pseudo-classes to customize the style of an input field. When using :focus, you can modify the appearance of the input field when it is in focus, while :valid will maintain the specified style if the user enters valid input and then moves on from the field.

#myfield:valid{
  background:orange;
}
#myfield:focus{
  background: orange;
}
<input type="text" id="myfield" required>

Answer №2

To determine the level of validation for an input field, consider whether you want a basic "not empty" check or more thorough validation. You can implement a starting point using the following CSS code:

/* Show red borders when filled, but invalid */
input:not(:placeholder-shown) {
  border-color: hsl(0, 76%, 50%);
}

Show green borders when valid
input:valid {
  //apply same styles you have on :focus
}
  • Source:

Answer №3

With the power of JavaScript, meeting your client's requirements is a breeze. By maintaining the :focus class as it is and introducing a secondary class with similar style modifications, you can efficiently enhance user experience. Simply attach an event listener to the entire form (or group of inputs) to detect keyup actions by the user. If the textbox remains empty, the styling will remain unchanged. However, if there is input detected, the additional class will be applied.

const inputsBox = document.querySelector('#inputs')

function changeClass(e){
    let box = e.target;
    box.value !== '' ? box.classList.add('filledOut') : box.classList.remove('filledOut')
}

inputsBox.addEventListener('keyup', changeClass)
#inputs {
  display: flex;
  flex-direction: column;
  width: 30%;
}

input {
  border: 1px solid black;
  transition: all 0.2s linear;
  padding: 8px;
  margin: 2px;
}

input:focus, .filledOut {
  border: 1px solid #fafafa;
  background: grey;
}
  <div id="inputs">
    <input/>
    <input/>
    <input/>
    <input/>
    <input/>
  </div>

Answer №4

If you want to enhance user experience, consider implementing Javascript

HTML

<input id="inputBox" />

Css

input {
    border: 1px solid #000;
    background: red;
}

input.is-focus {
    border: 1px solid #fafafa;
    background: blue;
}

Javascript

document.getElementById("inputBox").addEventListener('focus', (e) => {
    e.target.classList.add("is-focus");
})

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

Disable the movement and dragging functionality of the scroll feature in Google Maps using React

I have a map.jsx file in my React application that contains the code below: import React from 'react'; import GoogleMapReact from 'google-map-react'; import './map.css'; const Map = ({ location, zoomLevel }) => ( <d ...

Building a dynamic cities dropdown menu in ReactJs based on the chosen country

I have an array called countryList that looks like this: export const countryList = [ {name: 'Singapore', code: 'SG', cities:[ "Ang Mo Kio New Town", "Ayer Raja New Town", ...

I'm curious about the meaning behind this code snippet: `$Odd = ($Odd == "even") ? "odd" : "even";`. Any ideas?

<?php $Odd = "even"; $query = $MySQLi->query("SELECT id, look, username, motto FROM users WHERE rank = '7'"); if($query->num_rows > 0): while($UserRow = $query->fetch_assoc()) { $Odd = ($Odd == "even") ? "odd" : "even"; ?&g ...

Attempting to modify the key values within an object, however, it is mistakenly doubling the values instead

I'm encountering an issue when trying to update key values within an object. It seems to be adding duplicate values or combining all values together instead of assigning each name a specific language slug. I can't figure out where I'm going ...

The JSX in React won't display the modified state on the user interface

In my diary object, I have records of 2 meals function Magicdiary() { const [diary, setDiary] = React.useState<MagicDiaryDay[]>([ { mealName: "Breakfast", ingredient: null }, { mealName: "Lunch", ingredient: null }, ]) ...

Strange symbols were stored in the database after saving the textarea value

After submitting a form, text entered into a text area is being saved to my database. However, in one instance, certain characters such as • are appearing in the field. For example: • Text When retrieving the data from the database using Jav ...

The hover effect does not carry over to duplicated HTML

I successfully added a node, but I forgot to include the hover function of the node in my application. The hover function is not necessary, and I need it to work with ie8 compatibility. Here's my HTML: <div id="appendCell" style="color:green; colo ...

Alerts for drop down menu validation with multiple buttons

My goal is to design a multi-step form that collects user information. This form consists of 5 stages: Step 1: User details (Name, email, phone, age, gender) Step 2: Yes or No question Step 3: Yes or No question Step 4: Yes or No question Step 5: Yes o ...

The term 'sequelize' is missing its definition - it involves Sequelize and consign

Just starting out in the world of Node.js. I'm currently working on integrating Sequelize into a basic application with Consign. In my "config/db.js" file: var Sequelize = require('sequelize'); var sequelize = new Sequelize('test&ap ...

Preventing repetition of data and storing submitted form inputs in a cache

I am facing an issue with my code that checks for duplicate entries based on the USER ID in the database. When I submit the form and the USER ID already exists, it clears all other fields on the form, requiring me to re-enter all details again. This is fru ...

In all tests, except for the initial one, the DOM is not updated by test-utils once triggers have been fired

I have been facing an issue with checking for error messages related to field completion in HTML/DOM after vuelidate is triggered. The functionality works properly after the click trigger, and all tests pass successfully - including mounting, element searc ...

Tips for retaining the scroll position of a particular page after a postback

I am working on a grid to display data row by row. Each row is displayed using a user control. When I scroll to the bottom of the page and click on a row, it redirects me to a view page for that specific row. However, when I click on the back link, I would ...

Finding Text Between Two Distinct Strings Using Regular Expressions in JavaScript

I am currently utilizing AJAX technology. My approach involves sending a GET request that retrieves a raw HTML string representing the content of a webpage. I am grappling with the challenge of isolating all elements enclosed between div tags: <div ro ...

Is there a way to create a flexbox that combines a centered fixed child with a fixed child at the bottom?

I'm trying to create a layout using flexbox that looks like this: | | | | | CENTER FIXED ELEMENT | | | | BOTTOM FIXED ELEMENT | Here is the flexbox CSS I've attempted: .wrapper{ ...

Is the phrase "This site was built with Wix" visible on the website?

Recently, I've begun using Wix to build a website. I'm curious - does the message 'This website is created using Wix' appear at the top and bottom of the page when it's published? 'This website is created using Wix' I ...

Incorporating dynamic images into Laravel using Angular

I am currently trying to dynamically input the src value of an image using Angular. Below is the code I have written : HTML : <div ng-app="myApp" ng-controller="MyCtrl"> <img src="{{asset('assets/img/'.'/'. @{{ item.name ...

Guide to discovering an almost ascending sequence in an Array

I recently encountered a challenging algorithm problem that I need help with: "I have a sequence of integers stored in an array. My task is to determine whether it is possible to obtain a strictly increasing sequence by removing no more than one element f ...

Having trouble with sending a list of items from a VueJS form

I have a VueJS application that calls a patch method to update a user's profile. For example, I am attempting to update the field cities. I created a serializer and views.py using Postman during development. I used Postman to call the patch method fo ...

How can socket listener be dynamically added in node.js with socket.io?

Assuming you have a basic socket.io configuration set up: var app = require('http').createServer().listen(80,'127.0.5.12'), io = require('socket.io').listen(app); session = require('./local_modules/session.js'); / ...

What is the best way to store JSON data in the state of a ReactJS application?

I need assistance with a data format related issue. The current format of the data is being set by someone else in the backend of the application. When the data is empty, it looks like this: "opening_time":{"Mon":[["0"],["0"]], "Tue":[["0"],["0"]], "Wed" ...