I have a code snippet
$(document).on("click", "div[data-role=button]", myfunc);
function myfunc(e){
alert(event.target);
alert(e.target);
alert(event.currentTarget);
alert(e.currentTarget);
}
Each of them give different outputs when i click on the
element.
e is of type object
event is oftype MouseEvent
The e.currentTarget seems to give the correct answer.
My question is if i decided to add another parameter to my handler, how will i get to access the "e", parameter which gives the right answer.
EDIT:
I want to do
function myfunc(e,str){
}
How can i access e inside my function and how do i pass the two arguments?
EDIT 2
I found another interesting thing,
this
this correctly gives the target, even though i expected it to give the document any idea why?
You access e the same way you are already doing, I guess what you mean is how to set the handler in the click event. How about like this:
$(document).on("click", "div[data-role=button]", function(e) { myfunc(e, "some string"); });
Of course that doesn't make "some string" very flexible (unless you are rebinding the event when it changes), so it could just as easily be fixed in the myfunc function.
If you want it to be based on something, perhaps an attribute of the element being clicked, then perhaps you want:
$(document).on("click", "div[data-role=button]", function(e) { myfunc(e, $(this).data("string")); });
which will get the value of a data-string attribute, for example:
<div data-role="button" data-string="my string 1"></div>
Inside myFucnc e is a local variable that refers to the event object. event probably refers to a closure or a global variable.
The difference between target vs currentTarget is the following:
Identifies the current target for the event, as the event traverses the DOM. It always refers to the element the event handler has been attached to as opposed to event.target which identifies the element on which the event occurred.
https://developer.mozilla.org/en-US/docs/Web/API/Event/currentTarget
Related
Is there a difference between working a property of an element through the event.target vs working it directly?
I don't understand if there's any difference.
const btn = document.querySelector('#btn');
btn.addEventListener('click', function(e) {
console.log(e.target.value);
//vs
console.log(btn.value);
}
Is there a better practice when doing this?
Yes, there is an important difference. The event.target property tells you what element was involved with the creation of the event. For a "click", it's the element that was under the cursor when the "click" happened.
Thus if your HTML looked like:
<button><span>Text</span><img src="something.jpg"></button>
a click on the button content would trigger the event from either the <span> or the <img>, and one of those elements would be the target.
There's another event property, event.currentTarget, that is always a reference to the element to which the event handler is attached. That's probably what you want. Alternatively, if you bind handlers with .addEventListener(), then the value of this when the handler is invoked will be a reference to the same thing as currentTarget.
In your case you're selecting an element by ID. Your reference is the same as the target so there is no difference. A lot of time we use delegation so you might not have reference to the clicked element. Hence we use target from the event object.
Worth also to check target vs currentTarget
I need some help with the callbacks. For some reason, they don't work really well.
I'm making a game with jQuery. I have a <div id='button'></div> for all the buttons that are going to be in the game. The game is going to have two buttons that make actions, and a question on top of it. The question is controlled by a <h3 id='text'></h3>. What I want to know, is that for some reason I can't set callback functions to the button's ID's. In example,
I'd have the yes or no, that have their own id's set through jQuery like this:
$('#button').html('<button id='yes'>Yes</button><button id='no'></button>');
But for some reason, I would be able to set this:
$('yes').click(function(){
//function I would want
});
Of course, that's not what my code has, that was just an example. Here's the real code:
$(document).ready(function(){
$('#main,#batman,#car,#cop,#hobo,#knife,#gangfight,#ganggun,#gangknife,#blood,#hr').hide(-100);
var hr=$('#hr');
var main=$('#main');
var batman=$('#batman');
var car=$('#car');
var hobo=$('#hobo');
var cop=$('#cop');
var knife=$('#knife');
var gangfight=$('#gangfight');
var ganggun=$('#ganggun');
var gangknife=$('#gangknife');
var blood=$('#blood');
var text=$('#text');
var button=$('#button');
$('#start').html('Are you ready to play?');
$('#button').html('<button id="yes">Yes</button><button id="no">No</button>');
$('#yes').click(function(){
$('#yes,#no').hide(function(){
$('#start').hide();
main.fadeIn(-100);
hr.fadeIn(-100,function(){
text.delay(1000).html("You were just wandering around in the streets of new york, when suddenly.. You see batman!! You've never really liked him, what do you do?")
button.html('<button id="fight">Fight</button><button id="leave">Leave</button>',function(){
batman.fadeIn(1000);
$('fight').click(function(){
});
$('leave').click(function(){
text.fadeOut(function(){
text.text('Good call. As you leave, you encounter a hobo. What do you do?');
});
});
});
});
});
});
$('#no').click(function(){
$('#yes,#no').hide();
$('#start').text('Oh, okay then. Come back later!');
});
});
I'm just wondering.. How can I set callback functions to the 'fight' and 'leave'.
If you're wondering why there's all these variables at the start, those are just the images and characters.
You can't set a click handler on an element that doesn't exist. What you should do is use .on to bind a element further up the tree. Something like:
$("#someparentelement").on("click", "#yes", function() {
// your code
});
Which version of jQuery are you using? You should probably use jQuery.on() in this situation since your click handler code probably gets executed before the button is actually available in the DOM.
$("#button").on("click", "#yes", function (event) {
// Your yes-button logic comes here.
});
For more details and possibilities, read about the .on(events [, selector ] [, data ], handler(eventObject)) method in the jQuery documentation:
If selector is omitted or is null, the event handler is referred to as direct or directly-bound. The handler is called every time an event occurs on the selected elements, whether it occurs directly on the element or bubbles from a descendant (inner) element.
When a selector is provided, the event handler is referred to as delegated. The handler is not called when the event occurs directly on the bound element, but only for descendants (inner elements) that match the selector. jQuery bubbles the event from the event target up to the element where the handler is attached (i.e., innermost to outermost element) and runs the handler for any elements along that path matching the selector.
In this case, you want to delegate the event since your element is not yet available in the DOM when you're binding the event.
Don't use the click(), use on('click') and attach it to the document.
Creating a handler this way, will ensure that any new elements will be able to trigger the event.
$('fight') selects fight tag, not the tag with fight id. Try to use $('#fight') instead.
I'm learning how to manipulate events in JavaScript and I'm wondering "why do you have to pass the event object as a parameter (argument) into a function when using event handling?"
Here's an example of what I am talking about:
<script type="text/javascript">
document.getElementById('button_1').onclick = (function (event) {
alert("The event is: " + "on" + event.type);
});
</script>
I wrote the code above and I pretty much understand what it does. I just don't understand the whole (event) passing. I thought of this as a way of assigning an anonymous function to the button_1.onclick event handler. Does the event handler try to pass in an event before it gets assigned or?... I'm having a difficult time understanding this. If someone could please clarify this for me I would be grateful.
[I tried searching it on Google but found very complex explanations and examples. Only a simple-to-intermediate explanation would help.] =)
The Ever-Present Event, Whether You Like it or Not
The event is always present, even when you don't provide a name:
$(".foo").on("click", function(){
alert( arguments[0].type );
});
That is the same as saying this:
$(".foo").on("click", function(event){
alert( event.type );
});
The event object is already being passed to your callback (whether your provide a name for it or not), you can choose to not use it if you like. For instance, if we looked to a jQuery onClick method:
$(".foo").on("click", function(){
/* Do stuff */
});
Making Use of It
You'll note that I have no event object referenced in my callback. I'm not required to. However, if I want to use it, for whatever purpose, I should give it a name:
$(".foo").on("click", function(myEvent){
myEvent.preventDefault();
myEvent.stopPropagation();
});
Now that I have granted myself access to the event details, I can prevent the default behavior that would result from the event, and I can also stop the event from bubbling up the DOM to other elements.
Practical Example
Suppose we wanted to listen for click events on an element:
$("#bigSquare").on("click", function(event){
/* Do something */
});
Click events happen on an element when you click the element itself, or any of its children. Now suppose this element had two children:
<div id="bigSquare">
<div id="redSquare"></div>
<div id="blueSquare"></div>
</div>
Clicking any of these, the big square, the red square, or the blue square will cause the "click" event on the big square - after it causes the click event on whichever element you clicked first (events bubble up the DOM).
We could determine which element was the target in any click event via the event itself:
$("#bigSquare").on("click", function(event){
alert( event.target.id );
});
Note here how we're accessing the ID of the target that raised the event. If you click on the red square, when that event bubbles up to the big square, we will see alerted "redSquare". The same goes for the blue square. If you click that, the event will bubble up to the big square and we will see alerted "blueSquare".
You can test this online via the following demo: http://jsbin.com/ejekim/edit#javascript,live
Try clicking the orange, red, or blue square to see what is alerted.
You are not passing the event parameter anywhere. You are just making a function that takes one parameter, called event.
When the browser calls the event handlers, it calls the function(s) assigned to it, and passes the event object to it as the 1st parameter.
P.S. You don't need the () around your function.
document.getElementById('button_1').onclick = function (event) {
alert("The event is: " + "on" + event.type);
};
You aren't passing an event into the function, you are naming the first parameter passed to your function event.
The browser is the one that is going to call your function and it passes an event object when it calls your function. You can choose not to name that parameter function(){} but the browser is still going to pass the event object in, you can use it or not use it as you see fit.
Simply put, the Event object passed to a handler contains details about the event. For example, a KeyboardEvent contain info about the key pressed, the corresponding character, and any modifier keys (alt, shift, control, meta) that were held down.
Does the event handler try to pass in an event before it gets assigned or?
The handler is your function, so it's the receiver of event, not the passer.
The event handler is bound when you assign it to the element's onclick property (or by calling addEventListener, the modern, preferred method), which is before the handler is invoked.
The Event object is passed when the handler is invoked, which is when the event fires.
So, when a user clicks on your #button_1, this causes a "click" event to fire on the button, which invokes the button's "click" handler, which is passed a MouseEvent.
For more information, read about event-driven programming.
To add to the others answers and comments, your code will not work with IE. For cross-browser capability, you need to test the existence of the first argument:
<body>
<button id="button_1">Click Me!</button>
<script type="text/javascript" >
document.getElementById('button_1').onclick = (
function(event) {
var e = event ? event : window.event;
alert("The event is: " + "on" + e.type);
});
</script>
</body>
taken from: https://github.com/keithamus/jwerty
Does anyone know how to unbind after setting up a .key binding?
As a test, I want this set globally when something is selected
jwerty.key('↑', function(e) {
e.preventDefault();
alert('up');
});
then unbound when that object is unselected. That stuff is already set up, inside that unselect statement though I want to call the jwerty unbind but can't figure out how.
but when I a) don't know how to unbind it explicitly or b) if I try to change it to a different anonymous function I still see the alert.
If you want a global key handler that can be removed, you have to bind it using jQuery http://jsfiddle.net/mendesjuan/LxQ4H/2/
function doit() {
alert('up');
}
// to bind use namespaces so it can be unbound without removing
$(document.body).bind('keydown.test', jwerty.event('↑', doit));
// a button that unbinds the key handler
$('#btn').click(function(){
$(document.body).unbind('keydown.test')
});
If you want the key handler to be scoped to an HTML element, you need to set the listener on the element, not globally. This will only fire if the element that it's bound to has focus. Just pass in a selector to bind a shortcut local to that element http://jsfiddle.net/mendesjuan/LxQ4H/
jwerty.key('⌃+⇧+P/⌘+⇧+P', function () { [...] }, this, '#myinput');
If your element doesn't take focus by default (a div), you need to make it focusable by doing the following. http://jsfiddle.net/mendesjuan/LxQ4H/1/
// or 0, 1,2 3 if you want it to be tabbable
document.getElementById('#mydiv').tabIndex = -1;
These code samples came from https://github.com/keithamus/jwerty (same link you already mentioned)
If you have jQuery available, as Juan Mendes mentioned, you can use jQuery's bind() method, with jwerty.event.
However there is another way to solve this. Using the current code you provided;
jwerty.key('↑', function(e) { e.preventDefault(); alert('up'); });
jwerty's internals will do the bind for you, but will add it under a special "keydown.jwerty" namespace. (See this line of the codebase). So, following the code you already have, you just need to do this:
$(document.body).unbind('keydown.jwerty');
The cool thing about using namespaces in jquery is that you can bind all jwerty events by also doing this:
$(document.body).unbind('.jwerty');
In the following jQuery JavaScript code, what value does the parameter "e" take on within the function? I'm having difficulty understanding this because this function cannot be passed an argument elsewhere in the code so how would having a parameter work? And how would I use parameters in such functions that are not named and not called anywhere else in the code?
$(document).ready( function() {
$('div').each(function() {
$(this).click(function(e){
//some code
});
});
});
click sets the event handler. The click handler gets called by the browser when the event occurs, and the e parameter contains information about that event.
For keypress events, it contains which keys were pressed and what modifiers were pressed at that time (shift, control, etc.).
For mouse events, it contains the position of the click and which button was used.
See http://www.quirksmode.org/js/events_properties.html for more information about the properties of the event structure.
e is an eventObject as you can see in the jQuery click documentation.
I do not know what you can do with it however, but it should contain information about the click event. Maybe it's the standard DOM event.
That anonymous function is called when the event is fired, and e is an eventObject:
click( fn )
// fn, a function to bind to the click event on each of the matched elements.
function callback(eventObject) {
this; // dom element
}