addEventListener "click" - starts on page load - javascript

I can't understand, why addEventListener("click") starts after page loading, not waiting for "click". What is worse - it does not work on click again. Below you can find script:
const seven = document.getElementById("seven");
seven.addEventListener("click", typeNumber(7));
function typeNumber(a){
calculations.innerText = calculations.innerText + a;
}
No matter what function I add to event listener (console log, alert etc) it always starts when the page starts. Are you able to help?
I tried to choose different types of function invocations

Call typeNumber inside an anonymous function, rather than calling it immediately and passing the return value to addEventListener (when it expects a function as the second argument).
const seven = document.getElementById("seven");
seven.addEventListener("click", () => typeNumber(7));
function typeNumber(a){
document.getElementById("calculations").innerText = calculations.innerText + a;
}
<button id="seven">7</button>
<p id="calculations"></p>

you are invoking the typeNumber function immediately when you add it as a callback to the event listener, rather than passing a reference to the function. This means that the function is executed immediately, rather than waiting for the event to occur.
you need to pass a reference to the function instead of invoking it:
const seven = document.getElementById("seven");
seven.addEventListener("click", function() {
typeNumber(7);
});
function typeNumber(a){
calculations.innerText = calculations.innerText + a;
}
the typeNumber function will only be executed when the click event occurs on the seven element.

Related

variable, passed together with event, does not change

When I call editWorkout function for the first time, the variable 'workout' gets passed in the editWorkout2 function, but then, during the second time, when the same thing happens, but in this case 'workout' has new value, this value for some reason won't change in editWorkout2 function. How can I fix that?
function editWorkout(e, workout) {
e.stopImmediatePropagation();
saveBtn.addEventListener("click", function (e) {
console.log(workout);
editWorkout2(e, workout);
}.bind(this)
);
}
on each call of your editWorkout function, you're adding a new event listener to your "saveBtn" element with the same event type.
I recommend you read the usage notes of addEventListener.
So, the problem was as follows: because during the second call and all of the consecutive calls of the function editWorkout the event listener was going on top of the previous one, for some reason variable workout was not changing in that eventListener as a parameter. So I removed event listener in the editWorkout2 function, and everything started working fine

Click event returns undefined, but when I run a load event on the window the function works

I am trying to simply put a word from my array into the DOM. When the button is clicked it returns undefined and if I console.log the randIndex I get NaN.
Ok, so I have tried to figure this out but I think I am missing something. When I click on the mealBtn it should run a function to show a meal item above the button. However, it returns undefined and puts undefined in the DOM. The thing that most confuses me is if I run an initialize function on window.load it does exactly what its suppose to.
//load an item from menu on window load
window.addEventListener('load', init);
const mealBtn = document.getElementById('mealBtn');
const currentMeal = document.getElementById('current-meal');
const message = document.getElementById('message');
const menu = [
'Macaroni',
'Burgers',
'Chili',
'Breakfast',
'Chicken',
'Take Out?'
];
function init(){
showMeal(menu);
}
mealBtn.addEventListener('click', showMeal);
//show a meal from menu array
function showMeal(menu){
const randIndex = Math.floor(Math.random() * menu.length);
currentMeal.innerHTML = menu[randIndex];
message.innerHTML = 'How about this?';
message.style.color = '#003b6f'
};
I expect that when I click the button it should give a menu suggestion in the DOM right above the button. It works on the init function when the window is loaded just not when the button is clicked.
mealBtn.addEventListener('click', showMeal);
the argument being passed to showMeal when this is triggered is the event, not menu
you want either
mealBtn.addEventListener('click', () => showMeal(menu));
// or
mealBtn.addEventListener('click', showMeal.bind(null, menu));
The second is an example of partial application... it's succinct but not exactly immediately readable.
Event listener callback in javascript accepts single parameter: object based on Event (see here).
MouseEvent (click) has a detail property, whoch can be used as obj.addEventListener("click", (e) => doSomethingWith(e.detail))
In your case, the Event parameter is no use to you and you want to pass custom parameters to the handler. Tyler's answer shows you the way to adapt the handler. However, you could also simply
mealBtn.addEventListener('click', init);

