How to disable a function in javascript onclick - javascript

I added a redirect function when refresh button or user try to exit the page they get redirected but what I want to happen is this function to be unload or not executed when they click my button
<a onClick="alert(you are going to tweeter);"href="http://twitter.com" class="tweetbutton" >I Like Twitter</a>
so what happens is it conflicts and two alerts shows up, what I was needing is when the tweetbutton button is click the onclick alert will the one to appear then get redirected to twitter.com without the function below being executed
(function() {
setTimeout(function() {
var __redirect_to = 'http://facebook.com';
var _tags = ['btn', 'input'],
_go, _i, _i2;
for (_i in _tags) {
_els = document.getElementsByTagName(_tags[_i]);
for (_i2 in _go) {
if ((_tags[_i] == 'input' && _go[_i2].type != 'btn' && _go[_i2].type != 'submit' && _go[_i2].type != 'image') || _go[_i2].target == '_blank') continue;
_els[_i2].onclick = function() {
window.onbeforeunload = function() {};
}
}
}
window.onbeforeunload = function() {
setTimeout(function() {
window.onbeforeunload = function() {};
setTimeout(function() {
document.location.href = __redirect_to;
});
});
return 'you are leaving this page'
}
});
});

Update you code as follows:
<a "href="http://twitter.com" class="tweetbutton" >I Like Twitter</a>
Add this to your js
document.addEventListener('click', function (e) {
if (e.target.className == 'tweetbutton') alert('you are going to twitter');
});

Related

How do I add a second function to a button?

