How to set input:focus style programatically using JavaScript

Sinisa picture Sinisa · Jan 3, 2015 · Viewed 15.4k times · Source

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!

Answer

Karthik picture Karthik · Jan 3, 2015

Other alternative would be to build a stylesheet for the page.

Something like this:

 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 clean separation of css styles from the scripts and so the better maintenance.