0

I would like to get certain css property (for example the border-color) of any elements, but when its on a 'non-base' states, such as focus and hover. For example:

<style>
    .input {
        border: 1px solid red;
    }
    .input:focus {
        outline: none;
        border-color: green;
    }
</style>

<input type="text" class="input">

<script>
    let input = document.querySelector('.input');
    const inputBorderColor = window.getComputedStyle(input).getPropertyValue('border-color');
    console.log(inputBorderColor); // rgb(255, 0, 0)
</script>

Using getComputedStyle, I can grab the border color of the input for the 'base' state, but how do I get the border color for when the input is on focus (in this case border-color: green)?

Ahmad ikram
  • 140
  • 2

1 Answers1

0
const input = document.querySelector('.input');
input.addEventListener("focus", function() {
  console.log(window.getComputedStyle(input).color)
});

Codepen: https://codepen.io/disaladamsas/pen/KKvNZYz?editors=1111

  • With this solution, the value only becomes available when the user focuses on the input. Is there a way to get the value on page load (without having the need for user to interact with the input element)? – Ahmad ikram Nov 24 '21 at 15:49
  • i think you should use css variables –  Nov 24 '21 at 23:55
  • https://stackoverflow.com/questions/4481485/changing-css-pseudo-element-styles-via-javascript –  Nov 24 '21 at 23:55
  • Under a more common case, yes I would use css variables. But what I'm trying to achieve here is to generate a js object containing css properties related to the input. – Ahmad ikram Nov 25 '21 at 11:09