Jquery .on('click,'button' not working - javascript

I need to check if user closed browser. There is no reliable way, but the most accurate way seems to use onbeforeunload and check if a link or a button was clicked. I will also add f5 and some other extra checking.
But I have problem with button. If I click button, ajax call will be made even if there is if(window.link_was_clicked==false) condition.
<button onclick="setLocation('http://dev.site.com/checkout/')" class="button" title="Checkout" type="button"><span><span>Checkout</span></span></button>
And script:
jQuery(document).on('click', 'button', function(event) {
window.link_was_clicked= true;
});
window.onbeforeunload = function() {
if(window.link_was_clicked==false){
//make ajax call
}
};
It seems the problem is because there is setLocation function attached to button onclick. Is there any way to trigger jQuery(document).on first?

That variable doesnt exist on before load. so add it on the top and try again
window.link_was_clicked=window.link_was_clicked||false;
jQuery(document).on('click', 'button', function(event) {
window.link_was_clicked= true;
});
window.onbeforeunload = function() {
if(window.link_was_clicked==false){
//make ajax call
}
};

Since you haven't provided the code for setLocation(), I'll assume that that's where the problem is. Now, regarding a change to the order of execution of your click event handlers:
It is in general bad to have both embedded onclick and jquery-bound handlers, it leads to all sorts of confusion. If you can't change the html, however, you could do what this guy suggests: https://stackoverflow.com/a/7507888/2685386
$(document).ready(function() {
var myClick = $('button').attr('onclick');
$('button').removeAttr('onclick');
$(document).on('click', 'button', function(e) {
window.link_was_clicked=true;
// do my other stuff here....
eval(myClick);// this will now call setLocation()
});
});

Related

the disable functionality is working if I give alert inside the function

I tried to disable the click functionality for the element with id #sports. It works if I invoke alert() inside the function, but I want it to work without invoking it. If I comment out that code, it's not working.
Here is my code:
$("#sports").off("click").on("click", function () {
alert("disable click");
});
You can disabled it with calling the off() method inside the on() method:
$("#sports").on("click", function (){ // on button click
console.log("click disabled"); // Do anything, console.log, alert, anything
$(this).off("click"); // then disable the click event, set it to off,
// this way the on click event won't fire
// again unless it's created, again
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="sports">Click</button>
What about trying event.preventDefault()?
$("#sports").on("click", function (event){
event.preventDefault();
event.stopPropagation();
return false;
});
But if you want to disable it, you don't have to override its click function - it is enough to set 'disable' property of the DOM element:
$("#sports").disabled = true;

Calling registered event callback function based on conditions

Say I have a simple button like:
<button id='test'>ClickME</button>
on which through some script (provided by some other person), a click event is registered, like this:
$('#test').on('click', function(){
alert('click 1'); //Some lines of code
});
Later on the page load, I ran my script on top of it, in which I wanted to perform some actions on the same button click. In the script, I wrote something like:
$('#test').on('click', function(){
alert('click 2'); //Some lines of code
});
In this case, when I click on the button, I am getting two alerts which is understandable.
What I wanted to achieve is, First "click 2" should be alerted and in the same code, based on some condition, I may or may not call the previously registered function, i.e. "click 1" alert. I have no clue whether we can achieve such things and if yes, how can I prevent execution of already registered event?
Any help is appreciated.
You can unbind all previous event handlers from an element. Before that, you can store what they were. This allows you to write code like:
// not your code
$('#test').on('click', function(){
alert('click 1'); //Some lines of code
});
// your code
var prevHandler = $._data($("#test")[0], "events").click[0].handler;
$('#test').off('click');
$('#test').on('click', function(){
alert('click 2'); //Some lines of code
if (Math.random() > 0.5)
prevHandler();
});
jsfiddle: https://jsfiddle.net/ugefofLs/
Both handlers will run, the jQuery event model allows multiple handlers on one element, therefore a later handler does not override an older handler.
The handlers will execute in the order in which they were bound.
I suggest you merge the two code block something like this:
$('#test').on('click', function(){
alert('click 2'); //Some lines of code
if (some condition){
alert('click 1'); //Some lines of code
}
});
If you do not know whether or not other events have been registered, and still want to make sure only your event fires, you can use jQuerys event.stopImmediatePropagation() to only allow your event to be run.
event.stopImmediatePropagation()
Keeps the rest of the handlers from being executed and prevents the event from bubbling up the DOM tree.Keeps the rest of the handlers from
See the code and snippet below
//Change this to false to let both registrered events run
var preventOtherClickEvents = true;
var onClick = function(event) {
if (preventOtherClickEvents) {
event.stopImmediatePropagation();
}
alert('First event handler');
};
var onClickSecond = function() {
alert('Second event handler');
};
$('#button').on('click', onClick);
$('#button').on('click', onClickSecond);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id="button" value="Click Me" />

How to get JQuery.trigger('click'); to initiate a mouse click

I'm having a hard time understand how to simulate a mouse click using JQuery. Can someone please inform me as to what i'm doing wrong.
HTML:
<a id="bar" href="http://stackoverflow.com" target="_blank">Don't click me!</a>
<span id="foo">Click me!</span>
jQuery:
jQuery('#foo').on('click', function(){
jQuery('#bar').trigger('click');
});
Demo: FIDDLE
when I click on button #foo I want to simulate a click on #bar however when I attempt this, nothing happens. I also tried jQuery(document).ready(function(){...}) but without success.
You need to use jQuery('#bar')[0].click(); to simulate a mouse click on the actual DOM element (not the jQuery object), instead of using the .trigger() jQuery method.
Note: DOM Level 2 .click() doesn't work on some elements in Safari. You will need to use a workaround.
http://api.jquery.com/click/
You just need to put a small timeout event before doing .click()
like this :
setTimeout(function(){ $('#btn').click()}, 100);
This is JQuery behavior. I'm not sure why it works this way, it only triggers the onClick function on the link.
Try:
jQuery(document).ready(function() {
jQuery('#foo').on('click', function() {
jQuery('#bar')[0].click();
});
});
See my demo: http://jsfiddle.net/8AVau/1/
jQuery(document).ready(function(){
jQuery('#foo').on('click', function(){
jQuery('#bar').simulateClick('click');
});
});
jQuery.fn.simulateClick = function() {
return this.each(function() {
if('createEvent' in document) {
var doc = this.ownerDocument,
evt = doc.createEvent('MouseEvents');
evt.initMouseEvent('click', true, true, doc.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
this.dispatchEvent(evt);
} else {
this.click(); // IE Boss!
}
});
}
May be useful:
The code that calls the Trigger should go after the event is called.
For example, I have some code that I want to be executed when #expense_tickets value is changed, and also, when page is reload
$(function() {
$("#expense_tickets").change(function() {
// code that I want to be executed when #expense_tickets value is changed, and also, when page is reload
});
// now we trigger the change event
$("#expense_tickets").trigger("change");
})
jQuery's .trigger('click'); will only cause an event to trigger on this event, it will not trigger the default browser action as well.
You can simulate the same functionality with the following JavaScript:
jQuery('#foo').on('click', function(){
var bar = jQuery('#bar');
var href = bar.attr('href');
if(bar.attr("target") === "_blank")
{
window.open(href);
}else{
window.location = href;
}
});
Try this that works for me:
$('#bar').mousedown();
Technically not an answer to this, but a good use of the accepted answer (https://stackoverflow.com/a/20928975/82028) to create next and prev buttons for the tabs on jQuery ACF fields:
$('.next').click(function () {
$('#primary li.active').next().find('.acf-tab-button')[0].click();
});
$('.prev').click(function () {
$('#primary li.active').prev().find('.acf-tab-button')[0].click();
});
I have tried top two answers, it doesn't worked for me until I removed "display:none" from my file input elements.
Then I reverted back to .trigger() it also worked at safari for windows.
So conclusion, Don't use display:none; to hide your file input , you may use opacity:0 instead.
Just use this:
$(function() {
$('#watchButton').trigger('click');
});
You can't simulate a click event with javascript.
jQuery .trigger() function only fires an event named "click" on the element, which you can capture with .on() jQuery method.

Javascript onclick function trouble

I'm using a popover in bootstrap, and I want it to close when the user clicks anywhere else on the screen. The code I have is this:
$('#popover').bind('click', function() {
$(".popover").live('click', function(){ return false; });
$(document).one("click", function() {
alert('click');
});
});
The problem is that the click on the button is triggering the alert. For some reason javascript uses that click to start the function and trigger the click event inside of it. What am I doing wrong?
EDITED:
This code doesn't do anything:
$(".popover").live('clickoutside', function(){
alert('click');
});
Check out these:
https://developer.mozilla.org/en-US/docs/DOM/event.stopPropagation
https://developer.mozilla.org/en-US/docs/DOM/event.stopImmediatePropagation
If your .popover is inside #popover, you're triggering events from all the affected elements.
NOTE: jQuery's live is in deprecating process, use the alternatives:
http://api.jquery.com/on/
http://api.jquery.com/delegate/

jQuery: Can't cache onclick handler?

I've got a step-by-step wizard kind of flow where after each step the information that the user entered for that step collapses down into a brief summary view, and a "Go back" link appears next to it, allowing the user to jump back to that step in the flow if they decide they want to change something.
The problem is, I don't want the "Go Back" links to be clickable while the wizard is animating. To accomplish this I am using a trick that I have used many times before; caching the onclick handler to a different property when I want it to be disabled, and then restoring it when I want it to become clickable again. This is the first time I have tried doing this with jQuery, and for some reason it is not working. My disabling code is:
jQuery.each($("a.goBackLink"), function() {
this._oldOnclick = this.onclick;
this.onclick = function() {alert("disabled!!!");};
$(this).css("color", "lightGray ! important");
});
...and my enabling code is:
jQuery.each($("a.goBackLink"), function() {
this.onclick = this._oldOnclick;
$(this).css("color", "#0000CC ! important");
});
I'm not sure why it's not working (these are good, old-fashioned onclick handlers defined using the onclick attribute on the corresponding link tags). After disabling the links I always get the "disabled!!!" message when clicking them, even after I run the code that should re-enable them. Any ideas?
One other minor issue with this code is that the css() call to change the link color also doesn't appear to be working.
I wouldn't bother swapping around your click handlers. Instead, try adding a conditional check inside of the click handler to see if some target element is currently animating.
if ($('#someElement:animated').length == 0)
{
// nothing is animating, go ahead and do stuff
}
You could probably make this a bit more concise but it should give you an idea... Havent tested it so watch your console for typeos :-)
function initBack(sel){
var s = sel||'a.goBackLink';
jQuery(s).each(function(){
var click = function(e){
// implementation for click
}
$(this).data('handler.click', click);
});
}
function enableBack(sel){
var s = sel||'a.goBackLink';
jQuery(this).each(function(){
var $this = jQuery(this);
if(typeof $this.data('handler.click') == 'function'){
$this.bind('goBack.click', $this.data('handler.click'));
$this.css("color", "lightGray ! important");
}
});
}
function disableBack(sel){
var s = sel||'a.goBackLink';
jQuery(s).each(function(){
var $this = jQuery(this);
$this.unbind('goBack.click');
$this.css("color", "#0000CC ! important");
});
}
jQuery(document).ready(function(){
initBack();
jQuery('#triggerElement').click(function(){
disableBack();
jQuery('#animatedElement').animate({/* ... */ }, function(){
enableBack();
});
});
});

Categories