get elementId from event in jquery - javascript

function barvaInfo(event) {
$(document).ready(function(){
var nid = window.event.srcElement.id;
}
this works in IE but not in FF. Can i use jquery for this? i try with JQuery event api but then i do not know how to get ID from it.

If you're using jQuery, you'll need to assign a parameter to your event handlers, then pass the argument to your function on each event.
You may also want to call it from the context of the element that received the event.
// some mouseover event handler
$('div').mouseover( function( e ) {
barvaInfo.call( this, e )
});
function barvaInfo( event ) {
// element that originated the event
var nid = event.target.id;
// in this function, because we're using .call() to invoke it,
// "this" will reference the element that invoked the handler
}

The event object is normalized through jQuery for you and is passed into each event handler:
$('someelement').bind('click', function(event) {
var nid = this.id; // event.target.id
});
within the handler, this refers to the dom node of invocation. So this.id would address the id of the element. Alternative, the event object owns a property called target which also represent the element.
edit
As patrick dw pointed out, this will always be a reference to the node to which the event handler was bound to. event.target is exactly what it says, the element which is the actual target. See comments for an example link.

Related

Pragmatically test if specific event handler(function) is bound to an object's event using jQuery

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");

How to access $(this) and event in defined callback function

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>

Event reference is undefined on event listener callback passed as a method

Callback method is not being called when I attach my event to element. The method in question belongs to an object but it seems the way I am calling it the method isn't being called when the click event occurs.
var myObject = {
handledrop : function () {
//retrieved created html element
var elem = document.getElementById("required");
elem.addEventListener("click", this.deleteFavorite.bind(this), false);
},
//this method isn't being called when click event occurs
deleteFavorite: function (evt) {
console.log(evt);
}
}
What am I doing wrong? How do I pass the right context so that the correct method is called and passed the right context which is event
Couple of debug/trouble-shooting tips:
Post the html for the "required" element.
Check that the "required" element you think you're getting is valid:
var elem = document.getElementById("required");
console.log('elem:',elem);
You can also iterate its properties to ensure that function exists:
foreach(var property in elem){
console.log('property:',property);
}
For cross browser support - you might want to read this post:
addEventListener vs onclick

How do I get the current HTML element on which the event handler is being called

How do I get a reference to the HTML DOM element inside its event handler that I am wiring up?
var dashboard =
{
WireHandlers : function()
{
$(".approveButton")
.unbind("click")
.click(dashboard.approve)
},
approve : function()
{
// In here, I would like a reference
// to the HTML DOM element that was clicked
// Also, I would like its id
}
}
Simply add an argument to your approve function (typically named event) and call currentTarget on it:
approve : function(event) {
// In here, I would like a reference
// to the HTML DOM element that was clicked
event.currentTarget
// Also, I would like its id
event.currentTarget.id
}
Note that you can also use this within the approve method to reference the clicked element.
approve : function() {
this // or $(this) if you want to use jQuery
}
Note that in this case target and currentTarget are interchangeable. However, in more complex scenarios, there are important differences between the two.
$(this)
is the jQuery element (this is the DOM element)
this will not be bound to dashboard (as you're just providing the function as a callback, you'll have to use eg dashboard.WireHandlers)
From the jquery documentation here:
https://api.jquery.com/click/
you can access the acted upon element through the "this" variable:
approve : function()
{
var elem = this;
var id = elem.id;
}

Return an element's particular event handler

Given an element in the Dom, is it possible to return the name of the event handler for a particular event?
For instance,if i select an element
$("#container")
Is it possible to return the 'keypress' eventhandler bound to that element?
This post may help: http://james.padolsey.com/javascript/things-you-may-not-know-about-jquery/
You can access all event handlers bound to an element (or any object) through jQuery’s event storage:
// List bound events:
console.dir( jQuery('#elem').data('events') );
// Log ALL handlers for ALL events:
jQuery.each($('#elem').data('events'), function(i, event){
jQuery.each(event, function(i, handler){
console.log( handler.toString() );
});
});
// You can see the actual functions which will occur
// on certain events; great for debugging!
You could get it using : $('#container').attr('keypress')
Technically yes, if you're using a named function (although this is kind of an odd thing to be doing in the first place...).
// create a named function
function fooHandler() {}
// bind the named function
$("#container").keypress(fooHandler);
// retrieve the bound function from the data collection
$("#container").data('events').keypress[0].handler.name; // 'fooHandler'

Categories

Resources