focusout only fires on document load and never again?

I've got a fiddle for you: http://jsfiddle.net/pneebntd/3/
$(document).ready(function(){
$('#Address').focusout(ValidateAddress($(this).val(), "address"));
$('#City').focusout(ValidateAddress($(this).val(), "city"));
$('#State').focusout(ValidateAddress($(this).val(), "state"));
$('#Zipcode').focusout(ValidateAddress($(this).val(), "zip/postal code"));
$("#StateList").change(ValidateAddress($(this).val(), "state"));
});
function ValidateAddress(location, label) {
console.info("made it there : " + location + " " + label);
}
The short of it is that I'm (trying) to attach the event handler for a function I want to run when a control loses its focus (or when a dropdown changes value).
The way it's written, it fires on page load but never again after that. I've done this before but maybe it's just because it's Monday but... what am I doing wrong here?
This code
$('#Address').focusout(ValidateAddress($(this).val(), "address"));
calls ValidateAddress and passes its return value into focusout, exactly the way foo(bar()) calls bar and passes its return value into foo.
If you want to give a function to focusout, you have to do that instead. For instance:
$('#Address').focusout(function() {
ValidateAddress($(this).val(), "address");
});
That code creates a new anonymous function and passes that function reference into focusout. When the event occurs, it will call your ValidateAddress function.

JavaScript notifications onclick event

as soon as Notification instantiates onclick function fires but I want prevent this event before actual click occures on notification
var message = new Notification("RandomString");
message.onclick(alert("Random Message"))
Try this:
var message = new Notification("RandomString");
message.onclick = function(){alert("Random Message")};
I'm going to break this down a little bit to make it more clear what your code is doing.
message.onclick() will invoke the onclick property of message, which is probably currently null and therefore can't be called as a function.
Inside of the () you have alert("Random Message"), which is going to be called right then. This means that the value of that function call will be passed in to the onclick function call as a parameter. alert() doesn't return anything, so the alert fires, then you're left with this:
message.onclick('undefined')
What you wanted to do was make onclick a function and have it call the alert.
message.onclick = function() {
alert("Random Message")
};
Now you can fire that function by clicking the element it is attached to, or you can still fire it directly with message.onclick().
The best practice now is to use addEventListener rather than onclick. addEventListener will allow you to register multiple events of the same type.
message.addEventListener('click', function() {
alert("Random Message");
});
Another thing that newer programmers often don't realize is that you don't have to make the function while attaching it as the event listener. Here's an example using both methods:
function foo() {
alert("Random Message");
}
message.onclick = foo;
message.addEventListener('click', foo);

How to unsubscribe from amplify within subscribe function?

amplify.subscribe("WorkTypesReceived", function () {
var workTypesList = amplify.store("ExpenseWorkTypesFor" + JobNo_);
amplify.unsubscribe("WorkTypesReceived");
});
getDropdownExpenseWorkTypes(JobNo_);
My getDropdownExpenseWorkTypes calls a function that publishes "WorkTypesReceived" when it is complete. But since I call this entire function more than once on a single page, it exponentially explodes (multiple subscriptions to the same topic). I'd like to remove the subscription once it's been published once (and so goes into the subscribe function once).
The line amplify.unsubscribe("WorkTypesReceived") doesn't seem to work, and the documentation says I need a second parameter being the callback function. But I'm inside the callback function so unsure how to proceed.
If you add a name to your callback you can use that to unsubscribe from it...
amplify.subscribe( "WorkTypesReceived", function storeWork() {
var workTypesList = amplify.store( "ExpenseWorkTypesFor" + JobNo_ );
amplify.unsubscribe( "WorkTypesReceived", storeWork );
});

Categories

Resources