Don't execute a keydown function if some divs are clicked - javascript

My script execute some actions (like stop one audio player) in case the user press the space bar:
$('html').keydown(function(e){
if(e.keyCode == 32){
// Stop the audio player
}
}
But the problem comes when a user tries to write a message in the textarea because the previous function executes (and it's very annoying)... How can I do to not execute the function, in case the user is writing a message on a textarea or other elements?

You need to skip when user is focussing some control, this example will prevent the player to stop if user i typing in a text area.
$(function () {
$(document).keypress(function (e, f) {
var tagName = e.target.tagName.toLowerCase();
if (tagName != 'textarea') {
if (e.keyCode == 32) {
console.log('Stop Playing');
}
}
});
});
Hopw this helps.

Try this,
$('#textAreaId').keypress(function(e){
e.preventDefault();
});

Use stopPropagation method on event object when space bar pressed on textarea.
$(document).ready(function(){
$("#testTextArea").keydown(function(e){
if(e.keyCode == 32){
e.stopPropagation();
}
});
$("#container").keydown(function(e){
if(e.keyCode == 32){
alert('Player Stoped/Started')
}
});
})
fiddle : http://jsfiddle.net/b0u3z8pg/16/

Try This :)
$('html').keydown(function(e) {
if(e.keyCode == 32){
// stop the music player
}
});
$('input, textarea').keydown(function(e) {
e.stopPropagation();
});

Something like this:
The code inside the if statement only triggers if you are not focused inside a text area or input.
jsfiddle demo
HTML:
<textarea></textarea>
<input type="text">
jQuery:
var exclude = $("textarea, input");
$('html').on("keydown", function( e ) {
if ( e.keyCode == 32 && !exclude.is(':focus') ) {
console.log( 'Space pressed outside input or text area' );
}
});

You should check the sender of the event, if the sender is other controls then the audio player then ignore the call, otherwise stop the player.
$('html').keydown(function(e){
var senderID = $(event.target).attr('id');
if(senderID == 'myAudioPlayerID' && e.keyCode == 32){
// Stop the audio player
}
}

Related

Call function with mouse click

I have a text area. Each time the enter key is entered the cursor travels to the next line of the text area and a function is called. This function posts/updates the entry in a database. I want it so that if I edit a line and then click on the mouse to resume typing at another line the function is again called on the mouse click
$("#textarea").keydown(function (e) {
if (e.keyCode == 13) {
document.addEventListener('keydown', newLine(this, "\n"));
console.log("code added");
e.preventDefault();
stream();
Is it possible to change my line to something like this and the method gets called on pressing the enter key or pressing the mouse(anywhere in the text area)?
if (e.keyCode == 13 || mouse.click) {
I know the above isn't correct but want to illustrate what I'm after
You could take use of jQuery's .on method like so:
$("#textarea").on('click keydown', (e) => {
if(e.keyCode && e.keyCode == 13 || e.type == "click" ){
// Do stuff
}
});
It takes a first parameter as string with different events, which mean you can listen to multiple events at once. The second is a callback function, where you can track the event that is triggered. Nb: Events are different between click and keydown. You can have a closer look by putting console.log(e); in your callback
You'll need to attach another event listener. The keydown event will not trigger when a mouse is clicked. You will need to add a $(...).click(function ...) as well. For example...
function myFunction (e) {
document.addEventListener('keydown', newLine(this, "\n"));
console.log("code added");
stream();
}
$("#textarea").keydown(function() {
if (e.keyCode == 13) {
myFunction()
e.preventDefault();
}
});
$('#textarea').click(myFunction)
Instead of putting a condition you can create 2 events and a common function to handle it.
Foe Example:
$("#textarea").keydown(function (e) {
if (e.keyCode == 13) {
logic1()
$("#textarea").click(function() { logic1();});
function logic1(){
document.addEventListener('keydown', newLine(this, "\n"));
console.log("code added");
e.preventDefault();
stream();
}
I don't know about jQuery but with vanilla JS you can do something like this:
const textarea = document.querySelector('textarea');
const foo = event => {
const output = document.querySelector('output');
output.textContent = event.type;
}
textarea.addEventListener('click', foo, false);
textarea.addEventListener('keypress', foo, false);
<textarea></textarea>
<output></output>

Give keycode 2 different functions

I am using code to make the spacebar do something for an HTML 5 game. It works great, but the page that displays the game also has a Search Box, and visitors will not be able to use the spacebar properly in the Search Box on that page.
Below is the the code I am using for the spacebar on the game's page.
The Search Box is input type search, so I was wondering if a function could be make for :search, to revert the spacebar to work correctly inside the Search Box.
var hit = document.getElementById("hit");
document.onkeydown = function(e)
{
if (e.keyCode == 32)
{
e.preventDefault();
hit.click();
}
};
thanks
There are many ways you could do this, here's one:
var hit = document.getElementById("hit");
document.onkeydown = function(e) {
if (e.keyCode == 32) {
if (e.currentTarget.type === 'input') { //Or whatever check you want here
// Do things for your searchBox
return; //Prevent rest of the function from running
}
e.preventDefault();
hit.click();
}
};
Inside the above function you must check if the cursor is in your search box, and if it is then skip the rest of the function
Have rewritten your code as below, hope it helps
var hit = document.getElementById("hit");
document.onkeydown = function(e)
{
if (document.activeElement.nodeName != 'TEXTAREA' && document.activeElement.nodeName != 'INPUT') {
if (e.keyCode == 32)
{
e.preventDefault();
hit.click();
}
}
};
Cheers mate!
You can stop the 'keydown' events from the search bar from propagating upwards by calling event.stopPropagation():
document.addEventListener('keydown', function(e) {
console.log('hit!');
e.preventDefault();
});
let search = document.getElementById("search");
search.addEventListener('keydown', function(e) {
console.log("search!");
e.stopPropagation();
});
<form id="search"><input name="query" type="text"><input type="submit" value="search"></form>

Ignore keyup for a few seconds for ux

I have a multistep form using jquery validator plugin that also goes to the next page when you press enter.
function showPage(pg){
$('formError').empty();
$('table:visible').hide();
$('#page-' + pg).show();
$('input[type="text"]:visible').focus();
}
$(document).keydown(function(e) {
if(e.which == 13) {
if($('#msform :input:visible').valid()){
page++;
showPage(page);
}}});
The issue is that if you use the enter button, it triggers a validation error on the next page because the button is still being pressed and it tries to go to the next page.
How can I ignore the enter key for a small period so that releasing the enter key works to go to the next page without attempting to go to the page after the next page?
You can wait for the corresponding keyup event before taking in account a new keydown event for the enter key.
pressed = {};
$(document).keydown(function(e){
if(pressed[e.which] == null && e.which == '13'){
if($('#msform :input:visible').valid()) {
page++;
showPage(page);
}
}
pressed[e.which] = true;
});
$(document).keyup(function(e) {
pressed[e.which] = null;
});
You can use setTimeout() function like this
$(document).keydown(function(e) {
setTimeout(myFunction(),500);
});
function myFunction(){
if(e.which == 13) {
if($('#msform :input:visible').valid()){
page++;
showPage(page);
}}
}
::::::::::::::::::Update::::::::::::::::::
$(document).keydown(function(e) {
if(e.which == 13) {
setTimeout(myFunction(),500);
}
});
function myFunction(){
if($('#msform :input:visible').valid()){
page++;
showPage(page);
}
}

Hiding a div on Mouse click out OR escape keyword press

I have the following code that hides my div (live search results) when mouse is clicked outside the div but I can't incorporate an OR function that does the same thing (hides div) when the escape key is pressed. Any help is much, much appreciated. Also, original code on mouse click out is from a different thread I got here on Stackoverflow. The or function is giving me a hard time.
var mouse_is_inside = false;
$(document).ready(function()
{
$('.form_content').hover(function(){
mouse_is_inside=true;
}, function(){
mouse_is_inside=false;
});
$("body").mouseup(function(){
if $('#display').hide();
});
});
This hides #display on pressing escape:
$(document).keyup(function(event) {
if(event.which === 27) {
$('#display').hide();
}
});
Example: http://jsfiddle.net/nsufH/
You could also try to use window instead of document:
$(window).keyup(function(event) {
if(event.which === 27) {
$('#display').hide();
}
});
Or try to use live:
$(document).live('keyup', function(event){
if(event.which === 27) {
$('#display').hide();
}
});
Basically you need to monitor for the KeyCode and act based off it:
$(document).keyup(function(e) {
if (e.keyCode == 27) { $('#display').hide() } // esc
});
$(document).ready(function() {
$(document).on('mouseup keyup', function(e){
var e = e || event,
code = (e.keyCode ? e.keyCode : e.which),
target = e.srcElement || e.target;
if (target.className != 'form_content' || code==27) {
$('#display').hide();
}
});
});
Here is the jsfiddle hiding a div on mouseout and ESC key press :
http://jsfiddle.net/jrm2k6/q2kNX/
Of course there is probably some stuff to do in the way to adapt it as your own source code..

js deactivate spacebar when typing in textfield

I am creating a music player which uses the spacebar to pause and play audio, now is it possible to know if someone is currently typing in a textfield, because right now, if this user types in a textfield and audio is playing, when the user presses space the audio pauses, I would like basically that when the user is not in a textfield that a user can just play and pause audio, but when the user is typing that this function is disabled so the audio keeps playing. The code below, is the code I'm am current using for detecting when space is pressed;
//IF Space bar is Pressed
$(window).keypress(function(e) {
if(e.keyCode == 32) {
if(document.getElementById('audio').paused){
if(document.getElementById('video').style.display=="block"){
}
else{
document.getElementById('audio').play();
document.getElementById('pause').style.display="block";
document.getElementById('play').style.display="none";
}
}
else{
if(document.getElementById('video').style.display=="block"){
}
else{
document.getElementById('audio').pause();
document.getElementById('pause').style.display="none";
document.getElementById('play').style.display="block";
}
}
}
});
//END IF Space bar is pressed
Check the event sources tagName attribute:
function(e) {
e = e || event;
var el = e.srcElement || e.target,
cando = !(/textarea|input/i.test(el.tagName));
if(cando && e.keyCode == 32) {
/etc.
}
}
You could also try
if(e.keyCode == 32 && document.activeElement != document.getElementById('someTextBox'))
New code
//IF Space bar is Pressed
$(window).keypress(function(e) {
if(e.keyCode == 32) {
var inputs = document.getElementsByTagName('input');
for(var item in inputs)
{
if(inputs[item] == document.activeElement)
return;
}
if(document.getElementById('audio').paused){
if(document.getElementById('video').style.display=="block"){
}
else{
document.getElementById('audio').play();
document.getElementById('pause').style.display="block";
document.getElementById('play').style.display="none";
}
}
else{
if(document.getElementById('video').style.display=="block"){
}
else{
document.getElementById('audio').pause();
document.getElementById('pause').style.display="none";
document.getElementById('play').style.display="block";
}
}
}
});
//END IF Space bar is pressed
Check if a textarea has focus
if(e.keyCode == 32 && !text_area_has_focus) { ...
Logic for that could be something like this, if you're willing to use jQuery:
if(e.keyCode == 32 && !$('input[type=text]:focus').length) { ...

Categories