Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get elementId from event in jquery

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.

like image 750
senzacionale Avatar asked Dec 15 '25 09:12

senzacionale


2 Answers

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
}
like image 194
user113716 Avatar answered Dec 16 '25 21:12

user113716


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.

like image 44
jAndy Avatar answered Dec 16 '25 21:12

jAndy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!