0

I've got the following code:

function myfunc(e){
    console.log(e.target);
}

which returns the event of the clicked target. But I want to trigger that same function without clicking on a target.

Is this possible? is it possible to do something like this?

myfunc(document.getElementById('btn').target);
gespinha
  • 7,968
  • 16
  • 57
  • 91
  • check this, it may help http://stackoverflow.com/questions/5658849/whats-the-equivalent-of-jquerys-trigger-method-without-jquery – Deep Jul 06 '16 at 14:15
  • Possible dublicate: http://stackoverflow.com/questions/2705583/how-to-simulate-a-click-with-javascript – Alexander Davydov Jul 06 '16 at 14:19
  • Answer is probably in the duplicate, and you can check `if( typeof(e) !== 'undefined' ) { ... CODE FOR EVENT OBJECT ... }` – Alon Eitan Jul 06 '16 at 14:20

2 Answers2

0

I think you should modify your function like this, to use with and without event trigger (if you only need the element object)

function myfunc(e){
    var ele = e ? e.target : document.getElementById('btn');
    console.log(ele);
}
Mohammed Safeer
  • 20,751
  • 8
  • 75
  • 78
0

Triggering a .click() with javascript manually will directly bind the click to that element so in your case an event will not be passed by doing this . Also , target is a property of the event object so calling it directly on getElementById will not work . Logically once you getElementById then you already have your target because id's are unique .

On the other hand jquery library allows you to trigger clicks and pass custom data like so :

Example :

$( "button" ).on( "click", {name: "John"}, sayName);

function sayName(event){

    alert(event.data.name )

}

Hope this helps .

KpTheConstructor
  • 3,153
  • 1
  • 14
  • 22