Search code examples
javascriptcssstylesheetonfocus

How to set input:focus style programatically using JavaScript


I'm building a UI library in JS that can, without relying on any CSS stylesheets, create UI components, stylised from code. So far, it's been quite easy, with exception of styling different control states (such as input:focus one).

Code that I use to create 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;
}

Styling it for default state is easy. However I am unsure how to set style for states such as focused, disabled or not-editable.

If I'd be having CSS stylesheets included in the project that would be easily sorted out. However I can't have any CSS files included, it must be pure JS.

Does anyone know how to set style for an input field state (eg. input:focus) straight from JS code?

No JQuery please :-) Just straight-up JS.

Thanks in advance!


Solution

  • You would need to add an event listener to the element in order to change the style of it. Here is a very basic example.

    var input = document.getElementById("something");
    input.addEventListener("focus", function () {
      this.style.backgroundColor = "red";  
    });
    <input type="text" id="something" />