Stop onfocus event from firing in javascript - javascript

The onFocus event keeps firing on page load and doesn't seem to work when the element goes into focus. I only want the alert to fire off when the the input comes into focus not on page load
//Input
var input = document.getElementById('phonenumber');
//onfocus execute function
input.onFocus = alert('test')

You're calling the function alert and assigning its return value (undefined) to the focus handler. Try this instead:
input.onfocus = function() { alert('test'); };
Or, perhaps more understandably:
function inputFocused() {
alert('test');
}
input.onfocus = inputFocused;
Note that there are no parentheses after inputFocused in the assignment. We want to set onfocus to the function itself, not to the result of calling the function.

Related

preventDefault works only once?

this trigger works correctly ONE time. If it fires again, it just refreshes my page, so I’m guessing that the preventDefault isn’t working. Am I missing something?
function watchForm() {
$(‘form’).submit(event => { //listening for event on the form pop-up menu
event.preventDefault(); //suppresses browser from going to a linked page.
$(’#js-error-message’).empty();
let searchState = $(’#js-stateMenuForm :selected’).val();
getParks(searchState); //calls getParks function.
});
}
Rewrite your function to this below and see if it works:
function watchForm(){
// for every form on the page
$('form').on('submit', function(e){
// empty the error element
$('#js-error-message').empty();
var searchState = $('#js-stateMenuForm :selected').val();
// call the function that uses the value you are looking forward to.
getParks(searchState);
// where e is the event
e.preventDefault();
return false; // force return of the form's submission
});
}
Also, you can check this post: Jquery .on() submit event

Firing a function with onkeydown event

I made a cookie clicker using javascript and html, and at the moment I have it made so that upon clicking an image, it fires a function which increases your score. I want to make it so that instead of only being able to click the image, you can just click any button on the keyboard to fire the same function. I've only seen code to do this in an input field. I'm not sure if "document.addEventListener("keydown", function())" is what I'm looking for.
Try:
document.onkeydown = function() {
console.log('my code');
};
Edit (or):
document.onkeydown = myFn;
To listen for keypress you can add keydown event on document
document.addEventListener("keydown", callBack, false);
function callBack(e) {
var keyCode = e.keyCode;
console.log(keyCode);
}
Just assign a event handler to your event.
If you want to assign for the whole document, use this:
document.addEventListener("keydown", keyDownTextField, false);
document.getElementById("yourinput").addEventListener("keydown", keyDownTextField, false);
function keyDownTextField(e) {
console.log(e.keyCode);
}
<input id="yourinput" type="text" />
document.addEventListener('keydown', () => {
console.log('a');
});
should work.
However, some browsers don't give document focus, which is required for keydown events.
The classic approach to this (which works more universally) is to create an off-screen <input> element, and give it a blur event to regain focus when it loses it. This will force focus to always stay on that input, then it can receive key events.
const input = document.createElement('input');
input.style.position = 'absolute';
input.style.left = '-100000px';
input.addEventListener('blur', () => input.focus());
input.addEventListener('keydown', () => console.log('key down'));
document.body.appendChild(input);
input.focus();
This code:
- creates a new input element
- positions it absolutely way off the left of the screen (so it's not visible)
- adds a blur event which automatically gets focus back
- adds the keydown event itself

Double event handler and one function. How to prevent executing code twice?

I have one callback function bound to two events (change and focusout). However, I need the focusout to happen only when the element we're interacting with is not a checkbox.
This is the example code:
$(document).on('focusout change', '.selector', function() {
if ($(this).is(':checkbox')) {
// Do stuff and prevent the focusout to trigger. HOW???
}
doStuff(); // Action that applies to both cases, but needs to be limited at one execution only
});
The code above will execute twice:
When the checkbox gets checked/unchecked
When you click outside of the checkbox (lose focus (blur))
I tried using .off, but it ends up killing the focousout handler altogether, which I will need later for other elements which aren't checkboxes.
What would be the way to prevent the focusout handler to trigger for certain elements?
What you want to do is
$(document).on('focusout change', '.selector', function(event) {
event is an event object, which has properties, one of which is type. Checking the type you can now see if your function has been called because of a focusout or a change and run code as appropriate
The best way is to affect both events (or more) to the same function, like this :
A text input for example
<input id="myfield" type="text" />
Now the Javascript
var myfield = document.getElementById('myfield');
myfield.onfocus = myfield.onchange = function(e)
{
//your code
}
Yo can even add an other element
button.onclick = myfield.onkeyup = function(e)
{
//when the client press the enter key
if(e.key && e.key == "Enter")
{
//catch the target
}
//when the client click the button
else if(!e.key || e.target == button)
{
//catch the target
}
//otherwise you can do not care about the target and just execute your function
}
You must only know that you can add many elements and many events
element1.onfocus = element1.onblur = element2.onchange = element3.onchange = function(e){//your code}

Only inline handlers works

On my application only inline handlers works.
This is part of my Javascript function
function onDeviceReady() {
alert('ready');
document.querySelector('#idCpf').onkeypress = alert('keypress');
document.getElementById("idCpf").onclick=alert("click");
}
And this is my part of my html code
<input type="tel" autocomplete="on" id="idCpf" onblur="alert('onblur')" placeholder="Seu CPF" required>
On onDeviceReady function only the first alert works, and onkeypress and onclick show me an alert when the function onDeviceReady without pressing, click or blur the input. But my code only works when I use inline handlers, like on input type.... onblur="alert('onblur')".
What is my problem?
document.querySelector('#idCpf').onkeypress = alert('keypress');
calls the alert('keypress'); and assigns the return value of alert('keypress'); as event handler.
alert('keypress'); is executed immediately and not when the event is triggered.
To assign event handler you must do,
document.querySelector('#idCpf').onkeypress = function () { alert('keypress') };
document.getElementById("idCpf").onclick= function () { alert("click") };

Jquery on keyup not firing

I have an input and an event handler attached to it and for some reason, the keyup event is not working. I have looked at this a while and can't figure out what the problem is. The alert window is not even showing as I type something into the input box.
$(function () {
var tagField = $("#<%= EditTagNum.ClientID %>"); //asp.net code to get the generated client ID
$(tagField).on('keyup paste cut', function () {
alert('inside event handler');
var _this = this;
//because the paste event fires before the text has actually been
//pasted, I have to set a timeout. Once the timeout occurs, the text
//has then been entered into the input box.
setTimeout(function () {
var text = $(_this).val();
$(_this).val(text.replace(/\D/g, ''));
}, 0);
});
});
Update:
I changed my code to use the generated client id directly as so:
$("#ctl00_ContentPlaceHolder1_EditTagNum").on(.....
This did not solve the problem. BUT I did discover that once I run my event handler function in the console, then it works. It is if the event handler is never attached. Yet, when I am debugging in chrome I see that it reaches the function to attach the handler. It just never gets inside of it.
You can check if this works:
$(tagField).keyup(function() {
instead of
$(tagField).on('keyup paste cut', function () {
var tagField = $("#<%= EditTagNum.ClientID %>");
Here tagField is itself a jquery object. And you are wrapping this object again in jquery. Try following :
tagField.on('keyup paste cut', function () {
alert('inside event handler');
var _this = this;
//because the paste event fires before the text has actually been
//pasted, I have to set a timeout. Once the timeout occurs, the text
//has then been entered into the input box.
setTimeout(function () {
var text = $(_this).val();
$(_this).val(text.replace(/\D/g, ''));
}, 0);
});
});
It should work.
Instead of this : 'keyup paste cut', try this .. "keyup paste cut" ..
Worked for me magically in past ... ! :)
You can use
$(document).on('keyup', tagField, function() {...});
instead, if you are not sure that tagField is attached to the DOM at the time that you call $(tagField).on('keyup', tagfield, ...);

Categories

Resources