I have a form that if you click on the input field giving it focus the submit button displays.
However the issue I'm having is that when you try to click on the submit button it disappears as the focus has been removed from the input.
Here is my code:
<form method="post" id="subForm" class="clearfix">
<input id="fieldEmail" placeholder="email address" type="email"/>
<button type="submit"><i class="arrow"></i></button>
</form>
$('#fieldEmail').focus(function () {
$(this).next().addClass('visible');
}).blur(function () {
$(this).next().removeClass('visible');
});
What is the best way to keep the toggling of class 'visible' but allow me to click the submit button?
It has to do with the order of events.
You can use mousedown
to detect where the focus moves to because it triggers before the blur
:
(function () {
var submit_focus = false;
$('#fieldEmail').focus(function () {
$(this).next().addClass('visible');
}).blur(function () {
if (submit_focus) {
submit_focus = true;
} else {
$(this).next().removeClass('visible');
}
});
$('#submit').mousedown(function () {
submit_focus = true;
});
}());
I suggest to put a check inside the function which hides the button and see if the input field has some value (if yes, you wouldn´t want to hide the button, or?)
eg:
$('#fieldEmail').focus(function () {
$(this).next().addClass('visible');
}).blur(function () {
if($(this).val() === ""){
$(this).next().removeClass('visible');
}
});
We can have a check that on blur of textfield, the new focused element is button or not .
$('#fieldEmail').focus(function () { $(this).next().addClass('visible'); }).blur(function () { if(!event.relatedTarget||event.relatedTarget.type!='submit') $(this).next().removeClass('visible'); });
form { color:#333; position: relative; } input { padding:0 5px 5px; text-align: center; border:none; text-transform: uppercase; font-size:12px; width:170px; margin-left:15px; float:left; letter-spacing: 2px; } button { display: none; background: #ff0000; border:none; } .arrow { background:#ff0000; width:15px; height:15px; display: block; } .visible { display:block; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form method="post" id="subForm" class="clearfix"> <input id="fieldEmail" placeholder="email address" type="email"/> <button type="submit"><i class="arrow"></i></button> </form>
I would suggest to capture each click
event on document
and if the target
of that event
is not submit button or email input then hide the submit button
as below and remove the blur event from input
$(document).on('click',function(e){
if(e.target.type!="submit" && e.target.type !="email")
{
$('#fieldEmail').next().removeClass('visible')
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.