Why jquery click event is not firing on firefox? - javascript

I have this function in JS :
jQuery(function ($) {
$(document).on("click", ".botaoExcluirRecibos", function (e) {
e.preventDefault();
alert("Fired!");
});
});
And in my asp.net page i have this button:
<div class="listaExcluir" id="listaExcluir">
<ul id="listaArquivos">
<li>
<div class="voceAnexou"></div>
<div class="divInformacoesAtendimento divInformacoesAtendimentoTabelaRecibo">
<p>Você anexou:<strong> file1.png </strong></p>
<button class="botaoVermelhoPequeno botaoExcluirRecibos" onclick="return false;">Excluir</button>
</div>
</li>
</ul>
</div>
The button is added dynamically on the li tag, and more buttons can be added by the user.
It's not firing the click event at FIREFOX , but at CHROME is.
Obs: I had to add the onclick event inline on the button for preventing the postback issue.

First, you can add "return false;" to your event handler and it will avoid postbacks - you don't need to have it inline.
Second, I would recommend a binding function:
function BindClick(){
$(".botaoExcluirRecibos").unbind("click"); // To prevent double-binding click events!
$(".botaoExcluirRecibos").on("click", function(e){
e.preventDefault();
console.log("Fired!"); //Use the console instead of alerts for debugging purposes!
return false;
});
}
Now, just call:
BindClick();
Every time you add a control to the page that will need this event handler. This should work in every browser.

Related

Anchor link takes two clicks to fire the event

The HTML:
<asp:TextBox ID="dataTextBox" MaxLength="10" runat="server"></asp:TextBox>
<a class='new_message' onclick='focusMethod();' tabindex='-1' href='#dataTextBox"> New Message</a>";
Jquery function:
function focusMethod() {
$('[class=new_message]').click(function (e) {
e.preventDefault();
$($(this).attr('href')).focus();
});
}
When i click the anchor link the focus should go to the input text box. But it is taking 2 clicks to perform.
My scenarios are:
onclick is used in anchor tag to prevent default behaviour i.e firing the href.
I am building an accessible form so i need the href with value (so i wont be able to use href="#")
If i use just the click event handler without the function it is not being fired( instead href is fired and focus is not going to textbox)
It takes 2 clicks because the function focusMethod is fired first and then event handler is attached.
Is there any way to avoid performing the function "focusmethod' and only perform click event handler?
Because your method focusMethod is binding a new click event which is then executing next time you click that element. Just remove the inline click event onclick='focusMethod();' as it's not needed. Then instead of a function you can just do:
$('[class=new_message]').click(function (e) {
e.preventDefault();
$($(this).attr('href')).focus();
});
Edit:
Since your element is dynamic you need to use $(document).on(...) instead, otherwise the selector $(...).click(..) isn't going to find the element as it wouldn't exist when setting up the click event binding.
Below is a basic example with the element being dynamically created:
$(document).on("click", "[class=new_message]", function (e) {
e.preventDefault();
console.log("clicked");
$($(this).attr('href')).focus();
});
$("body").html("<a class='new_message' tabindex='-1' href='#dataTextBox'> New Message</a>");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
remove click event in HTML.
use only class.click in JS.
for href you are opening with single quote but closing with double quote.
$('[class=new_message]').click(function(e) {
e.preventDefault();
$($(this).attr('href')).focus();
});
<a class='new_message' tabindex='-1' href='#dataTextBox'> New Message</a>
It takes 2 clicks because the function focusMethod is fired first and then event handler is attached.
You've correctly identified the issue, you're requiring a click to run the function that contains the jQuery .click function. Just remove the focusMethod() function (and onclick) altogether.
$('.new_message').click(function(e) {
e.preventDefault();
$($(this).attr('href')).focus();
});
<asp:TextBox ID="dataTextBox" MaxLength="10" runat="server"></asp:TextBox>
<a class='new_message' tabindex='-1' href='#dataTextBox'>New Message</a>
If #Spencer Wieczorek answer(accepted answer) is not working for someone then you should just need a simple replace 'click' to 'turbolinks:click'.
$(document).on("turbolinks:click", "[class=new_message]", function (e) {
e.preventDefault();
console.log("clicked");
$($(this).attr('href')).focus();
});

