Javascript – How to change the style of an element/container when the focus is “inside” it


Suppose to have a code like this:

<div class="notSelected">
          <input type="text" name="name" id="name" />
      <div class="description">
          Tell us what's your name to make us able to fake to be your friend 
          when sending you an email.

Now suppose I've something like this (it's just an example) for each element of a form.
I'd like to change the style from notSelected to Selected when:

  • User focus on the input element
  • User move the mouse over a notSelected div

When he change focus the Selected div should became notSelected again.

I'd like to do something like this to increment the size of the text of the selected div. Anyway it could be cool make other changes too so I'd prefer to change the class attribute.

What is the best way to do something like this in JavaScript? Is there any JavaScript framework that can boost me doing this thing? So it will be easy to add effects like fading etc…

I downloaded MooTools but with a fast read of the docs I did not see how to do this without having a specific ID for any of the forms div, but is the first time I use it. I've no problem using any other framework, but if you suggest one, please write also what should I look for specifically.

Best Solution

I would recommend a look at jQuery for your task. It is quite easy to learn and produces nice effects quickly. But your described effect alone, pure JavaScript would also be enough.

Make your DIVs always have a class called "selectable". You can toggle other CSS classes later on. Create a CSS class named "selected" and give it the desired look.

<div class="selectable">  (=off) vs. <div class="selectable selected"> (=on)

Then add something like this to the scripts section of your document:


  // handle mouseover and mouseout of the parent div
    function() { 
    function() { 

  // handle focus and blur of the contained input elememt,
  // unless it has already been selected by mouse move
  $("div.selectable input").focus(
    function() {
    function() {

This is untested so there might be a glitch in it, but it will give you the general idea where to start.

P.S: Changing text size on mouse move may not be the best of all ideas. It leads to rearranging the page layout which is annoying for the user.