Abhinav Pandey
Abhinav Pandey

Reputation: 270

Button to change color on focus using tab key and back to original color on pressing enter

I reach my button using tab key and after that when it does a focus, I want it to change color so that it shows that you have reached the button and, when you press the enter key, it should change its color back to original.

<div style="position: absolute; margin: 0; left: 0; bottom: 0">
            <input id=" vehicles" class="button calculator large top-right-border transition" type="submit" name="submit"   />
        </div>

and CSS is

#vehicles:hover{
     background: red;
}
#vehicles:focus{
     background: red;
}
#vehicles{
     background: green;
}

On pressing enter I want my color to go back to green.

Upvotes: 1

Views: 5646

Answers (4)

Nish
Nish

Reputation: 738

hope it helps,

 <html><body>

<input type="submit" 
       id="vehicles" 
       style="background-color:red;" 
       onfocus ="change_color()"/>

    <script>
        function change_color()
        {
            document.getElementById("vehicles").style.backgroundColor="Blue";
        }
    </script>
    </body>

    </html>`

Upvotes: 0

Janty
Janty

Reputation: 1714

I think you should use :active instead of :focus. It will give you your required solution

<input id="vehicles" class="button calculator large top-right-border transition" type="submit" name="submit"   />


#vehicles:hover{
     background: red;
}
#vehicles:active{
     background: red;
}
#vehicles{
     background: green;
}

Find the JSFIDDLE

Its will work for you. Use jQuery for focus-defocus. for more please go through

http://api.jquery.com/focusout/

Upvotes: 0

cuth
cuth

Reputation: 534

Using :active won't revert it back to green for good. You will probably need to use JavaScript to unfocus the button.

<input id="vehicles" type="submit" onkeypress="if (event.which === 13) this.blur()" />

Upvotes: 3

AstroCB
AstroCB

Reputation: 12367

You have a space between the opening parenthesis and vehicles in your id assignment in the input element, so your CSS styling isn't applying to it. It should be

<input id="vehicles".../>

rather than

<input id=" vehicles".../>

Demo

Upvotes: 0

Related Questions