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

| improve this question | | | | |
\$\endgroup\$
1
\$\begingroup\$

Chaining is the power way in jQuery:

var button = $("#submit-button");
$("#search").focus(function(){
    button.slideDown("slow");
}).blur(function(){
   button.slideUp("slow");
});
| improve this answer | | | | |
\$\endgroup\$
  • \$\begingroup\$ @EthanBierlein This is absolutely a good answer. The suggestion is to improve the code by using chaining. \$\endgroup\$ – 200_success Sep 18 '16 at 6:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.