Injecting information into an input field using the :before pseudo-class in CSS when focus

In order to have a static part "+91" displayed in an input field upon focus, I have successfully replaced the placeholder during onFocus and onBlur events. However, I am unable to add a listener to read content from :before.

<div class="goal-mobile">
  <input id="mobileField" onblur="this.placeholder = 'Enter your mobile number'" onfocus="this.placeholder = ''" type="tel" class="input-mobile"/>
</div>

.goal-mobile{
    position: relative;
    &:before{
        content: "+91";
        position: absolute;
        left: 20px;
        top: 20px;
        color: rgba(3,3,3,.6);
    }
}

Although the class is set to load "+91" by default, I need it to be loaded when the input field is focused. I have tried using :focus::before{} without success. What alternative method can I use to achieve the default static display of "+91" in the input box upon onFocus?

PS: Since I am using the Vue JS framework, implementing jQuery may not be straightforward.

Answer №1

According to @connexo's input on your query, it is not possible to directly access the content of ::before & ::after using JavaScript.

Nevertheless, a workaround is to request CSS to load content from the element's attribute and then manipulate that attribute using JavaScript.

You can add a new attribute to your div. Let's name this attribute data-num for demonstration purposes:

<div class="goal-mobile" data-num="">
  <input id="mobileField" type="tel" class="input-mobile"/>
</div>

Subsequently, in the CSS code, utilize the attr() function to populate content:

.goal-mobile{
  position: relative;
}

.goal-mobile:before {
  content: attr(data-num);
  position: absolute;
  left: 20px;
  top: 20px;
  color: rgba(3,3,3,.6);
}

Now, you have the flexibility to set any desired string for that content in JavaScript:

const $mobile = document.querySelector('.goal-mobile');
const $mobileInput = document.querySelector('.goal-mobile input');

const phoneNum = '+91';

$mobileInput.onfocus = () => {
  $mobile.setAttribute('data-num', phoneNum);
}

$mobileInput.onblur = () => {
  $mobile.setAttribute('data-num', '');
}

Here's a demo link for reference.

Please be aware that while this method is functional, it may not be the most efficient approach to achieve your objective - using an actual element could be a simpler solution.

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

Obtain Data Grid from Website

I need to extract a table with the following columns: "Date|Open|High|Low|Close|No.of Shares|No.of trades|Total Turnover|Deliverable Qty" from the website "" Below is the code I am using: Sub Macro_BSE() Application.ScreenUpdating = False Dim File ...

The Architecture of a Symfony 3 Project with Integration of Vue.js and Webpack

As I prepare to develop an application with a REST API backend that will be utilized by a Vue.js frontend, my goal is to keep the frontend and backend code together in one repository. However, I am currently facing a dilemma regarding where to place my Vu ...

Enhance the impact of "dialogs" to the fullest extent or minimize it to achieve the

How can I position the minimized dialog on the bottom of the div when appending dialogs next to each other in a FB messaging system? To achieve a Facebook messaging effect, the titlebar must go down when minimizing/maximizing the dialog. Perform the follo ...

JQuery If Statement always outputs a consistent number regardless of the input provided

I'm facing an issue with my HTML form and JQuery code that is supposed to calculate a figure. The problem I am encountering is that the if statement always returns the same number, regardless of the input: $(document).ready(function() { ...

Changing the parent scope from the child component does not automatically reflect changes in an ng-repeat

I am facing an issue with the communication between a child controller and a parent controller. I have a function that adds data to a parent array which is used in an ng-repeat directive. Although the parent array gets updated correctly and its length is ...

The JQuery library seems to be unresponsive on my webpage, despite being correctly included

Despite trying multiple ways to include the JQuery library on my page, I keep encountering the "$ is not defined" error. I have ensured that all the links were correct and from various sources, both local and external. What other options should I consider ...

When my route in NextJS processes the request, it returns a ReadableStream from req

I am encountering an issue with my code and I have tried looking for solutions in other similar questions without any success. Is there anyone who can assist me? Here is the content of my route.js file: import dbConnect from "@/lib/dbConnect"; i ...

Discover the steps to implement a live user list in a chat application with the help of angular.js, socket.io, and node

Currently, I am in the process of developing a chat application with AngularJS and Socket.io. The current status of my project allows users to send and receive messages from different individuals. To gain access to the chatbox, users need to input their na ...

Issues arising with code splitting using React HashRouter in a project utilizing Typescript, React 17, and Webpack 5

Encountered build issues while setting up a new project with additional dependencies. package.json: { "name": "my-files", "version": "1.0.0", "description": "App", "main": " ...

How to conceal the day picker in jQuery UI datepicker

I am facing a problem that has been addressed before. As someone with only basic knowledge of CSS, I am a bit confused here. I have two datepickers in my code. <style> .ui-datepicker-calendar { display: none; } </style> Unfortunately, ...

Upon utilizing @nuxtjs/auth for logging in, I noticed that it sends a request with a URL that deviates from the one I initially provided

The Issue at Hand Utilizing the Nuxt.js module @nuxtjs/auth' for login authentication has resulted in an unexpected error. Specifically, upon using the loginWith method, instead of redirecting to the URL specified in the configuration, it redirects t ...

Interactive web page with dynamic JQuery functionality and navigable page links

I am working on the project/index.html page <html> <head> <title>Index</title> <scripts...> </head> <body> Hello <div id="content"></div> <button id="page1" value="page1"/> <but ...

Obtaining a file using capybara independently of rails

Case Study: Attempting to access an external URL using Capybara for downloading a file. It is necessary to use Selenium or Webkit as the driver, since Rack-test does not allow visiting external URLs. This website utilizes iframes. The prompt for file dow ...

Error: The property 'create' of undefined cannot be read (Material UI/enzyme)

When I mount a component, I encounter an error that does not occur when using shallow rendering. The specific error is: TypeError: Cannot read property 'create' of undefined at stylesOrCreator (node_modules/@material-ui/core/CircularProgress/C ...

The markers on Google Maps are currently displaying in the wrong position, despite the latitude and longitude being correct

Utilizing the Google Maps API, I have implemented a system to dynamically add map markers tracking 2 of our company's vehicles. The website is developed in asp.net c# mvc with bootstrap 4.3.1. An ajax request retrieves the latest marker location from ...

Encountering difficulties while attempting to convert JSON to XML resulting in an error being

I can't seem to figure out how to successfully convert the JSON result into XML format. I've tried the code below but it's not working as expected. Any help would be greatly appreciated. Here is the code snippet: <script src="../Jquery ...

Issues with PHP not retrieving selected radio button values

Currently, I am using a PHP webpage to generate a list of all files with a .264 extension in a specific folder. Once the file is selected, it is then sent to a command for video playback on a display connected to the computer. I have encountered some diff ...

The pipe property cannot be accessed for the specified type "OperatorFunction<unknown, [unknown, boolean, any]>"

I have set up a data subscription that I want to utilize through piping, but for some reason it's not working as expected. The error message I'm receiving is: The property pipe is not available for type "OperatorFunction<unknown, [unknown, b ...

Resolve the issue of text overflow in PrimeNG Turbo Table cells

When utilizing Primeng table and enabling the scrollable feature, the table is expected to display a scrollbar while ensuring that the text within the cells does not overflow. Unfortunately, this expected behavior is not occurring. To see an example of th ...

What steps can be taken to make the carousel inconsistent when relying on the assigned id in props?

I recently developed a slider with slots, but encountered an issue. The code for this component revolves around the use of IDs for each slide as prop, making it unnecessarily complex. I am convinced that there is a more straightforward way to achieve the s ...