Lost "click" event during AJAX refresh

$(":input").on("change", function(e) {
console.log("change triggered");
$("#section").html("<button id='order'>Order</button>");
registerButtons();
});
function registerButtons() {
$("#order").on("click", function(e) {
console.log("click triggered");
alert("Hello World");
});
$("#order").on("mousedown mouseup", function(e) {
console.log(e.type + " triggered");
});
}
registerButtons();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="123"/>
<div id="section">
<button id="order">Order</button>
</div>
I have a web page with a button and some input fields.
On the button an click event is registered
On the input fields an change event is registered
The onChange will trigger an AJAX server call, and the result will replace parts of the web page - including the button. After AJAX result is processed, all listener are registered again.
Now the problem. A user changes the value of an input field, and clicks directly the button - but to slow (lets assume the user needs 500ms for the click), so the onChange event is fired and the page is "updated/replaced". Now the "old" button fires an onMouseDown and the "new" button fires an onMouseUp event - but no onClick.
My current workaround is, to register the two mouseDown/mouseUp events, get the timestamp of the mouse down, and if the mouse up comes in 2 seconds, do what should be done by the onClick.
It is no option to remove the button part from the AJAX response - in worst case the button could be removed and replaced by an user info.
My hope is, that there is a better solution... any ideas?
You can take advantage of the event delegation and set your listener on the container instead of the button.
You are adding a click listener to your old button and your adding a new button to the dom. So the click won't work.
The button wasn't working because for some reason it can't focus when you hover over it. So I added a getFocus method and now it should work.
$("input").on("change", function(e) {
console.log("change triggered");
$("#section").html("<button id='order'>Order</button>");
});
function registerButtons() {
$('#section').on("mouseup", '#order', function(e) {
alert('Clicked!');
});
}
registerButtons();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="123"/>
<div id="section">
<button id="order">Order</button>
</div>
I just found out that jQuery provides a sweet API that can be used for event delegation. This way we don't have to manually check for event target. Check it out http://api.jquery.com/on/
$("input").on("change", function(e) {
console.log("change triggered");
$("#section").html("<button id='order'>Order</button>");
});
function registerButtons() {
$("#section").on("click", '#order', function(e) {
console.log("click triggered");
alert("Hello World");
});
$("#section").on('mouseover','#order', function(e){
$(this).focus();
});
}
registerButtons();

event.preventDefault() not working

