one function can be triggered by two events but dont let it trigger by second event after it already occured by one event for example a function creates a box and it can be done by 2 methods
press enter
focus out
so once the box is created dont let it create by the other event.(please tell multiple ways to do it).
<textarea onfocusout="createFolder()>
or
$("textarea").keypress(function (e) {
if (e.which == 13 && !e.shiftKey) {
// $('textarea').replaceWith('<p class="text-center bd-title">' + $("textarea").val() + '</p>')
createFolder();
}
});
you can maintain a flag
let isFolderCreated = false;
$("textarea").keypress(function (e) {
if (!isFolderCreated && (e.which == 13 && !e.shiftKey)) {
isFolderCreated = true;
createFolder();
}
});
all its doing here is checking if the folder is not created and creating the folder
Related
I'm trying to call a function in 2 ways: either way, when the function is called it should not allow the other one to call the method
Here renameFolder is called in 2 places: first on focus out and second when enter is being pressed.
The problem is that when enter is pressed it calls the function 2 times 1 for enter being pressed and second for focus out as well.
$('#rename').click(function() {
//delete previous popup-menu if exists
removeMenu();
var folder = e.target.id;
var folderId = $("#" + folder).attr("id");
var folderName = $('#' + folder).parent().parent().children('.bd-title').text().trim();
$('#' + folder).parent().parent().children('.bd-title').replaceWith('<textarea class="bd-folder-title-input" oninput="this.style.height = `1px`;this.style.height = (10+this.scrollHeight)+`px`;" onfocusout="renameFolder()" maxlength="50" cols="10">' + folderName + '</textarea>');
$('textarea').focus();
$('textarea').select();
$("textarea").keypress(function(e) {
if (e.which == 13 && !e.shiftKey) {
renameFolder();
}
});
});
There are many possible method, one easy way would just be to funnel everything through one path:
$("textarea").keypress(function (e) {
if (e.which == 13 && !e.shiftKey) {
$(e.currentTarget).trigger('focusout'); // or blur
}
});
I've been developing a simple system that is supposed to change between two different scenes when you press a button.
gameOne();
var game = 1;
function gameOne() {
game = 1;
console.log("Game 1");
$( "body" ).keyup(function( event ) {
if ( event.which == 49 && game == 1) { // Number 1 key
gameTwo();
}
});
}
function gameTwo() {
game = 2;
console.log("Game 2");
$( "body" ).keyup(function( event ) {
if ( event.which == 49 && game == 2) { // Number 1 key
gameOne();
}
});
}
Expected behaviour - I want it to say Game 1, after after pressing the 1 key and then Game 2 after pressing the 1 key again, and then repeat this as I press 1.
Actual behaviour - It does the expected behaviour a few times, and then it starts repeating 1 and 2 over and over again, to the point it lags the browser out.
JSFiddle: https://jsfiddle.net/a0npotm8/10/
I'm really sorry if this is a basic question or anything, I'm still fairly new to Javascript and JQuery and this is really confusing me currently.
All help is appreciated.
Thank you :)
The problem here is that you are rebinding the keyup event recuresively inside the keyup callback, so it ends up by breaking the browser.
What you need to do is to get the keyup binding code out of the two functions:
gameOne();
var game = 1;
$("body").keyup(function(event) {
if (event.which == 49 && game == 1) { // Number 1 key
gameTwo();
} else if (event.which == 49 && game == 2) { // Number 1 key
gameOne();
}
});
function gameOne() {
game = 1;
console.log("Game 1");
}
function gameTwo() {
game = 2;
console.log("Game 2");
}
what about something like:
let game = 1;
document.onkeyup = ev => {
if (ev.which === 49) {
console.log(`Game ${game}`);
game = game === 1 ? 2 : 1;
}
};
will it solve your issue?
You can use a delegate event handler to control actions like this, so you do not have to juggle event bindings around.
var $container = $('#container').focus();
$(document.body)
.on('keyup', '#container.game1', function(e){
if (e.which == 49) {
console.log('Game 1');
$container.removeClass('game1').addClass('game2');
}
})
.on('keyup', '#container.game2', function(e){
if (e.which == 49) {
console.log('Game 2');
$container.removeClass('game2').addClass('game1');
}
});
#container {
min-width: 100vw;
min-height: 100vh;
background-color: rgb(128, 128, 128);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container" class="game1" tabindex="0">
</div>
This logic creates two different delegate event handlers for the body. Both filter out events for the #container child element of the body, but also filter based on an additional class on the container; game1 and game2. Depending on which class the element has, only one of the event handlers will process.
Whenever you call keyup on an element, you attach another event handler. To catch events, you only need to call it once. The callback functions that handle the event will fire every time the event happens.
I'm trying to create a note system. Whatever you type into the form gets put into a div. When the user hits Enter, they submit the note. However I want to make it so when they hit Shift + Enter it creates a line break a the point where they're typing (like skype). Here's my code:
$('#inputpnote').keypress(function(event){
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode=='13' && event.shiftKey){
$("inputpnote").append("<br>");
}
else if(keycode == '13'){
var $pnote = document.getElementById("inputpnote").value;
if ($pnote.length > 0) {
$("#pnotes-list").append("<div class='pnote-list'><li>" + $pnote + "</li></div>");
$('#inputpnote').val('');
}
}
});
#inputpnote is the form where the user enters their note and #pnotes-list is the place where the notes are being appended to. Thank you in advance!
I think for this you'd have to set two global variables, 1 for shitftKeyPress and 1 for enterKeyPress and then you'd need a keydown and a keyup to set those values and then you check to see if they are both true, because your logic is saying, when a key is pressed, execute this code, if you press a key and then press another key, the only that will happen is the function will be called twice.
EDIT:
Example code of what it should look like:
var hasPressedShift = false;
var hasPressedEnter = false;
$('#inputpnote').keydown(function(event){
if(shiftkey) {
hasPressedShift = true;
}
if(enterKey) {
hasPressedEnter = true;
}
});
$('#inputpnote').keyup(function(event){
if(shiftkey) {
hasPressedShift = false;
}
if(enterKey) {
hasPressedEnter = false;
}
});
$('#inputpnote').keypress(function(event){
if(hasPressedShift && hasPressedEnter) {
// Do something
}
});
This was a quick mock up, but it's similar to how it should look
I have an input field that I have bound an event on keypressed, but when I press Enter (to execute the event for the input) two dialogs from jQuery UI pops open and ruin my variables. How can I stop the events bound to the enter key for dialogs?
$("#itemSample").on('keypress', function (e) {
if (e.keyCode == 13 && $("#itemSample").val().trim().length > 0) {
//do something
}
});
On the parameter 'e' (Event) you have the necessary functions:
$("#itemSample").on('keypress', function (e) {
if (e.keyCode == 13 && $("#itemSample").val().trim().length > 0) {
// You probably need just one of the following two lines:
e.preventDefault();
e.stopPropagation();
}
});
For more info: http://css-tricks.com/return-false-and-prevent-default/
I want to add a autocomplete function to a site and found this guide which uses some js code which works really nice for one textbox: http://www.sks.com.np/article/9/ajax-autocomplete-using-php-mysql.html
However when trying to add multiple autocompletes only the last tetbox will work since it is the last one set.
Here is the function that sets the variables for the js script
function setAutoComplete(field_id, results_id, get_url)
{
// initialize vars
acSearchId = "#" + field_id;
acResultsId = "#" + results_id;
acURL = get_url;
// create the results div
$("#auto").append('<div id="' + results_id + '"></div>');
// register mostly used vars
acSearchField = $(acSearchId);
acResultsDiv = $(acResultsId);
// reposition div
repositionResultsDiv();
// on blur listener
acSearchField.blur(function(){ setTimeout("clearAutoComplete()", 200) });
// on key up listener
acSearchField.keyup(function (e) {
// get keyCode (window.event is for IE)
var keyCode = e.keyCode || window.event.keyCode;
var lastVal = acSearchField.val();
// check an treat up and down arrows
if(updownArrow(keyCode)){
return;
}
// check for an ENTER or ESC
if(keyCode == 13 || keyCode == 27){
clearAutoComplete();
return;
}
// if is text, call with delay
setTimeout(function () {autoComplete(lastVal)}, acDelay);
});
}
For one textbox I can call the function like this
$(function(){
setAutoComplete("field", "fieldSuggest", "/functions/autocomplete.php?part=");
});
However when using multiple textboxes I am unsure how I should go about doing this, here is something I did try but it did not work
$('#f1').focus(function (e) {
setAutoComplete("f1", "fSuggest1", "/functions/autocomplete.php?q1=");
}
$('#f2').focus(function (e) {
setAutoComplete("f2", "fSuggest2", "/functions/autocomplete.php?q2=");
}
Thanks for your help.
You should be using classes to make your function work in more than one element on the same page. Just drop the fixed ID's and do a forEach to target every single element with that class.