Durgesh
Durgesh

Reputation: 119

javascript event.target not working in mozilla

<script type ='javascript'>
    function fun(userID) {
        var btn = event.target; // error 'event' undefine in mozilla 
        alert(btn.id);
    }
</script>

<asp:linkButton id ="target" style =" cursor:pointer" onclick ="fun('1')" >click here </asp:LinkButton>

I am new in JavaScript, I have written above code and this code is working fine in Google chrome but not working in Mozilla Firefox. can anyone suggest how to find control firing event?

Upvotes: 4

Views: 9016

Answers (5)

Will
Will

Reputation: 1

Use arguments[0].target instead of event.target. Most browsers support the event global variable, but firefox does not. arguments[0] contains all the same properties and functions, but is supported by all browsers.

As a side note: indices in the arguments array can be changed by your own code. In my current project arguments[0] contains all of my controller functions for some reason, while the global event methods and properties are contained in arguments[1]. Not entirely sure why this is, but you might need to do some debugging on the arguments array to see what values it contains and adjust accordingly. More often than not however, arguments[0] should work.

Upvotes: 0

mplungjan
mplungjan

Reputation: 177786

If you pass the button using the keyword this then no need for event

...onclick="fun(this,1)"

function fun(but, userID) { 
  var butID=but.id

}

Upvotes: 0

Beetroot-Beetroot
Beetroot-Beetroot

Reputation: 18078

To access the event in the click handler, attach it in jQuery rather than in the HTML.

HTML:

<a id ="target" style ="cursor:pointer" data-value="1">click here</a>

Javascript:

$(function() {
    $("#target").on('click', function(event) {
        event.preventDefault();
        var btn = this;
        var value = $(this).data('value');
        alert(btn.id + ', ' + value);
    });
});

Many (including myself) consider this the "proper" way to attach event handlers. There are several advantages, of which access to the event object is just one.

Upvotes: 0

Akhil Sekharan
Akhil Sekharan

Reputation: 12683

Pass event to the function:

<asp:linkButton id ="target" style =" cursor:pointer" onclick ="fun(event, '1')" >click here </asp:LinkButton>

function fun(event, userID)
{
    event= event|| window.event;
    var btn = event.target; 
    alert(btn.id);
}

OR

Make sure your event is not undefined

function fun(userID)
{
    var e = event || window.event;
    var btn = e.target; 
    alert(btn.id);
}

Upvotes: 11

defau1t
defau1t

Reputation: 10619

event is undefined in firefox, because firefox doesn't have this property and instead you can provides an event to an event handler function as a parameter.

However your code is fine to work in Chrome and IE

Further I would also have script a type like <script type ='text/javascript'> and not just <script type ='javascript'>

Upvotes: 0

Related Questions