I had button which had onclick function
<div id="canvas">
<button onclick="document.location.href='hello.php'">Go</button>
</div>
Now I want to stop this onclick event which redirects to hello.php, so I have written the following jQuery function
$("#canvas").on('click', 'button', function(event) {
event.preventDefault();
});
This didn't work so I added a return false but it's still not working.
$("#canvas").on('click', 'button', function(event) {
event.preventDefault();
return false;
});
You can view it at Jsfiddle
Note: I do not want to remove onclick of button
The correct solution is to remove the onclick from the HTML in the first place.
Assuming that's not possible, you can remove it after the fact:
$("#canvas button").first().prop("onclick", null);
That clears the onclick property on the element, which removes the handler set up by the onclick attribute. (It's a no-op if the button doesn't exist at all.)
It's probably worth noting that if the button is in a form, it will now submit the form, since its onclick isn't taking the user away from the page. (Since button's default type is submit.)
You should just use the removeAttr jQuery method:
$('#canvas button').removeAttr('onclick');

When to use PreventDefault( ) vs Return false? [duplicate]

This question already has answers here:
What's the difference between event.stopPropagation and event.preventDefault?
(8 answers)
Closed 7 years ago.
Firstly, in JavaScript's event model, you will come
across a concept called as event bubbling
(which makes an event to propagate from child
element to a parent element). In order to avoid
such kind of bubbling effect, many developers
use an event method called stopPropagation( ).
Alternatively, developers have started to use
return false statement to stop such propagation.
Now, there is another terminology called
preventDefault( ). As the name indicates, this
method prevents any default behavior of an
element to trigger. Best use case is to prevent an
anchor tag to open a link.
You may come across a scenario where you
would like to prevent the anchor tag from
opening a link (default behavior) as well as stop
the event from going up to the parent.
In such situation, instead of writing two lines of code,
you can get it done in single line i.e; return false
return false;
return false; does 3 separate things when you call it:
event.preventDefault() – It stops the browsers default behaviour.
event.stopPropagation() – It prevents the event from propagating (or “bubbling up”) the DOM.
Stops callback execution and returns immediately when called.
Note that this behaviour differs from normal (non-jQuery) event handlers, in which, notably, return false does not stop the event from bubbling up.
preventDefault();
preventDefault(); does one thing: It stops the browsers default behaviour.
When to use them?
We know what they do but when to use them? Simply it depends on what you want to accomplish. Use preventDefault(); if you want to “just” prevent the default browser behaviour. Use return false; when you want to prevent the default browser behaviour and prevent the event from propagating the DOM. In most situations where you would use return false; what you really want is preventDefault().
Examples:
Let’s try to understand with examples:
We will see pure JAVASCRIPT example
Example 1:
<div onclick='executeParent()'>
<a href='http://stackoverflow.com' onclick='executeChild()'>Click here to visit stackoverflow.com</a>
</div>
<script>
function executeChild() {
alert('Link Clicked');
}
function executeParent() {
alert('div Clicked');
}
</script>
Run the above code you will see the hyperlink ‘Click here to visit
stackoverflow.com‘ now if you click on that link first you will get
the javascript alert Link Clicked Next you will get the javascript
alert div Clicked and immediately you will be redirected to
stackoverflow.com.
Example 2:
<div onclick='executeParent()'>
<a href='http://stackoverflow.com' onclick='executeChild()'>Click here to visit stackoverflow.com</a>
</div>
<script>
function executeChild() {
event.preventDefault();
event.currentTarget.innerHTML = 'Click event prevented'
alert('Link Clicked');
}
function executeParent() {
alert('div Clicked');
}
</script>
Run the above code you will see the hyperlink ‘Click here to visit
stackoverflow.com‘ now if you click on that link first you will get
the javascript alert Link Clicked Next you will get the javascript
alert div Clicked Next you will see the hyperlink ‘Click here to
visit stackoverflow.com‘ replaced by the text ‘Click event prevented‘
and you will not be redirected to stackoverflow.com. This is due > to event.preventDefault() method we used to prevent the default click
action to be triggered.
Example 3:
<div onclick='executeParent()'>
<a href='http://stackoverflow.com' onclick='executeChild()'>Click here to visit stackoverflow.com</a>
</div>
<script>
function executeChild() {
event.stopPropagation();
event.currentTarget.innerHTML = 'Click event is going to be executed'
alert('Link Clicked');
}
function executeParent() {
alert('div Clicked');
}
</script>
This time if you click on Link the function executeParent() will not
be called and you will not get the javascript alert div Clicked
this time. This is due to us having prevented the propagation to the
parent div using event.stopPropagation() method. Next you will see the
hyperlink ‘Click here to visit stackoverflow.com‘ replaced by the text
‘Click event is going to be executed‘ and immediately you will be
redirected to stackoverflow.com. This is because we haven’t prevented
the default click action from triggering this time using
event.preventDefault() method.
Example 4:
<div onclick='executeParent()'>
<a href='http://stackoverflow.com' onclick='executeChild()'>Click here to visit stackoverflow.com</a>
</div>
<script>
function executeChild() {
event.preventDefault();
event.stopPropagation();
event.currentTarget.innerHTML = 'Click event prevented'
alert('Link Clicked');
}
function executeParent() {
alert('Div Clicked');
}
</script>
If you click on the Link, the function executeParent() will not be
called and you will not get the javascript alert. This is due to us
having prevented the propagation to the parent div using
event.stopPropagation() method. Next you will see the hyperlink ‘Click
here to visit stackoverflow.com‘ replaced by the text ‘Click event
prevented‘ and you will not be redirected to stackoverflow.com. This
is because we have prevented the default click action from triggering
this time using event.preventDefault() method.
Example 5:
For return false I have three examples and all appear to be doing the exact same thing (just returning false), but in reality the
results are quite different. Here's what actually happens in each of
the above.
cases:
Returning false from an inline event handler prevents the browser from navigating to the link address, but it doesn't stop the event from propagating through the DOM.
Returning false from a jQuery event handler prevents the browser from navigating to the link address and it stops the event from propagating through the DOM.
Returning false from a regular DOM event handler does absolutely nothing.
Will see all three example.
Inline return false.
<div onclick='executeParent()'>
<a href='http://stackoverflow.com' onclick='return false'>Click here to visit stackoverflow.com</a>
</div>
<script>
var link = document.querySelector('a');
link.addEventListener('click', function() {
event.currentTarget.innerHTML = 'Click event prevented using inline html'
alert('Link Clicked');
});
function executeParent() {
alert('Div Clicked');
}
</script>
Returning false from a jQuery event handler.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<a href='http://stackoverflow.com'>Click here to visit stackoverflow.com</a>
</div>
<script>
$('a').click(function(event) {
alert('Link Clicked');
$('a').text('Click event prevented using return FALSE');
$('a').contents().unwrap();
return false;
});
$('div').click(function(event) {
alert('Div clicked');
});
</script>
Returning false from a regular DOM event handler.
<div onclick='executeParent()'>
<a href='http://stackoverflow.com' onclick='executeChild()'>Click here to visit stackoverflow.com</a>
</div>
<script>
function executeChild() {
event.currentTarget.innerHTML = 'Click event prevented'
alert('Link Clicked');
return false
}
function executeParent() {
alert('Div Clicked');
}
</script>
Hope these examples are clear. Try executing all these examples in a html file to see how they work.

How to replace event handler when button is disabled

I have a situation where I have to replace all unauthorized controls in My UI from hidden state to disabled. Add a tooltip with un authorized text. Click the control to see unauthorized text.
I am able to update code but blocked at one point where I have to stop firing event on the control.
At the same time I have to show an alert on click of the event. How can I do this?
My trails are here in fiddle
Problem:
I have [clickdisabled = disable] click function which need to be called if control is disabled.
But at the same time on the control I have onclick="SearchDetails(); called which is throwing an error.
<input id="btnSearch" type="button" name="btnSearch" value="Search" onclick="SearchDetails();return false;" title="search" clickDisabled=disable />
//Add title to all disabled items in project
$('[clickdisabled=disable]').attr("title", "You are not authorized to perform this action.");
// Show unauthorized error on click of disabled control
$('[clickdisabled = disable]').click(function () {
alert($(this).attr("title"));
});
If you are expecting situations when the functions are not available, you could check if they exist before calling them:
<input id="btnSearch" type="button" name="btnSearch" value="Search"
onclick="if (typeof(SearchDetails) === typeof(Function)) SearchDetails();"
title="search" clickDisabled=disable />
Fiddle
What you need to do is keep track of both your normal onclick event handler and disabled onclick event handler. When you disable your button, remove the normal onclick event handler and add your disabled onclick event handler. When you re-enable the button, remove the disabled onclick event handler, and add the normal event handler back. You can do this with the jQuery .on() and .off() events (see the example below).
function onNormalClick(e){
alert('This is the default test button functionality.');
}
function onDisabledClick(e){
alert('This button is disabled.');
e.preventDefault();
e.stopPropagation();
}
function disableButtons(selector){
$(selector).css('color', '#888');
$(selector).off('click', onNormalClick);
$(selector).on('click', onDisabledClick);
}
function enableButtons(selector){
$(selector).css('color', '#000');
$(selector).off('click', onDisabledClick);
$(selector).on('click', onNormalClick);
}
$(document).ready(function(){
$('.test').on('click', onNormalClick);
$('#disabler').click(function(){
disableButtons('.test');
});
$('#enabler').click(function(){
enableButtons('.test');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class='test'>Test</button>
<hr/>
<button id=disabler>Disable</button>
<button id=enabler>Enable</button>
You could prevent the default handling like this:
var button = $('#your_button_id');
button.click(function(e){
e.preventDefault();
alert("Your alert message for the user");
});

Categories