Someone33
Someone33

Reputation: 568

Css input:focus only on first click

Does anybody know a way to input:focus an element only on first click?

<style>
input[type='text'].error:focus{border-color:#f00} 
</style>

So, if the user "focus out" it returns to the original border color.

Thanks in advance for any hint.

Edit

I wasn't sure at all. Thanks @blender.

I think the easist way to do it is using jquery or similar, right?

Upvotes: 1

Views: 2460

Answers (3)

Someone33
Someone33

Reputation: 568

For all who have the same or a similar question, here's is a possible jQuery solution:

 $('input').on('focusout',function(){
 $(this).removeClass('error');
 });

This will remove the error class on :focus out. When the user :focusin another time the input element, it will return to the default color.

Example default border-color with css:

 <style>
  input[type='text']:focus {border-color: black;}
 </style>

Upvotes: 0

Artyom Neustroev
Artyom Neustroev

Reputation: 8715

As @Blender said, it does not seem possible in pure CSS.
I would suggest to handle focusin and focusout events to add a class to an element and use data- attributes to get if element was already clicked or not.

Have a look at this jsFiddle.

Upvotes: 0

Keenan Payne
Keenan Payne

Reputation: 816

I am confused as to what you mean by "only on first click". If you want to style an input on click, you can just use this CSS:

input[type="text"].error:focus { border-color: #f00; }

And this HTML:

<input type="text" class="error" />

That will style the input border given it has the class of error (if you are adding/removing the class dynamically that is).

However, if you are styling for errors (like if the user hasn't filled out the form), you might want to try something like this:

 input[type="text"]:invalid { border-color: #f00; }

 input[type="text"]:valid{ border-color: #; } //If form is filled in

Then in your HTML:

<input type="text" required />

Does that help answer your question a little bit?

Upvotes: 1

Related Questions