What is the method for selectively applying a "fade to black" mask to an input field?

For my current project, I need to incorporate a design feature where a "fade to black" mask gradually appears on the left side of an input field once the text content reaches the maximum visible width of the input box.

The image below provides a visual representation of what I'm aiming to achieve: https://example.com/image.png

I have already started implementing this feature with the following code snippet:

var input = document.querySelector('#input');
var container = document.querySelector('.myInput');

input.addEventListener('keydown', function(e) {
  if (input.value.length > 12) {
    container.classList.add('faded');
  } else {
    container.classList.remove('faded');
  }
});
body {
  background: #000;
}

.myInput {
  position: relative;
}

.myInput input {
  font-family: "Trim", "NOW G", "Oscine";
  font-style: normal;
  font-weight: 500;
  font-size: 28px;
  background: #000;
  padding: 12px;
  color: #fff;
  box-sizing: border-box;
  margin: 0 0 0 10px;
  border: 1px solid #ccc;
  width: 200px;
}

.faded::before {
  display: block;
  background-image: -webkit-linear-gradient(left, black, rgba(0, 0, 0, 0));
  width: 20px;
  position: absolute;
  content: "";
  left: 15px;
  top: 1px;
  bottom: 1px;
}
<script src="https://example.com/jquery.min.js"></script>
<div class="myInput">
  <input id="input" placeholder="Search" />
</div>

Now, my challenge is to make this mask appear conditionally (without hardcoding the 12-character limit and input width) and to develop a responsive solution that will be compatible with varying widths and text sizes.

Any suggestions or ideas on how to approach this?

Answer №1

To determine if the input is overflowing, you can use the following code:

(input.offsetWidth < input.scrollWidth)

It is recommended to listen for the input event instead of keydown to capture the paste event as well.

Check out the code snippet below:

document.addEventListener('input', function(e) {
  if (e.target.nodeName.toLowerCase() === 'input') {
    var input = e.target;
    var container = input.parentNode;
    if (input.offsetWidth < input.scrollWidth) {
      if (!container.classList.contains('faded')) {
        container.classList.add('faded');
        var cs = getComputedStyle(input);
        container.querySelector('.shadow').style.left = [
          'border-left-width', 'margin-left', 'padding-left'
        ].reduce(function(a, e) {
          return a += parseInt(cs[e])
        }, 0) + 'px';
      }
    } else {
      container.classList.remove('faded');
    }
  }
});
body {
  background: #000;
}

.myInput {
  position: relative;
  margin:1rem;
}

.myInput input {
  font: normal 500 28px "Trim", "NOW G", "Oscine";
  background: #000;
  padding: 12px;
  color: #fff;
  box-sizing: border-box;
  margin: 0 0 0 10px;
  border: 1px solid #ccc;
  width: 200px;
}

.faded .shadow {
  position: absolute;
  top: 1px;
  bottom: 1px;
  width: 20px;
  background-image: linear-gradient(90deg, #000, rgba(0, 0, 0, 0));
}

#input2 {
  margin-left: 20%;
  padding-left: 3em;
}
<div class="myInput">
  <input id="input" placeholder="Search" />
  <span class="shadow"></span>
</div>


<div class="myInput">
  <input id="input2" placeholder="Search" />
  <span class="shadow"></span>
</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

Experiencing challenges with socket io connectivity between my backend and Quasar application. Encountering a 403 Forbidden error while trying to establish a connection with

I recently updated my Quasar app and ran into issues with the websocket connection after switching from development to production mode. The app is hosted on an Express server via pm2 on my Ubuntu server, which also connects to a database. Here are some sn ...

Ways to verify the click status of a button prior to initiating an AJAX request with jQuery?

I am facing an issue with a button that needs to be clicked by the user before submitting the form. Here's the code snippet for the button: $('#chooseButton') .on( 'click', function() { console.log("user ha ...

Incorporating FaceBook into a PhoneGap Application

Currently, I am working on integrating Facebook into my phonegap/cordova application. To guide me through the process, I am using the resources provided in this link: https://github.com/davejohnson/phonegap-plugin-facebook-connect/ Even though I have bee ...

Absolute file path reference in Node.js

I'm working on a Node.js project using WebStorm IDE. Here's the structure of my project: The root folder is named "root" and inside are 2 folders: "main" and "typings". The "main" folder has a file called "foo.ts", while the "typings" folder co ...

