Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the onclick calling object?

I need to have a handler on the calling object of onclick event.

<a href="123.com" onclick="click123(event);">link</a>  <script>   function click123(event) {     //i need <a> so i can manipulate it with Jquery   } </script> 

I want to do this without the use of $().click or $().live of jQuery but with the method described above.

like image 637
Konstantinos Avatar asked Oct 12 '09 09:10

Konstantinos


People also ask

How do I get Onclick in CSS?

We can use the tabindex attribute in the img tag and the :focus pseudo-class to simulate onclick events in CSS. For example, insert an image with the img tag with id as pic and tabindex value as 0 . In CSS, select the pic id with the :focus pseudo-class. Then, change the height and width of the image to 75px .

How do you get the ID of a clicked element by JavaScript?

To get the id attribute of a DOM element on click, create an event listener using AddEventListener() and retrieve the id of the clicked object using Element. target() .

How do I get Onclick value in react?

To pass an event and parameter onClick in React:Pass an inline function to the onClick prop of the element. The function should take the event object and call handleClick . Pass the event and parameter to handleClick .


2 Answers

pass in this in the inline click handler

<a href="123.com" onclick="click123(this);">link</a> 

or use event.target in the function (according to the W3C DOM Level 2 Event model)

function click123(event) {     var a = event.target; } 

But of course, IE is different, so the vanilla JavaScript way of handling this is

function doSomething(e) {     var targ;     if (!e) var e = window.event;     if (e.target) targ = e.target;     else if (e.srcElement) targ = e.srcElement;     if (targ.nodeType == 3) // defeat Safari bug         targ = targ.parentNode; } 

or less verbose

function doSomething(e) {      e = e || window.event;     var targ = e.target || e.srcElement || e;     if (targ.nodeType == 3) targ = targ.parentNode; // defeat Safari bug } 

where e is the event object that is passed to the function in browsers other than IE.

If you're using jQuery though, I would strongly encourage unobtrusive JavaScript and use jQuery to bind event handlers to elements.

like image 150
Russ Cam Avatar answered Oct 13 '22 05:10

Russ Cam


The easiest way is to pass this to the click123 function or you can also do something like this(cross-browser):

function click123(e){   e = e || window.event;   var src = e.target || e.srcElement;   //src element is the eventsource } 
like image 22
jerjer Avatar answered Oct 13 '22 06:10

jerjer