user482594
user482594

Reputation: 17486

How do I pass in event in javascript?

The javascript code is like below.

var ADDRESS = {
    checkit : function(element){
    if(event.target.className == "delete"){
        doSomethingweird();
    } else {
        doSomething();
    }
}

and the calling function looks something like below.

<div onclick="ADDRESS.checkit(this);">
    <div class="delete">del</div>
</div>

Apparently, only input 'this' gets passed in, but I want to also pass in the event such that I can use it to find out the event.target.className. (Above code works in Chrome, but not in IE so far, because IE does not seem to recognize event) How should I change ADDRESS.addressbook_clicked(this); so that event also gets passed in?

Upvotes: 0

Views: 172

Answers (3)

mu is too short
mu is too short

Reputation: 434835

Bind your handler in the usual jQuery manner:

<div id="x">
    <div class="delete">del</div>
</div>

And:

$('#x').click(ADDRESS.checkit);

Then, change your ADDRESS to this:

var ADDRESS = {
    checkit : function(event){
        // And if you need your old "element", look in "this" instead.
        if(event.target.className == "delete"){
            doSomethingweird();
        } else {
            doSomething();
        }
    }
};

That should solve your cross-browser problems and it is the standard jQuery approach.

Upvotes: 2

Jay
Jay

Reputation: 6294

If you can garantee the structure of your HTML then you could do something like this:

var ADDRESS = {
    checkit : function(element){
    if($(this).children(".delete").length > 0){
        doSomethingweird();
    } else {
        doSomething();
    }
}

Upvotes: 0

Ruan Mendes
Ruan Mendes

Reputation: 92314

Your HTML should be

<div onclick="ADDRESS.checkit(this, event||window.event);">
    <div class="delete">del</div>
</div>

Now the event element is also being passed to your event handler.

Warning This is old style event handling, most people nowadays use non-obtrusive event handling which decouples your JS and your HTML.

Upvotes: 4

Related Questions