javascriptdom-eventsrevealing-module-pattern

Get event target from within Javascript module


I'm using the revealing module pattern for the first time and gradually getting to grips with it.

In my html I have something like this:

<a href='#' onclick='myApp.doStuff'>Click here</a>

In Javascript I have:

var myApp = (function () {

    var doStuff = function() {
        //Get clicked element and modify it with jQuery?
    }

    return {
        doStuff: doStuff
    }

})();

How do I get the clicked element at the point indicated above?


Solution

  • You can use jQuery methods, like alex23 said.

    But you can also write in html:

    <a href='#' onclick='myApp.doStuff(this)'>Click here</a>
    

    and this for your javascript:

    var myApp = (function () {
    
        var doStuff = function(elem) {
            //use the element here
        }
    
        return {
            doStuff: doStuff
        }
    
    })();
    


    Update

    If you want to pass the event object, too, extend the call in onclick to:

    onclick='myApp.doStuff(this, event)'
    

    and the javascript to:

    ...
    var doStuff = function(elem, event){
    ...
    }