Yo!
I have the following function implemented on my site, which allows the user to press up/down to fluidly scroll through different sections of the page:
// CONTROL TOP NAVBAR WITH UP/DOWN ON KEYBOARD
$(document).keydown(function(e) {
var p = $("li.active");
if (e.keyCode === 38) {
e.preventDefault();
p.prev().find("a").click();
} else if (e.keyCode === 40) {
e.preventDefault();
p.next().find('a').click();
}
});
This works fine. However, I also have a contact form on the page. When the user is typing in the contact form, I’d like them to be able to move up/down with their keyboard in the textbox to navigate properly. However, it currently still controls the navbar.
My contact form has the id of #contactform. Code is here:
<form name="contactform" id="contactform" method="post" action="/contact/" _lpchecked="1">
<ul class="form-block">
<!-- HONEYPOT -->
<li class="on-no-robots" style="height:0px; text-indent:-9999px; font-size:0px; overflow:hidden;">
<label>Humans Don't Submit This!! If you can see this, you don't have CSS, and you scare me. This is just here to filter out automated comments!</label>
<input name="robotest" id="robotest" type="text" />
</li>
<!-- HONEYPOT -->
<li class="third">
<label for="name">Name</label>
<input type="text" name="name" id="name" value="" class="required" />
</li>
<li class="third">
<label for="email">Email Address</label>
<input type="email" name="email" id="email" value="" class="required email" />
</li>
<li class="third">
<label for="phone">Phone Number</label>
<input type="text" name="phone" id="phone" value="" />
</li>
</ul>
<h3>How can we help you?</h3>
<ul class="form-block">
<li class="full">
<textarea name="comments" id="comments" class="required"></textarea>
</li>
<li>
<input id="submitButton" type="submit" value="Talk to us" />
</li>
</ul>
</form>
Is it possible to make a conditional statement that says “if #contactform#name, #contactform#email, #contactform#comments is in focus, disable this function”?
I’m fairly bad at jquery, but here was my attempt:
$(document).keydown(function(e) {
if ($("#contactform input", "#contactform textarea").is(":focus")){
return;
}
else{
var p = $("li.active");
if (e.keyCode === 38) {
e.preventDefault();
p.prev().find("a").click();
} else if (e.keyCode === 40) {
e.preventDefault();
p.next().find('a').click();
}
}
});
Currently, the up/down arrow function works fine, although the conditional statment is wrong. What have I missed here?
Here’s a JavaScript routine (in use on this site) to detect whether a user is in a text field:
It could be improved by using jQuery syntax, but even as-is it should be enough to get your conditional working: