1

JS/Jquery Disappear on focus next element / jquery on focus on element hide previous element after there has been an input

I have the code:

<script> $(document).ready(function(){ $("div").click(function(){ $("#hide").hide(); }); ); </script> 

The above hides the element 'div' onclick. What I am really looking for is when I have filled the first field, and click on the second one, then it should hide the first one. The div should slide out. For eg I have 5 fields as Name, Email, DOB, Address, Post Code. So when I have entered my Name, and click on Email, the Name DIV should disappear by sliding out. I am new to JQuery.

How can I do this?

Thanks

1
  • You could hide your fields on blur but from a UX point of view it's very bad. How do you get back to the field you've just filled to change it in case you made a mistake? Commented Feb 6, 2015 at 0:24

3 Answers 3

1

Here is a very simple answer that you can easily extend:

$('input#email').click(function(){ if ($('input#name').val().length > 0 ){ $('input#name').hide(); } });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input id='name' placeholder="name"></input><br> <input id='email' placeholder="email"></input><br>

Sign up to request clarification or add additional context in comments.

Comments

0

Although it's not a good idea to hide fields from the user, you could fadeOut each not empty field when focus is set on another field. This way you have at least possibility to get back to field when you click outside the form (it will be visible until any other field is not clicked).

$(".txt").focus(function(){ var inputs = $(".txt").not($(this)).not(".txt:hidden"); if($(".txt").not(".txt:hidden").length == 2){ $(".txt").focusout(function(){ if($(this).val()){ $(this).fadeOut(); } }); } inputs.each(function(){ if($(this).val()){ $(this).fadeOut(); } }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <div><input type="text" class="txt" placeholder="Name"/></div> <div><input type="text" class="txt" placeholder="Email"/></div> <div><input type="text" class="txt" placeholder="DOB"/></div> <div><input type="text" class="txt" placeholder="Address"/></div> <div><input type="text" class="txt" placeholder="Post Code"/></div>

JSFiddle

Comments

0

You can bind an event using jQuery's on() or bind() methods. The event you care about is blur which triggers when an element loses focus.

Something like:

$('#name').on('blur', function() { $(this).hide(); }); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.