1
\$\begingroup\$

I have made a form where the submit button will show if the text box is focused and the button will hide if the text box is blurred.

These codes work fine. But I wonder if the jQuery code could be more simplified. Or is there any toggle function available?

var search = $("#search");
var button = $("#submit-button");
search.focus(function(){
 button.slideDown("slow");
});
search.blur(function(){
 button.slideUp("slow");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form action="" method="get">
 <div>
 <input type="text" name="search" title="search" class="search" id="search" placeholder="Enter text here"/>
 </div>
 <button type="submit" class="submit-button" id="submit-button" name="submit" style="display: none">Click to Search</button>
</form>

Note: I can do it with click function. But I want to do it with focus and blur

200_success
145k22 gold badges190 silver badges478 bronze badges
asked Sep 17, 2016 at 20:32
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

Chaining is the power way in jQuery:

var button = $("#submit-button");
$("#search").focus(function(){
 button.slideDown("slow");
}).blur(function(){
 button.slideUp("slow");
});
answered Sep 18, 2016 at 3:34
\$\endgroup\$
1
  • \$\begingroup\$ @EthanBierlein This is absolutely a good answer. The suggestion is to improve the code by using chaining. \$\endgroup\$ Commented Sep 18, 2016 at 6:20

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.