How to customize the input: style focusing programmatically using JavaScript

I am creating a UI library in JS that can, without relying on any CSS stylesheets, create UI components styled from code. This has been pretty easy so far, aside from styling various control states (e.g. input: focus one).

The code I'm using to create the input field:

function newInput()
{
    var ctr = docmuent.createElement("input");
    ctr.setAttribute("type","text");
    ctr.setAttribute("value", some-default-value);
    ctr.style.fontFamily = "sans-serif,helvetica,verdana";
    /* some font setup here, like color, bold etc... */
    ctr.style.width = "256px";
    ctr.style.height = "32px";
    return ctr;
}

      

Arranging it by default is easy. However, I'm not sure how to set the style for states such as focused, disabled, or not editable.

If I have CSS stylesheets included in the project that sorted easily. However, I cannot include any CSS files, it should be pure JS.

Does anyone know how to style the state of an input field (like input: focus) right from JS code?

No JQuery please :-) Just straight JS.

Thanks in advance!

+4


source to share


3 answers


You will need to add an event listener to the element to change its style. Here's a very simple example.



var input = document.getElementById("something");
input.addEventListener("focus", function () {
  this.style.backgroundColor = "red";  
});
      

<input type="text" id="something" />
      

Run codeHide result


+3


source


Another alternative would be to create a stylesheet for the page.

Something like that:



 var styles='input:focus {background-color:red}';

 var styleTag=document.createElement('style');
 if (styleTag.styleSheet)
     styleTag.styleSheet.cssText=styles;
 else 
     styleTag.appendChild(document.createTextNode(styles));

 document.getElementsByTagName('head')[0].appendChild(styleTag);

      

This way you will have a clean separation of css styles from scripts and hence better service.

+2


source


First create your contribution:

<input type="text" id="myElementID" />

      

Then add the following javascript javascript:

const element = document.getElementById("myElementID");

// Add a box shadow on focus
element.addEventListener("focus", (e) => {
  e.target.style.boxShadow = "0 0 0 3px #006bff40";
});

// Remove the box shadow when the user doesn't focus anymore
element.addEventListener("blur", (e) => {
  e.target.style.boxShadow = "";
});

      

0


source







All Articles