I am trying to understand how is this code works
$("#imageGallery a").click(function(event){
event.preventDefault();
});
Why is the function handler (in this case "event") are executed? Isn't the handler supposed to be some var which isn't executed? feel free to share any keyword / article about this
Thankss..
The .click() method as you are using it takes an argument which is a callback function.
$("#imageGallery a").click(myCallback);
function myCallback(e) {
// the argument e which you can name anything you want is a
// jQuery event object
}
That callback function will be passed a single argument which is a jQuery event object. I've written the code above to use a separately defined function for the callback for illustration purposes. But, the function can also be defined inline as an inline anonymous function like this:
$("#imageGallery a").click(function(e) {
// the argument e is a jQuery event object
});
The jQuery event object has both properties and methods. .preventDefault() is one of the methods on that object. You can see a list of other properties on the object here in the jQuery doc.
event is not an event handler, it is an event object with properties and methods, including preventDefault() method that is being called in your example.
Your event handler is an anonymous function function(event){ event.preventDefault(); }
In this case, event (The first argument passed to your function) contains an object of the event that happened (In this case a click event). That event object creates functions such as preventDefault(), which tell the browser to ignore any future action from this event, such as opening the link that was clicked.
Try adding a line right before it:
$("#imageGallery a").click(function(event){
console.log(event);
event.preventDefault();
});
And take a look at your console (Press F12), and look as the console tab, and see what it outputs. You can see all the fields, and everything else that the event object contains.
To clarify things a bit more, event is not a handler, your entire function is:
function(event){
event.preventDefault();
}
jQuery will then pass the browser event object to this function when the event is fired, and your code will then execute.
Related
I was looking for method to specifically test if a certain handler(function) was bound to specific object on a specific event.
The problem I am trying to solve is I want to bind a handler to an objects unload event but I wanted a way to test if it was already bound so I did not bind it twice.
Here is a solution that worked for me. I used this stackoverflow answer (https://stackoverflow.com/a/2518441/2512022) to create the following function to test if a object has a specific handler bound to a specific event.
This function take a Object, Event Name, and handler function name as input parameters and will return true/false if the function is bound the event on the object passed in.
function testHandler(obj, sEvent, sHandlerName)
{
var retVal = false;
// Get all events bound to object
var windowEvents = jQ._data(obj, "events");
// Get all handlers for a specific event
var handlers = windowEvents[sEvent];
jQ(handlers).each(function() {
// Using passed name to see if there is a match
if(this.handler.name === sHandlerName)
{
retVal = true;
return;
}
});
return retVal;
}
Then call the function as follows.
// Test if there is a beforeclose() handler bound to the window objects
// "beforeunload" event
testHandler(window, "beforeunload", "beforeclose");
You could even test if there is on anonymous handler attached to an event. In the call below "this" references a button, and we are testing if there is an anonymous hanlder attached to the buttons click event
testHandler(this, "click", "anonymous");
I am trying to create a button listener function inside bindPop in leaflet. But it does not read parameter of onclick function. In the below code alertConfirmed()function works fine for me but filterEventsBasedOnCluster(feature) does not read the parameter 'feature'. It says feature is not defined. feature is an object.
here is the code:
layer.bindPopup('<div id="alert">Found...!<input type="button" value="Please confirm" onclick="alertConfirmed()"> <input type="button" id="create" value="see patients" onclick="filterEventsBasedOnCluster(feature)"><table id="table"></table></div>')
`
Any help is much appreciated.
If you attach event handlers via the onclick HTML attribute, you can not control the parameters received by that handler. Let me quote the docs:
The single argument passed to the specified event handler function is a MouseEvent object. Within the handler, this will be the element upon which the event was triggered.
The way to pass a custom argument is to define a closure, by having a function that returns a function that receives only the event reference.
This is exactly the same solution as described in «Leaflet.contextmenu callbacks» and «Leaflet marker event fires at wrong time».
Read that. I mean it.
So in the end it should look something like:
function getHandlerForFeature(feat) { // A function...
return function(ev) { // ...that returns a function...
console.log(feat); // ...that has a closure over the value.
}
}
layer.bindPopup("<button id='mybutton'>Foo!</button>")
// The button doesn't exist in the DOM until the popup has been opened, so
layer.on('popupopen', function(){
L.DomEvent.on(
document.getElementById('mybutton'),
'click',
getHandlerForFeature(layer) // The result of this call is the event handler func.
);
});
Note that you can not use the onclick="code" syntax, as you need to create a string of runnable code, and that code will only be able to access variables in the global scope. Sure, you can JSON.stringify() your data, but you won't be able to have references to variables outside.
try this:
I am just correcting the wrong part only:
onclick="filterEventsBasedOnCluster('+feature+')"
You are not passing the variable properly.
I'm trying to enable some touch controls through a callback function but I'm having trouble accessing the event as well as $(this) in my callback function. Right now the code looks as follows:
$('.img-responsive').each(touchControls);
function touchControls(event) {
event.preventDefault();
var mc = new Hammer(this);
mc.on("doubletap", function() {
console.log($(this));
});
}
Where '.img-responsive' is a class of images on my page.
When it tries to call event.preventDefault, I get an error that event.preventDefault is not a function. I thought the event was automatically passed to the variable called? I know when I did a named callback function with .on, event.preventDefault() worked perfectly fine. I assume it's different when I do it with .each, how do I properly access it?
Now, if I remove the event.preventDefault() line, when it logs $(this), I get a function. I was expecting to get individual elements so I could set touch controls for them, but that clearly didn't work. I tried to bind 'this' by:
$('.img-responsive').each(touchControls).bind(this);
But when I logged $(this), it was still a function and not the element I was expecting.
I'm basically just confused as to how to access $(this) and event within the defined callback function.
.each is not an event handler so its callback function does not accept an event object. The method signature of the each callback function looks like this:
.each( function )
function
Type: Function( Integer index, Element element )
A function to execute for each matched element.
So you won't have an event object to reference but, more importantly, there will be no default event behavior to prevent.
Conversely, on does in fact setup event handlers. Its callback function does take an event as its parameter. You can handle your event management within your event handler code, inside the callback function for .on.
this will refer to your current element as you iterate. But inside your inner callback function there will be a different context (so a different this). Simply store a reference to the element in the outer scope:
function touchControls() {
var $this = $(this);
var mc = new Hammer(this);
mc.on("doubletap", function(e) {
e.preventDefault();
console.log($this);
});
}
You have the event being passed in the wrong function.. You need to pass it into the event listener. The first argument of an each loop is the current index of the iteration.
$('.img-responsive').each(touchControls);
function touchControls(eachIndex) {
var mc = new Hammer(this);
mc.on("doubletap", function(event) {
// move preventDefault here and pass the event
event.preventDefault();
console.log($(this));
});
}
function Hammer(el){
return $(el)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="img-responsive">img</div>
<div class="img-responsive">img</div>
Why this works in jQuery :
$('#selCars').change(function(){
alert( "I have changed!" );
})
but not this one :
$('#selCars').change(alert( "I have changed!" ) );
You pass a function reference to .change(). Your second example just has code there, not a function reference.
Your first example works because it passes a function reference which IS what is required.
A function reference is required because this is a callback that will be called at a later time. The .change() function which executes immediately needs to save the callback reference into it's own variable and then call it later when the change event actually occurs. To do that, it needs a function to call at that later time, not a raw piece of code.
And, the other answer is because, .change() was written to require a function reference. That's how the developers that spec'ed and wrote it designed it. If you want it to work, you have to follow their rules.
Because it's a callback, i.e. you're passing something that be called back later, so what you've to pass is a reference to a function, and that reference will be stored and called when the event will fire.
The change method doesn't store some code, it stores only a pointer to the function. Your function is called an event handler.
It's because .change() attaches an event handler to an element. The handler won't be called until the event has occurred.
Since in JavaScript, functions are just another datatype, you could also do this:
var handler = function(event) {
alert("I have changed!");
}
$('#selCars').change(handler);
Note that handler is a function, Whereas alert() would just return undefined.
After spending so much time in jQuery, I'm rusty on my old fashioned JS...
The question: When attaching an event to an object that you want to trigger a function, how do you pass the event to said function?
Example function:
myFunction(e){
...
}
Example event attachment:
document.getElementById('blargh').onkeypress = function(){myfunction([what do I put here to pass the event?])};
Make the handler accept a parameter, say event, and pass it to your function:
document.getElementById('blargh').onkeypress = function(event){myfunction(event)};
The event handler always gets the current event passed as parameter... in the W3C model.
For IE you have to get the parameter via window.event. Thus, in the function you can write something like:
function(event) { event = event || window.event; myfuntion(event);}
you can try using arguments. This variable gets automatically populated in the local scope. It is an array of all the arguments that was passed into the function. If you pass arguments on to your myfunction, everything that was passed into the even handler will be passed as an array to myfunction.
document.getElementById('blargh').onkeypress = function(){myfunction(arguments)};
function myfunction(args)
{
alert(args[0]);
}