Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 627
Siniša Avatar asked Jan 03 '15 03:01

Siniša


People also ask

When focus () method is used in JavaScript?

JavaScript focus method is used to give focus to a html element. It sets the element as the active element in the current document. It can be applied to one html element at a single time in a current document. The element can either be a button or a text field or a window etc.

Why is focus () Used?

Javascript focus() methods helps to highlight a HTML form element. It sets the element as an active element in the current document. In current documentation, focus can be applied to only one single element. The focus can be applied either to a text, a button, etc.


2 Answers

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" />
like image 156
Cjmarkham Avatar answered Sep 28 '22 01:09

Cjmarkham


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.

like image 35
Karthik Avatar answered Sep 28 '22 03:09

Karthik