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

\$\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");
});
\$\endgroup\$
1
  • \$\begingroup\$ @EthanBierlein This is absolutely a good answer. The suggestion is to improve the code by using chaining. \$\endgroup\$ Sep 18, 2016 at 6:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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