Blurring the edges of a div container

I have successfully faded the top of a div, but I am struggling to achieve the same effect for the bottom. I attempted to reverse the CSS properties used for fading the top, but it does not seem to be working as expected. HTML: <div class="container-c ...

Utilize text alignment effectively by considering language direction - left-to-right for English and right-to-left for Arabic

I am managing a community website and I am looking to customize the text direction based on the language of the posts. For English posts, I want the direction to be LTR with text-align: left) For Arabic posts, I want the direction to be RTL with text-ali ...

Maintaining the original size of the fill texture when resizing a path in SVG

I have created an SVG pattern using the following code: <svg height="10" width="10" xmlns="http://www.w3.org/2000/svg" version="1.1"> <defs> <pattern id="circles-1_4" patternUnits="userSpaceOnUse" width="10" height="10"> & ...

Vorlon.js is requesting Socket.io, even though its configuration already includes socket.io

Whenever I try to load the app, a red div appears in front with the message: Vorlon.js: make sure to load socket.io before referencing vorlon.js or set includeSocketIO = true in your catalog.json file. Every time I access the server page, my terminal d ...

Create a hierarchical tree structure using a string separated by dots

I am struggling with organizing a tree structure. :( My goal is to create a tree structure based on the interface below. export type Tree = Array<TreeNode>; export interface TreeNode { label: string; type: 'folder' | 'file'; ...

Ways to effectively conceal an HTML div element with CSS or JavaScript

Is there a way to hide the div element that is nested inside a bootstraps radio or checkbox container using jquery? I'm unable to upload an image, but here is a preview: http://prntscr.com/6wrk2m <style> .my-radio{ border: 1px solid #F0F; } &l ...

step by step guide on swapping a portion of a JSON string

I need to eliminate the character "C" from keys that start with C_ in the following JSON string. Here is the JavaScript object I have: var jsonData= { key1:val1, key2:val2, C_100:1, C_101:2, C_102:3, } The desired output should look like this: v ...

Eliminating the use of <ul> <li> tag within the validation-summary-errors

I am facing an issue with a website where the error message is displaying in a specific format. <div class="validation-summary-errors"> <span>Password change was unsuccessful. Please correct the errors and try again.</span> <u ...

Is it possible to automatically move text to the next line once it reaches a specific character limit using HTML/CSS/PHP?

Is there a way to handle text when it reaches the ceiling or exceeds a certain number of characters so that it goes to the next line instead of showing a scrollbar? I have a div element where I display text retrieved from a MySQL database, and sometimes th ...

The ComponentDidUpdate function treats the previous state (prevState) and the current state (this

Initially, I had a state update function that looked like this: doChangeValue(data) { const dataNew = this.state.data dataNew[data.id] = data.value this.setState({ ...dataNew, [dataNew[data.id]]: data.value}) } However, I realized that thi ...

What is the best way to create a sliding <nav> effect when a <div> is clicked?

Hello! I am looking for a solution that will cause the navigation contents to slide out from the left when the div class "bt-menu" is clicked. It should also slide back in to the left either when the div is clicked again or when anywhere outside of the nav ...

Discover the job specifications pages on Dice.Com by utilizing C programming language

I have taken on a student project involving web scraping job postings from Dice.Com for analysis. My main focus is on extracting the job description, but I am struggling to figure out how to access it. With limited knowledge in HTML and C#, I find it dif ...

The seamless integration of an HTML dropdown list in a form with a PHP email feature

Take a look at this HTML code snippet with PHP integration. How can I achieve this? I'm fairly new to coding. I'm currently developing a contact form that includes a dropdown menu for selecting an email address related to a specific physician. I ...

Decoding JSON with JavaScript following the response from JsonConvert.SerializeObject(json) in a .NET handler

I am currently working on a web application using the .NET platform. I have written a Handler code that returns a JSON object to JavaScript (after making an AJAX request). Here is the Handler code: var wrapper = new { left = left.ToString(), t ...

Is there a way to determine the duration that a click was held down for?

When triggering an onClick event, I want to determine whether it was a single click or if the mouse button was held down for some time before releasing. This way, I can call the myTest() function within onClick="myTest()", which will log "mouse was click ...

Navigating using passing data in ReactJs

The following data contains information about people: const people = [ { img: 11, name: "Ahmed", job: "developer", }, { img: 13, name: "Kazim", job: "Engineer", }, ...