javascript event.target not working in mozilla - javascript

<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?

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);
}

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'>

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.

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
}

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.

Related

OnClick Event Triggered on button click and Division, that button is inside that DIV [duplicate]

Consider the following:
<div onclick="alert('you clicked the header')" class="header">
<span onclick="alert('you clicked inside the header');">something inside the header</span>
</div>
How can I make it so that when the user clicks the span, it does not fire the div's click event?
Use event.stopPropagation().
<span onclick="event.stopPropagation(); alert('you clicked inside the header');">something inside the header</span>
For IE: window.event.cancelBubble = true
<span onclick="window.event.cancelBubble = true; alert('you clicked inside the header');">something inside the header</span>
There are two ways to get the event object from inside a function:
The first argument, in a W3C-compliant browser (Chrome, Firefox, Safari, IE9+)
The window.event object in Internet Explorer (<=8)
If you need to support legacy browsers that don't follow the W3C recommendations, generally inside a function you would use something like the following:
function(e) {
var event = e || window.event;
[...];
}
which would check first one, and then the other and store whichever was found inside the event variable. However in an inline event handler there isn't an e object to use. In that case you have to take advantage of the arguments collection which is always available and refers to the complete set of arguments passed to a function:
onclick="var event = arguments[0] || window.event; [...]"
However, generally speaking you should be avoiding inline event handlers if you need to to anything complicated like stopping propagation. Writing your event handlers separately and the attaching them to elements is a much better idea in the medium and long term, both for readability and maintainability.
Keep in mind that window.event is not supported in FireFox, and therefore it must be something along the lines of:
e.cancelBubble = true
Or, you can use the W3C standard for FireFox:
e.stopPropagation();
If you want to get fancy, you can do this:
function myEventHandler(e)
{
if (!e)
e = window.event;
//IE9 & Other Browsers
if (e.stopPropagation) {
e.stopPropagation();
}
//IE8 and Lower
else {
e.cancelBubble = true;
}
}
Use this function, it will test for the existence of the correct method.
function disabledEventPropagation(event)
{
if (event.stopPropagation){
event.stopPropagation();
}
else if(window.event){
window.event.cancelBubble=true;
}
}
I had the same issue - js error box in IE - this works fine in all browsers as far as I can see (event.cancelBubble=true does the job in IE)
onClick="if(event.stopPropagation){event.stopPropagation();}event.cancelBubble=true;"
This worked for me
<script>
function cancelBubble(e) {
var evt = e ? e:window.event;
if (evt.stopPropagation) evt.stopPropagation();
if (evt.cancelBubble!=null) evt.cancelBubble = true;
}
</script>
<div onclick="alert('Click!')">
<div onclick="cancelBubble(event)">Something inside the other div</div>
</div>
For ASP.NET web pages (not MVC), you can use Sys.UI.DomEvent object as wrapper of native event.
<div onclick="event.stopPropagation();" ...
or, pass event as a parameter to inner function:
<div onclick="someFunction(event);" ...
and in someFunction:
function someFunction(event){
event.stopPropagation(); // here Sys.UI.DomEvent.stopPropagation() method is used
// other onclick logic
}
I cannot comment because of Karma so I write this as whole answer: According to the answer of Gareth (var e = arguments[0] || window.event; [...]) I used this oneliner inline on the onclick for a fast hack:
<div onclick="(arguments[0] || window.event).stopPropagation();">..</div>
I know it's late but I wanted to let you know that this works in one line. The braces return an event which has the stopPropagation-function attached in both cases, so I tried to encapsulate them in braces like in an if and....it works. :)
According to this page, in IE you need:
event.cancelBubble = true
Use separate handler, say:
function myOnClickHandler(th){
//say let t=$(th)
}
and in html do this:
<...onclick="myOnClickHandler(this); event.stopPropagation();"...>
Or even :
function myOnClickHandler(e){
e.stopPropagation();
}
for:
<...onclick="myOnClickHandler(event)"...>
Why not just check which element was clicked? If you click on something, window.event.target is assigned to the element which was clicked, and the clicked element can also be passed as an argument.
If the target and element aren't equal, it was an event that propagated up.
function myfunc(el){
if (window.event.target === el){
// perform action
}
}
<div onclick="myfunc(this)" />
This also works - In the link HTML use onclick with return like this :
Delete
And then the comfirmClick() function should be like:
function confirmClick() {
if(confirm("Do you really want to delete this task?")) {
return true;
} else {
return false;
}
};
<div onclick="alert('you clicked the header')" class="header">
<span onclick="alert('you clicked inside the header'); event.stopPropagation()">
something inside the header
</span>
</div>
Event.preventDefault()
is the current norm, and the one thing that worked for me. See: https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault
<button value=login onclick="login(event)">login</button>
//and in a script tag
function login(ev){
ev.preventDefault()
return false;
}
this worked in the latest Chrome, Opera, and IE. (the Mozilla page indicates Firefox would do it too, so I don't even test it!)
The best solution would be handle with the event through a javascript function, but in order to use a simple and quick solution using the html element directly, and once that the "event" and "window.event" are deprecated and not universally supported (https://developer.mozilla.org/en-US/docs/Web/API/Window/event), I suggest the following "hard code":
<div onclick="alert('blablabla'); (arguments[0] ? arguments[0].stopPropagation() : false);">...</div>

Nested click event handler causing issue of running handler multiple times on a single click [duplicate]

Consider the following:
<div onclick="alert('you clicked the header')" class="header">
<span onclick="alert('you clicked inside the header');">something inside the header</span>
</div>
How can I make it so that when the user clicks the span, it does not fire the div's click event?
Use event.stopPropagation().
<span onclick="event.stopPropagation(); alert('you clicked inside the header');">something inside the header</span>
For IE: window.event.cancelBubble = true
<span onclick="window.event.cancelBubble = true; alert('you clicked inside the header');">something inside the header</span>
There are two ways to get the event object from inside a function:
The first argument, in a W3C-compliant browser (Chrome, Firefox, Safari, IE9+)
The window.event object in Internet Explorer (<=8)
If you need to support legacy browsers that don't follow the W3C recommendations, generally inside a function you would use something like the following:
function(e) {
var event = e || window.event;
[...];
}
which would check first one, and then the other and store whichever was found inside the event variable. However in an inline event handler there isn't an e object to use. In that case you have to take advantage of the arguments collection which is always available and refers to the complete set of arguments passed to a function:
onclick="var event = arguments[0] || window.event; [...]"
However, generally speaking you should be avoiding inline event handlers if you need to to anything complicated like stopping propagation. Writing your event handlers separately and the attaching them to elements is a much better idea in the medium and long term, both for readability and maintainability.
Keep in mind that window.event is not supported in FireFox, and therefore it must be something along the lines of:
e.cancelBubble = true
Or, you can use the W3C standard for FireFox:
e.stopPropagation();
If you want to get fancy, you can do this:
function myEventHandler(e)
{
if (!e)
e = window.event;
//IE9 & Other Browsers
if (e.stopPropagation) {
e.stopPropagation();
}
//IE8 and Lower
else {
e.cancelBubble = true;
}
}
Use this function, it will test for the existence of the correct method.
function disabledEventPropagation(event)
{
if (event.stopPropagation){
event.stopPropagation();
}
else if(window.event){
window.event.cancelBubble=true;
}
}
I had the same issue - js error box in IE - this works fine in all browsers as far as I can see (event.cancelBubble=true does the job in IE)
onClick="if(event.stopPropagation){event.stopPropagation();}event.cancelBubble=true;"
This worked for me
<script>
function cancelBubble(e) {
var evt = e ? e:window.event;
if (evt.stopPropagation) evt.stopPropagation();
if (evt.cancelBubble!=null) evt.cancelBubble = true;
}
</script>
<div onclick="alert('Click!')">
<div onclick="cancelBubble(event)">Something inside the other div</div>
</div>
For ASP.NET web pages (not MVC), you can use Sys.UI.DomEvent object as wrapper of native event.
<div onclick="event.stopPropagation();" ...
or, pass event as a parameter to inner function:
<div onclick="someFunction(event);" ...
and in someFunction:
function someFunction(event){
event.stopPropagation(); // here Sys.UI.DomEvent.stopPropagation() method is used
// other onclick logic
}
I cannot comment because of Karma so I write this as whole answer: According to the answer of Gareth (var e = arguments[0] || window.event; [...]) I used this oneliner inline on the onclick for a fast hack:
<div onclick="(arguments[0] || window.event).stopPropagation();">..</div>
I know it's late but I wanted to let you know that this works in one line. The braces return an event which has the stopPropagation-function attached in both cases, so I tried to encapsulate them in braces like in an if and....it works. :)
According to this page, in IE you need:
event.cancelBubble = true
Use separate handler, say:
function myOnClickHandler(th){
//say let t=$(th)
}
and in html do this:
<...onclick="myOnClickHandler(this); event.stopPropagation();"...>
Or even :
function myOnClickHandler(e){
e.stopPropagation();
}
for:
<...onclick="myOnClickHandler(event)"...>
Why not just check which element was clicked? If you click on something, window.event.target is assigned to the element which was clicked, and the clicked element can also be passed as an argument.
If the target and element aren't equal, it was an event that propagated up.
function myfunc(el){
if (window.event.target === el){
// perform action
}
}
<div onclick="myfunc(this)" />
This also works - In the link HTML use onclick with return like this :
Delete
And then the comfirmClick() function should be like:
function confirmClick() {
if(confirm("Do you really want to delete this task?")) {
return true;
} else {
return false;
}
};
<div onclick="alert('you clicked the header')" class="header">
<span onclick="alert('you clicked inside the header'); event.stopPropagation()">
something inside the header
</span>
</div>
Event.preventDefault()
is the current norm, and the one thing that worked for me. See: https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault
<button value=login onclick="login(event)">login</button>
//and in a script tag
function login(ev){
ev.preventDefault()
return false;
}
this worked in the latest Chrome, Opera, and IE. (the Mozilla page indicates Firefox would do it too, so I don't even test it!)
The best solution would be handle with the event through a javascript function, but in order to use a simple and quick solution using the html element directly, and once that the "event" and "window.event" are deprecated and not universally supported (https://developer.mozilla.org/en-US/docs/Web/API/Window/event), I suggest the following "hard code":
<div onclick="alert('blablabla'); (arguments[0] ? arguments[0].stopPropagation() : false);">...</div>

Passing argument to JS function from link onclick

I have a link that looks like this:
<a id="mylink" onclick="deleteHike( 3 );" href="javascript:void(0);">Yes</a>
It is able to call this JavaScript:
window.onload = function()
{
//Get a reference to the link on the page
// with an id of "mylink"
var a = document.getElementById("mylink");
//Set code to run when the link is clicked
// by assigning a function to "onclick"
a.onclick = function( hike_id )
{
// Somecode her
// But when I try to use the hike_id it displays as [object MouseEvent]
}
}
But the value that comes in is [object MouseEvent], not the number that I was expecting. Any idea why this happens and how to fix this? :)
Thanks!
You are trying to assign the function to your link in two different and conflicting ways.
Using the eval-ed function string, onclick = "function(value)", works but is deprecated.
The other way of binding the click handler in the onload event works too, but if you want a particular value to be passed, you'll have to change your script a bit because the value as given in the initial onclick is completely lost when you set the onclick to a new function.
To make your current method work, you don't need an onload handler at all. You just need this:
function deleteHike(hike_id) {
// Some code here
}
To do it the second way, which I recommend, it would look like this:
<a id="mylink" href="javascript:void(0);">Yes</a>
with this script:
function deleteHike(e, hike_id) {
// Some code here
// e refers to the event object which you can do nifty things with like
// - learn the actual clicked element if it was a parent or child of the `this` element
// - stop the event from bubbling up to parent items
// - stop the event from being captured by child items
// (I may have these last two switched)
}
function getCall(fn, param) {
return function(e) {
e = e || window.event;
e.preventDefault(); // this might let you use real URLs instead of void(0)
fn(e, param);
};
}
window.onload = function() {
var a = document.getElementById("mylink");
a.onclick = getCall(deleteHike, 3);
};
The parameter of a DOM event function is the event object (in Firefox and other standards-compliant browsers). It is nothing in IE (thus the need to also grab window.event). I added a little helper function for you that creates a closure around your parameter value. You could do that each time yourself but it would be a pain. The important part is that getCall is a function that returns a function, and it is this returned function that gets called when you click on the element.
Finally, I recommend strongly that instead of all this, you use a library such as jQuery because it solves all sorts of problems for you and you don't have to know crazy JavaScript that takes much expertise to get just right, problems such as:
Having multiple handlers for a single event
Running JavaScript as soon as possible before the onload event fires with the simulated event ready. For example, maybe an image is still downloading but you want to put the focus on a control before the user tries to use the page, you can't do that with onload and it is a really hard problem to solve cross-browser.
Dealing with how the event object is being passed
Figuring out all the different ways that browsers handle things like event propagation and getting the clicked item and so on.
Note: in your click handler you can just use the this event which will have the clicked element in it. This could be really powerful for you, because instead of having to encode which item it was in the JavaScript for each element's onclick event, you can simply bind the same handler to all your items and get its value from the element. This is better because it lets you encode the information about the element only in the element, rather than in the element and the JavaScript.
You should just be able to declare the function like this (no need to assign on window.onload):
function deleteHike(hike_id)
{
// Somecode her
// But when I try to use the hike_id it displays as [object MouseEvent]
}
The first parameter in javascript event is the event itself. If you need a reference back to the "a" tag you could use the this variable because the scope is now the "a" tag.
Here's my new favorite way to solve this problem. I like this approach for its clarity and brevity.
Use this HTML:
<a onclick="deleteHike(event);" hike_id=1>Yes 1</a><br/>
<a onclick="deleteHike(event);" hike_id=2>Yes 2</a><br/>
<a onclick="deleteHike(event);" hike_id=3>Yes 3</a><br/>
With this JavaScript:
function deleteHike(event) {
var element = event.target;
var hike_id = element.getAttribute("hike_id");
// do what you will with hike_id
if (confirm("Delete hike " + hike_id + "?")) {
// do the delete
console.log("item " + hike_id + " deleted");
} else {
// don't do the delete
console.log("user canceled");
}
return;
}
This code works because event is defined in the JavaScript environment when the onclick handler is called.
For a more complete discussion (including why you might want to use "data-hike_id" instead of "hike_id" as the element attribute), see: How to store arbitrary data for some HTML tags.
These are alternate forms of the HTML which have the same effect:
<a onclick="deleteHike(event);" hike_id=4 href="javascript:void(0);">Yes 4</a><br/>
<button onclick="deleteHike(event);" hike_id=5>Yes 5</button><br/>
<span onclick="deleteHike(event);" hike_id=6>Yes 6</span><br/>
When you assign a function to an event on a DOM element like this, the browser will automatically pass the event object (in this case MouseEvent as it's an onclick event) as the first argument.
Try it like this,
a.onclick = function(e, hike_id) { }

window.event.srcElement doesn't work for firefox?

The following doesn't work for firefox. I'm trying delete the table row on click. Can anyone please help. Many thanks.
<INPUT TYPE="Button" onClick="delRow()" VALUE="Remove">
function delRow(){
if(window.event){
var current = window.event.srcElement;
}else{
var current = window.event.target;
}
//here we will delete the line
while ( (current = current.parentElement) && current.tagName !="TR");
current.parentElement.removeChild(current);
}
window.event is IE only. window.event does not exist in W3C standard.
event object by default is pass in as the first argument to a event handler with the W3C standard.
an inline onlick event in the markup calling a function mean that the event handler is calling that function. With your markup as example. It mean function() { delRow(); }. As you can see you won't be able to see the event object in delRow() except when you are in IE because event is in the window object.
parentElement is also IE only, in most case changing it to parentNode would work. Assuming the parent node is also an element.
I suggest you to use javascript library such as jQuery or change your code if you need to keep things relatively the same.
<INPUT TYPE="Button" onclick="delRow(event);" VALUE="Remove">
function delRow(e) {
var evt = e || window.event; // this assign evt with the event object
var current = evt.target || evt.srcElement; // this assign current with the event target
// do what you need to do here
}
You have to use event.target instead of window.event.target to work for Firefox. Try to use the following.
<INPUT TYPE="Button" onclick="delRow()" VALUE="Remove">
function delRow(){
if(window.event){
var current = window.event.srcElement;
}else{
current = event.target;
}
//here we will delete the line
while ( (current = current.parentElement) && current.tagName !="TR");
current.parentElement.removeChild(current);
}
var CurrentObject =
0 < window.navigator.appVersion.toString().indexOf("MSIE")
?
window.event.srcElement
:
evt.target;
Here's Mozilla's documentation of the Event class; might give you some insight.
NEVER use individual browser checks like "check for MSIE".
Do you know how many browsers you'd have to check for... and individual browser VERSIONS... to check them all?
NEVER use jQuery for this either. Write correct code yourself. Never include (useless) massive libraries when you aren't going to use 99% of their features anyway.
just found out, works on ie & ff and chrome. others don't know but I expect that this will work on allso the rest. at least hope so :)
As a beginner in html, JS and PHP, it's very annoying that there is not a standard in these things ! even styling a simple div element can be a headage because of the behavior is not allways the same on different browsers !?
function somefunc()
{
var callerelement = arguments.callee.caller.arguments[0].target;
alert(callerelement.id)
}

How to stop event propagation with inline onclick attribute?

Consider the following:
<div onclick="alert('you clicked the header')" class="header">
<span onclick="alert('you clicked inside the header');">something inside the header</span>
</div>
How can I make it so that when the user clicks the span, it does not fire the div's click event?
Use event.stopPropagation().
<span onclick="event.stopPropagation(); alert('you clicked inside the header');">something inside the header</span>
For IE: window.event.cancelBubble = true
<span onclick="window.event.cancelBubble = true; alert('you clicked inside the header');">something inside the header</span>
There are two ways to get the event object from inside a function:
The first argument, in a W3C-compliant browser (Chrome, Firefox, Safari, IE9+)
The window.event object in Internet Explorer (<=8)
If you need to support legacy browsers that don't follow the W3C recommendations, generally inside a function you would use something like the following:
function(e) {
var event = e || window.event;
[...];
}
which would check first one, and then the other and store whichever was found inside the event variable. However in an inline event handler there isn't an e object to use. In that case you have to take advantage of the arguments collection which is always available and refers to the complete set of arguments passed to a function:
onclick="var event = arguments[0] || window.event; [...]"
However, generally speaking you should be avoiding inline event handlers if you need to to anything complicated like stopping propagation. Writing your event handlers separately and the attaching them to elements is a much better idea in the medium and long term, both for readability and maintainability.
Keep in mind that window.event is not supported in FireFox, and therefore it must be something along the lines of:
e.cancelBubble = true
Or, you can use the W3C standard for FireFox:
e.stopPropagation();
If you want to get fancy, you can do this:
function myEventHandler(e)
{
if (!e)
e = window.event;
//IE9 & Other Browsers
if (e.stopPropagation) {
e.stopPropagation();
}
//IE8 and Lower
else {
e.cancelBubble = true;
}
}
Use this function, it will test for the existence of the correct method.
function disabledEventPropagation(event)
{
if (event.stopPropagation){
event.stopPropagation();
}
else if(window.event){
window.event.cancelBubble=true;
}
}
I had the same issue - js error box in IE - this works fine in all browsers as far as I can see (event.cancelBubble=true does the job in IE)
onClick="if(event.stopPropagation){event.stopPropagation();}event.cancelBubble=true;"
This worked for me
<script>
function cancelBubble(e) {
var evt = e ? e:window.event;
if (evt.stopPropagation) evt.stopPropagation();
if (evt.cancelBubble!=null) evt.cancelBubble = true;
}
</script>
<div onclick="alert('Click!')">
<div onclick="cancelBubble(event)">Something inside the other div</div>
</div>
For ASP.NET web pages (not MVC), you can use Sys.UI.DomEvent object as wrapper of native event.
<div onclick="event.stopPropagation();" ...
or, pass event as a parameter to inner function:
<div onclick="someFunction(event);" ...
and in someFunction:
function someFunction(event){
event.stopPropagation(); // here Sys.UI.DomEvent.stopPropagation() method is used
// other onclick logic
}
I cannot comment because of Karma so I write this as whole answer: According to the answer of Gareth (var e = arguments[0] || window.event; [...]) I used this oneliner inline on the onclick for a fast hack:
<div onclick="(arguments[0] || window.event).stopPropagation();">..</div>
I know it's late but I wanted to let you know that this works in one line. The braces return an event which has the stopPropagation-function attached in both cases, so I tried to encapsulate them in braces like in an if and....it works. :)
According to this page, in IE you need:
event.cancelBubble = true
Use separate handler, say:
function myOnClickHandler(th){
//say let t=$(th)
}
and in html do this:
<...onclick="myOnClickHandler(this); event.stopPropagation();"...>
Or even :
function myOnClickHandler(e){
e.stopPropagation();
}
for:
<...onclick="myOnClickHandler(event)"...>
Why not just check which element was clicked? If you click on something, window.event.target is assigned to the element which was clicked, and the clicked element can also be passed as an argument.
If the target and element aren't equal, it was an event that propagated up.
function myfunc(el){
if (window.event.target === el){
// perform action
}
}
<div onclick="myfunc(this)" />
This also works - In the link HTML use onclick with return like this :
Delete
And then the comfirmClick() function should be like:
function confirmClick() {
if(confirm("Do you really want to delete this task?")) {
return true;
} else {
return false;
}
};
<div onclick="alert('you clicked the header')" class="header">
<span onclick="alert('you clicked inside the header'); event.stopPropagation()">
something inside the header
</span>
</div>
Event.preventDefault()
is the current norm, and the one thing that worked for me. See: https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault
<button value=login onclick="login(event)">login</button>
//and in a script tag
function login(ev){
ev.preventDefault()
return false;
}
this worked in the latest Chrome, Opera, and IE. (the Mozilla page indicates Firefox would do it too, so I don't even test it!)
The best solution would be handle with the event through a javascript function, but in order to use a simple and quick solution using the html element directly, and once that the "event" and "window.event" are deprecated and not universally supported (https://developer.mozilla.org/en-US/docs/Web/API/Window/event), I suggest the following "hard code":
<div onclick="alert('blablabla'); (arguments[0] ? arguments[0].stopPropagation() : false);">...</div>

Categories

Resources