Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Stop .blur() event when clicking "submit" button

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 the problem I'm facing is when you click the submit button this instigates the blur function, hiding the button and shrinking the form. I need to find a way to stop the .blur() method only when the user is clicking to focus on the submit button. Is there any good workaround for this?

Would appreciate any help I can get!

like image 485
Jake Avatar asked Dec 05 '12 18:12

Jake


4 Answers

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 
}
like image 170
William Neely Avatar answered Oct 24 '22 22:10

William Neely


Try this inside .blur handler:

if ($(':focus').is('#submitbtn')) { return false; }
like image 34
pxx Avatar answered Oct 24 '22 22:10

pxx


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

like image 33
palaѕн Avatar answered Oct 24 '22 21:10

palaѕн


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="[email protected]" 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.

like image 23
dmi3y Avatar answered Oct 24 '22 21:10

dmi3y