Say I have a standard HTML link like so:
<a href='https://whateverdomain.com/whatever.pdf' class='pdf-download'>
How can I both link to that .pdf and fire a jQuery function at the same time?
I've written this so far:
$('.pdf-download').addEventListener('click', function() {
$.getJSON('/documents/email', function(email) {
if (email.documentID && email.message == 'success') {
console.log('Sending email...');
};
},
false);
But that just prevents my button from being clickable. I should mention that that listener is part of a bigger function:
function checkForAnswers() {
var count = $('.pdf-checklist').filter(function() {
return $(this).val() !== "";
}).length;
var total = $('.pdf-checklist').length;
$('.pdf-download').addEventListener('click', function() {
$.getJSON('/documents/email_press_ad', function(email) {
if (email.documentID && email.message == 'success') {
console.log('Sending email...');
};
}, false);
if (count == total) {
$('.pdf-download').removeClass('disabled');
$('.pdf-download').removeAttr('disabled');
} else {
$('.pdf-download').addClass('disabled');
$('.pdf-download').attr('disabled', 'disabled');
}
console.log(count + '/' + total);
}
$('.pdf-checklist').on('keyup', checkForAnswers);
You could try just binding it with on
$(".pdf-download").on("click", function (e) {
e.preventDefault();
//do your stuff.
//navigate to a click href via window.location
window.location = $(this).attr('href');
});
So you cancel the click default event and manually force the url change after code is complete.
Editted according to comments.

window.onbeforeunload only works after i refresh the page

note: i see this Question but the problem is not the same.
I have one page named login_check.cfm and this page do a location.href to home.cfm
inside the home.cfm i have this code
<script>
window.onbeforeunload = function() { window.history.go(0); };
</script>
or
<script>
window.onbeforeunload = function() { window.history.forward(1); };
</script>
my intention is to prohibit the User to use the back button, and its work, but only a do a refresh or use a link to do refresh.
the problem is my page is 90% ajax based and the most off the user go back to login page when they clicked backbutton.
use Document ready() make no difference.
suggestions ?
i found this old Question where rohit416 give a good answer and it still works
(function ($, global) {
var _hash = "!",
noBackPlease = function () {
global.location.href += "#";
setTimeout(function () {
global.location.href += "!";
}, 50);
};
global.setInterval(function () {
if (global.location.hash != _hash) {
global.location.hash = _hash;
}
}, 100);
global.onload = function () {
noBackPlease();
// disables backspace on page except on input fields and textarea.
$(document.body).keydown(function (e) {
var elm = e.target.nodeName.toLowerCase();
if (e.which == 8 && elm !== 'input' && elm !== 'textarea') {
e.preventDefault();
}
// stopping event bubbling up the DOM tree..
e.stopPropagation();
});
}
})(jQuery, window);

Jquery: <a> link click preventDefault() not working?

I'm trying to prevent a link click from firing if accidentally touched while scrolling in mobile? I have never tried something like this before and am having trouble getting it to work right. I am testing this on a desktop for the time being.
My buttons are structured similar to:
<a href="http://www.google.com">
<div style="width:100%;height:80px;margin-bottom:50px;">test</div>
</a>
I am trying to use the preventDefault() function to override default click actions and check if a the page is being scrolled, or it the click was accidental before allowing it to work. The logic to check seems to work, however the links navigate on click no matter what i do. I assume this has something to do with the links behaviour being propogated to the child div, but am not sure.
Below is my script, the problem is in the last $('a').click(); function.
UPDATE:
I still need a better way to do it using just the $('a') selector if anyone knows how. Kind of a hack but, if i change the selector to $('a>div') and change the 'targetLink' to $(this).parent().attr('href') it seems to work, Is there a way to do this using $('a') only because some of my buttons have more children.
//Mobile accidental scroll click fix:---
//- prevent clicked link from executing if user scrolls after mousedown, until next mousedown.
//- prevent clicked link from executing if user is still scrolling and mouse is down(for slow scrolls)
$(document).ready(function(){
var self = this,
scrolling = false,
mouseDown = false,
scrollAfterPress = false;
scrollDelay = 1500,
linkConditionCheckDelay = 700;
$(window).scroll(function() {
self.scrolling = true;
console.log('scrolling:' + self.scrolling);
clearTimeout( $.data( this, "scrollCheck" ) );
$.data( this, "scrollCheck", setTimeout(function() {
self.scrolling = false;
console.log('scrolling:' + self.scrolling);
}, scrollDelay) );
});
$(document).mousedown(function(){
self.scrollAfterPress = false;
int00 = setInterval(function() { checkScrollAfterPress(); }, 100);//execute every 100ms (while mouse is down)
self.mouseDown = true;
console.log('mousedown:'+ self.mouseDown);
}).mouseup(function(){
clearInterval(int00);
self.mouseDown = false;
console.log('mousedown:'+ self.mouseDown);
});
function checkScrollAfterPress(){
if(self.scroll === true){
self.scrollAfterPress = true;
}
}
$('a').click(function(e){
//prevent default click event behaviour
var targetLink = $(this).attr('href');
console.log('clicked on:'+targetLink);
setTimeout(function() {
if(!self.scrolling && !self.mouseDown && !self.scrollAfterPress && targetLink !== undefined){
window.location.href = targetLink;
}
}, linkConditionCheckDelay); //add small delay to prevent immeditiate responses between mouse up and start of scroll.
e.stopPropagation();
e.preventDefault();
});
});
You can use return false or e.preventDefault
But when you click on that link why your adding window.location.href = targetLink;?? which will redirect the user to the given location.Same as link
Try my code below i have removed it.
$(document).ready(function(){
var self = this,
scrolling = false,
mouseDown = false,
scrollAfterPress = false;
scrollDelay = 1500,
linkConditionCheckDelay = 700;
$(window).scroll(function() {
self.scrolling = true;
console.log('scrolling:' + self.scrolling);
clearTimeout( $.data( this, "scrollCheck" ) );
$.data( this, "scrollCheck", setTimeout(function() {
self.scrolling = false;
console.log('scrolling:' + self.scrolling);
}, scrollDelay) );
});
$(document).mousedown(function(){
self.scrollAfterPress = false;
int00 = setInterval(function() { checkScrollAfterPress(); }, 100);//execute every 100ms (while mouse is down)
self.mouseDown = true;
console.log('mousedown:'+ self.mouseDown);
}).mouseup(function(){
clearInterval(int00);
self.mouseDown = false;
console.log('mousedown:'+ self.mouseDown);
});
function checkScrollAfterPress(){
if(self.scroll === true){
self.scrollAfterPress = true;
}
}
$('a').click(function(e){
//prevent default click event behaviour
var targetLink = $(this).attr('href');
console.log('clicked on:'+targetLink);
setTimeout(function() {
if(!self.scrolling && !self.mouseDown && !self.scrollAfterPress && targetLink !== undefined){
//window.location.href = targetLink;
}
}, linkConditionCheckDelay); //add small delay to prevent immeditiate responses between mouse up and start of scroll.
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="http://www.google.com">
<div style="width:100%;height:80px;margin-bottom:50px;">test</div>
</a>
I will suggest another approach and use jQuery Mobile Events. Something like this:
*untested, but is the idea
// set global var 'locked'
var locked = false;
// locked var true while scrolling
jQuery(document).on('scrollstart', function() { locked = true; });
// locked var back to false when finish
jQuery(document).on('scrollstop', function() { locked = false; });
// bind 'tap' & 'click' events to 'a' tag
jQuery(document).on('tap click', 'a', function(event) {
// But before proceed, check locked var
if (locked) {
event.preventDefault;
return false;
} else {
// ok, proceed with the click and further events...
}
});
Docs/ref:
scrollstart event
scrollstop event
tap event
vclick event
.click()
Use in your $'a'.click(function(e){...} part return false; to prevent the default behavior.
In your case:
$('a').click(function(e){
var targetLink = $(this).attr('href');
console.log('clicked on:'+targetLink);
setTimeout(function() {
if(!self.scrolling && !self.mouseDown && !self.scrollAfterPress && targetLink !== undefined){
window.location.href = targetLink;
}
}, linkConditionCheckDelay);
return false;//Stops default behavior
});
Perhaps there is something I am missing, but I do not see why your code cannot be made as simple as the following:
$(document).ready(function () {
var is_scrolling = false;
var timeout = null;
$(window).scroll(function () {
is_scrolling = true;
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(function () {
is_scrolling = false;
}, 1500);
});
$('a').click(function (e){
if (is_scrolling) {
e.preventDefault();
}
});
});

How to cancel single click event when double click event uses

I am using asp .net mvc 4. My problem is in my modal popup I am using mouse double click. It works properly, but if I cancel particular popup form and then single click on details, again it will displays. The main problem is that single works as the double click. I need some time delay between these clicks. I only need to display modal popup with double click. If I submit the details may be of page refreshing it get works. Below shown is modal.js that I make changes.(only change click to dblclick)
Modal.prototype.show = function (_relatedTarget) {
var that = this
var e = $.Event('show.bs.modal', { relatedTarget: _relatedTarget })
this.$element.trigger(e)
if (this.isShown || e.isDefaultPrevented()) return
this.isShown = true
this.escape()
**this.$element.on('click.dismiss.modal', '[data-dismiss="modal"]',** $.proxy(this.hide, this))
Modal.prototype.hide = function (e) {
if (e) e.preventDefault()
e = $.Event('hide.bs.modal')
this.$element.trigger(e)
if (!this.isShown || e.isDefaultPrevented()) return
this.isShown = false
this.escape()
$(document).off('focusin.bs.modal')
this.$element
.removeClass('in')
.attr('aria-hidden', true)
.off('click.dismiss.modal')
$.support.transition && this.$element.hasClass('fade') ?
this.$element
.one($.support.transition.end, $.proxy(this.hideModal, this))
.emulateTransitionEnd(300) :
this.hideModal()
}
this.$element.on('click.dismiss.modal', $.proxy(function (e) {
if (e.target !== e.currentTarget) return
this.options.backdrop == 'static'
? this.$element[0].focus.call(this.$element[0])
: this.hide.call(this)
}, this))
$(document).on('dblclick.bs.modal.data-api', '[data-toggle="modal"]', function (e) {
//alert("onclick");
var $this = $(this)
var href = $this.attr('href')
var $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) //strip for ie7
var option = $target.data('modal') ? 'toggle' : $.extend({ remote: !/#/.test(href) && href }, $target.data(), $this.data())
e.preventDefault()
$target
.modal(option, this)
.one('hide', function () {
$this.is(':visible') && $this.focus()
})
})
in my candidate.js
$('body').on('dblclick', '.IndMaster-edit', function (e) {
//alert("succ111");
e.preventDefault();
//alert($(this).attr('class'));
$(this).attr('data-target', '#modal-container');
$(this).attr('data-toggle', 'modal');
});
$(".IndMaster-edit").dblclick(function () {
//alert("first");
var sectionvalue = $(this).attr("data-id");
var titleselection = $(this).attr("title");
//alert(titleselection);
//alert(sectionvalue.toString());
$.ajax({
async:false,
// Call CreatePartialView action method
url: "/IndMaster/EditIndPartial",
data: { section: sectionvalue, indmanid: titleselection },
type: 'Get',
success: function (data) {
//alert("hhiii");
//$('#myModal').modal('show');
$("#IndMaster-DetailModel").empty();
//alert("end1");
//alert("success11");
$("#IndMaster-DetailModel").append(data);
//alert("end2");
//alert("success22");
$("#IndMaster-DetailModel").dialog("open");
//$("#createForm").hide();
//alert("end3");
//alert("success");
},
error: function () {
alert("something seems wrong");
}
});
});
In my IndMaster.cshtml
<td class="tagstd IndMaster-edit" data-id="status" title="#item.Ind_ID">
<span class="btn btn-xs icon-tag pull-left tag-btn" data-id="Package_No" title="#item.Ind_ID" style="visibility:hidden"></span> #item.IND_APP_PASS_STATUS.First().Package_No</td>
I changed click function to dblclick.
I created a jsfiddle for this, please check, using this you have to use a delay so that you can count the number of clicks
var DELAY = 700, clicks = 0, timer = null;
$(function(){
$("a").on("click", function(e){
clicks++; //count clicks
if(clicks === 1) {
timer = setTimeout(function() {
alert("Single Click"); //perform single-click action
clicks = 0; //after action performed, reset counter
}, DELAY);
} else {
clearTimeout(timer); //prevent single-click action
alert("Double Click"); //perform double-click action
clicks = 0; //after action performed, reset counter
}
})
.on("dblclick", function(e){
e.preventDefault(); //cancel system double-click event
});
});
http://jsfiddle.net/y7epojfo/

how to detect if a link was clicked when window.onbeforeunload is triggered?

I have window.onbeforeunload triggering properly. It's displaying a confirmation box to ensure the user knows they are navigating (closing) the window and that any unsaved work will be erased.
I have a unique situation where I don't want this to trigger if a user navigates away from the page by clicking a link, but I can't figure out how to detect if a link has been clicked inside the function to halt the function. This is what I have for code:
window.onbeforeunload = function() {
var message = 'You are leaving the page.';
/* If this is Firefox */
if(/Firefox[\/\s](\d+)/.test(navigator.userAgent) && new Number(RegExp.$1) >= 4) {
if(confirm(message)) {
history.go();
}
else {
window.setTimeout(function() {
window.stop();
}, 1);
}
}
/* Everything else */
else {
return message;
}
}
You're looking for deferred event handling. I'll explain using jQuery, as it is less code:
window._link_was_clicked = false;
window.onbeforeunload = function(event) {
if (window._link_was_clicked) {
return; // abort beforeunload
}
// your event handling
};
jQuery(document).on('click', 'a', function(event) {
window._link_was_clicked = true;
});
a (very) poor man's implementation without jQuery's convenient delegation handling could look like:
document.addEventListener("click", function(event) {
if (this.nodeName.toLowerCase() === 'a') {
window._link_was_clicked = true;
}
}, true);
this allows all links on your page to leave without invoking the beforeunload handler. I'm sure you can figure out how to customize this, should you only want to allow this for a specific set of links (your question wasn't particularly clear on that).
var link_was_clicked = false;
document.addEventListener("click", function(e) {
if (e.target.nodeName.toLowerCase() === 'a') {
link_was_clicked = true;
}
}, true);
window.onbeforeunload = function() {
if(link_was_clicked) {
link_was_clicked = false;
return;
}
//other code here
}
You can differ between a link unload or a reload/user entering a different address unload s by using a timer. This way you know the beforeunload was triggered directly after the link click.
Example using jQuery:
$('a').on('click', function(){
window.last_clicked_time = new Date().getTime();
window.last_clicked = $(this);
});
$(window).bind('beforeunload', function() {
var time_now = new Date().getTime();
var link_clicked = window.last_clicked != undefined;
var within_click_offset = (time_now - window.last_clicked_time) < 100;
if (link_clicked && within_click_offset) {
return 'You clicked a link to '+window.last_clicked[0].href+'!';
} else {
return 'You are leaving or reloading the page!';
}
});
(tested in Chrome)

Categories