jQuery Stop .blur() event when clicking “submit” button

后端 未结 4 1473
暗喜
暗喜 2021-02-07 17:36

I am building a small landing page with a simple demo e-mail signup form. I want to have the form field open up when focused, and then shrink back down on blur.

However

相关标签:
4条回答
  • 2021-02-07 17:42

    I know this question is old but the simplest way to do it would be to check event.relatedTarget. The first part of the if statement is to prevent throwing an error if relatedTarget is null (the IF will short circuit because null is equivalent to false and the browser knows that it doesn't have to check the second condition if the first condition is false in an && statement).

    So:

    if(event.relatedTarget && event.relatedTarget.type!="submit"){
         //do your animation 
    }
    
    0 讨论(0)
  • 2021-02-07 17:43

    It isn't the prettiest solution, but it does work. Try this:

    $("#submitbtn").mousedown(function() {
        mousedownHappened = true;
    });
    
    $("#email").blur(function() {
        if (mousedownHappened) // cancel the blur event
        {
            mousedownHappened = false;
        }
        else // blur event is okay
        {
            $("#email").animate({
                opacity: 0.75,
                width: '-=240px'
            }, 500, function() {
            });
    
            // hide submit button
            $("#submitbtn").fadeOut(400);
        }
    });​
    

    DEMO HERE

    0 讨论(0)
  • 2021-02-07 17:53

    why not rely on submit event instead of click? http://jsbin.com/ehujup/5/edit

    just couple changes into the html and js

    wrap inputs into the form and add required for email as it obviously suppose to be

    <form id="form">
     <div id="signup">
       <input type="email" name="email" id="email" placeholder="me@email.com" tabindex="1" required="required">
       <input type="submit" name="submit" id="submitbtn" value="Signup" class="submit-btn" tabindex="2">
     </div>
    </form>
    

    in js, remove handler which listen #submitbtn

    $("#submitbtn").on("click", function(e){
      e.stopImmediatePropagation();
      $("#signup").fadeOut(220);
    });
    

    and use instead submit form listerer

    $("#form").on("submit", function(e){
      $("#signup").fadeOut(220);
      return false;
    });
    

    you may use $.ajax() to make it even better.

    Doing this you gain point in terms of validation and the native browser's HTML5 validator will make check email format where it is supported.

    0 讨论(0)
  • 2021-02-07 18:06

    Try this inside .blur handler:

    if ($(':focus').is('#submitbtn')) { return false; }
    
    0 讨论(0)
提交回复
热议问题