[Vuejs]-Adding content to input from :before css on focus

0👍

Like @connexo commented on your question, you won’t be able to access content of ::before & ::after directly from javascript.

However, you could ask css to load content from the element’s attribute & manipulate that attribute in javascript.

Add a new attribute in your div. I’ll call this data-num for this example:

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

Then in css, use attr() function to fill 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 can set whatever string you’d like for that content in js:

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 fiddle

You won’t be able to use attr() for anything other than content, but its support is pretty good: caniuse: attr()

Please note that even though it works, this might not be the best way to achive what you want – you could easily do this with a real element instead.

Leave a comment