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.
Related
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
<script>
var ohnoesEl = document.getElementById("ohnoes");
var onOhNoesClick = function(e) {
e.preventDefault();
var audioEl = document.createElement("audio");
audioEl.src = "https://www.kasandbox.org/programming-sounds/rpg/giant-no.mp3";
audioEl.autoplay = "true";
document.body.appendChild(audioEl);
};
ohnoesEl.addEventListener("click", onOhNoesClick);
</script>
In this code, I didn't understand one thing. I checked internet and StackOverflow but couldn't find anything.
I have a problem to understand event property.
Why do we put e as an argument before we use properties such as preventDefault?
How will I realize whether I should use it or not?
I have a problem to understand event property.
Well, it's not a property. All event handling functions are automatically passed a reference to the event object that represents the event currently being handled. This object can tell you quite a bit about the circumstances at the time of the event (i.e. which mouse button was clicked, what key was pressed, where on the screen the mouse was when the click happened, what object triggered the event, etc.).
Why do we put e as an argument before we use properties such as
preventDefault?
The syntax of e.preventDefault() is simply common Object-Oriented Programming syntax of: Object.method(). We are accessing the Event object that was passed into the function with the e identifier and then invoking the preventDefault method stored within that object.
It's how you get at some object-specific behavior. .preventDefault() is not a global function, you can't just call it on its own. It's only something that an event object can do, so you have to reference the object before calling the method.
As with all function arguments, you may call the argument any valid name you like, but since the object will be an event object, e, evt, and event are quite common.
How will I realize whether I should use it or not?
In your code: e.preventDefault(), indicates that the event that was triggered should not perform its built-in action, effectively cancelling the event.
You would use this technique in situations where the user has initiated some event, but your code determines that the process should not continue. The best example is with a form's submit event. If the user hasn't filled out all the required fields and then hits the submit button, we don't want the form to be submitted, so we check to see if the required fields were filled in and, if not, we cancel the submit event.
Here's an example:
// Get a reference to the link:
var link = document.getElementById("nasaLink");
// Set up a click event callback function that will automatically
// be passed a reference to the click event when it occurs. In this
// example, the event will be received as "evt".
link.addEventListener("click", function(evt){
console.clear(); // Cancel previous log entries
// Get the type of event that was received and the object that triggered it
console.log("You triggered a " + evt.type + " on :", evt.target)
// Cancelling an event is generally based on some condition
// Here, we'll make it simple and say that if you click on the
// link when the second is an even second, the navigation will be cancelled
if(new Date().getSeconds() % 2 === 0){
// Normally, clicking a valid hyperlink will navigate you away from the current page
// But, we'll cancel that native behavior by cancelling the event:
evt.preventDefault();
console.log(evt.type + " cancelled! No navigation will occur.");
}
console.log("The mouse was postioned at: " + evt.screenX + " x " + evt.screenY);
console.log("The SHIFT key was pressed at the time? " + evt.shiftKey);
console.log("\tTry clicking again, but with SHIFT held down this time.");
});
Click for NASA
The event property is an object that is passed to every event handler.
This event object then has many properties and methods you can call to manipulate the event process and action in the handler.
For instance, in the event object you have this method called preventDefault() . What does preventDefault() do? Each event is triggered by a particular html dom element in the page. Sometimes this html elements have behaviour attached to them. For instance, and <a> element has the potential of changing the browser url for a particular window. If the element that triggered the event is then an <a>, with preventDefault() you just cut the default behaviour for that <a> anchor and that will avoid an url load/change.
I recommend you find a reference for this event object and pay a read to it. So you'll become more familiar to what it is available within it.
I need to execute code from 3 different places on my website when an event gets triggered. I've added 3x listeners but for some reason only the first listener gets called.
Here's the code I'm testing at the moment: JSFiddle
window.addEventListener('tompina_event', function (e) {
document.write("triggered 1");
});
window.addEventListener('tompina_event', function (e) {
document.write("triggered 2");
});
window.addEventListener('tompina_event', function (e) {
document.write("triggered 3");
});
var evt = new CustomEvent('tompina_event');
window.dispatchEvent(evt);
Result:
triggered 1
This is the result I was hoping for:
triggered 1triggered 2triggered 3
It works, but the document.write destroys the original page and thus the execution of other code.
Please rewrite so the result is set in an other way like alert("triggered 1") or console.log("triggered 1").
The problem is with document.write(). Each call is overriding the strings from the previous call, and it appears that only one is firing. Change to console.log(), or document.body.innerHTML += "" and you will see them all firing.
The write() method is mostly used for testing: If it is used after an HTML document is fully loaded, it will delete all existing HTML.
A few weeks ago I was painfully able to dynamically add buttons to an HTML DOM object that has its own .on('click'.. handler, and use e.stopPropgation to stop these new child elements from firing the event.
The weird thing I did was call a function without any parenthesis. I have no idea why I did this or why it works, or why it does not work when I do attach parenthesis. I want to know if I am doing something by fluke and not design (and now I will add comments to it).
It goes as such:
//Container is the parent element
// var buttons stores the buttons with class 'buttons'
$('.container').on('click', function(){
$(buttons).appendTo($(this)).fadeIn(500).find('.buttons').click(tableButton);
});
function tableButton(e){
e.stopPropagation();
//do stuff
}
I can't figure out why I wrote the call to tableButton with no arguements or why it works perfectly. I tried to change the syntax to
.find('.buttons').on('click', function(e){
tableButton(e);
});
but then it no longer works.
Any help appreciated!
It works because you're passing a function to the click handler rather than calling the function yourself (the ()) An example of that:
var testFunction = function(msg) {
alert(msg);
}
var functionCaller = function(functionToCall) {
functionToCall('hello!');
}
functionCaller(testFunction);
functionCaller passes the message argument to testFunction(), but we only pass testFunction to functionCaller (without arguments)
For the part which doesn't work, isn't the function name tableButton() instead of tableButtons()?
See http://jsfiddle.net/g2PAn/
You don't actually call it, you just declare it and the arguments it accepts. The click callback is called with an argument indeed, but not by you.
The problem probably comes from the fact that jQuery calls your function with the element clicked bound as this, you could call table button like this:
.find('.buttons').on('click', function(e){
tableButton.call(this, e);
});
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);