I am trying to delay the default event or events in a jQuery script. The context is that I want to display a message to users when they perform certain actions (click primarily) for a few seconds before the default action fires.
Pseudo-code:
- User clicks link/button/element
- User gets a popup message stating 'You are leaving site'
- Message remains on screen for X milliseconds
- Default action (can be other than href link too) fires
So far, my attempts look like this:
$(document).ready(function() {
var orgE = $("a").click();
$("a").click(function(event) {
var orgEvent = event;
event.preventDefault();
// Do stuff
doStuff(this);
setTimeout(function() {
// Hide message
hideMessage();
$(this).trigger(orgEvent);
}, 1000);
});
});
Of course, this doesn't work as expected, but may show what I'm trying to do.
I am unable to use plugins as ths is a hosted environment with no online access.
Any ideas?
I would probably do something like this.
$("a").click(function(event) {
event.preventDefault();
doStuff(this);
var url = $(this).attr("href");
setTimeout(function() {
hideMessage();
window.location = url;
}, 1000);
});
I'm not sure if url can be seen from inside the timed function. If not, you may need to declare it outside the click handler.
Edit: If you need to trigger the event from the timed function, you could use something similar to what karim79 suggested, although I'd make a few changes.
$(document).ready(function() {
var slept = false;
$("a").click(function(event) {
if(!slept) {
event.preventDefault();
doStuff(this);
var $element = $(this);
// allows us to access this object from inside the function
setTimeout(function() {
hideMessage();
slept = true;
$element.click(); //triggers the click event with slept = true
}, 1000);
// if we triggered the click event here, it would loop through
// this function recursively until slept was false. we don't want that.
} else {
slept = false; //re-initialize
}
});
});
Edit: After some testing and research, I'm not sure that it's actually possible to trigger the original click event of an <a> element. It appears to be possible for any element other than <a>.
Something like this should do the trick. Add a new class (presumably with a more sensible name than the one I've chosen) to all the links you want to be affected. Remove that class when you've shown your popup, so when you call .click() again your code will no longer run, and the default behavior will occur.
$("a").addClass("fancy-schmancy-popup-thing-not-yet-shown").click(function() {
if ($(this).hasClass("fancy-schmancy-popup-thing-not-yet-shown"))
return true;
doStuff();
$(this).removeClass("fancy-schmancy-popup-thing-not-yet-shown");
var link = this;
setTimeout(function() {
hideMessage();
$(link).click().addClass("fancy-schmancy-popup-thing-not-yet-shown";
}, 1000);
return false;
});
Probably the best way to do this is to use unbind. Something like:
$(document).ready(function() {
$("a").click(function(event) {
event.preventDefault();
// Do stuff
this.unbind(event).click();
});
})
This might work:
$(document).ready(function() {
$("a").click(function(event) {
event.preventDefault();
doStuff(this);
setTimeout(function() {
hideMessage();
$(this).click();
}, 1000);
});
});
Note: totally untested
Related
I am using MVC Razor - The overall goal is to create a "print view" pop-up page.
The print view button is on the parent page, when clicked, an ajax event is fired which will populate an empty div with the contents that are to be included in the print preview:
//from the view
#Ajax.ActionLink("prntPreview", "Display", new { ID = Model.Detail.ID }, new AjaxOptions { UpdateTargetId = "modal" }, new { #class = "btnPreview" })
then, using JavasScript/jQuery I clone the contents of that newly populated div and create a new window with the contents:
//in the scripts file
$('.btnPreview').on('click', function () {
$(document).ajaxStop(function () {
var pageData = $('#modal').html();
setTimeout( //add a slight delay
function () {
PopupPrint(pageData);
}, 300);
});
});
function PopupPrint(data) {
var mywindow = window.open('', '', 'height=500,width=800,resizable,scrollbars');
mywindow.document.write(data);
mywindow.focus();
//do some other stuff here
}
This is where I run into difficulty. The first time I click, everything is working as expected - however, if you do not navigate away from the parent page and try to use the print preview button a second time, the popup will be created twice, then three times etc. with each additional click.
I think that the problem is because each time the .btnPreview is clicked, a new $(document).ajaxStop event is being created, causing the event to fire multiple times.
I have tried to create the ajaxStop as a named function which is declared outside the scope of the click event and then clear it but this produces the same result:
var evnt = "";
$('.btnPreview').on('click', function () {
evnt =
$(document).ajaxStop(function () {
var pageData = $('#modal').html();
setTimeout( //add a slight delay
function () {
PopupPrint(pageData);
evnt = "";
}, 300);
});
});
I also have other ajaxStop events initialised so don't want to completely unbind the ajaxStop event. Is it possible to get the name or something from each ajax event so that I can clear just that event or similar?
You can prevent adding additional triggers by checking with a variable outside of scope like this:
(function() {
var alreadyAdded = false;
$('.btnPreview').on('click', function() {
if (!alreadyAdded) {
$('.eventTrigger').click(function() {
console.log('printing!');
});
alreadyAdded = true;
}
});
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="btnPreview">Add Event</button>
<button class="eventTrigger">Trigger</button>
Please note that the variable and function are encapsulated in a self-executing anonymous function and do not pollute global space.
The output of the sample can be seen in the developer console. If you remove the if-check then every click on the "Add Event" button produces an additional print statement on the "Trigger" button each time it is clicked (which is your problem). With the if, there will ever only be one event on the trigger button.
There were 2 issues which I needed to address.
The answer is to unbind the ajax event after it has checked that the request had completed and to unbind and reattach the button click trigger.
This is how I did it:
//in the scripts file
$('.btnPreview').off('click').on('click', function () {
$(document).ajaxComplete(function (e) {
var pageData = $('#modal').html();
setTimeout( //add a slight delay
function () {
PopupPrint(pageData);
}, 300);
$(this).off(e);
});
});
I unbound the click event by adding .off('click') before the .on. this is what stopped it popping up multiple times.
The other issue was that anytime any ajax event completed (triggered by something else) that would also create the popup - to get around that, I added $(this).unbind(e); to the end of the code block which removed the ajaxComplete binding which was being triggered each time any ajax event completed.
Is it possible to make sure jQuery on click event executes before the user is forwarded to the external URL? I have been googling now for 2 hours and read a couple of posts here on stackoverflow. I just cant get this to work.
This is what I've tried:
HTML:
Click me
JS:
$('.external-url').on("click", function (e) {
e.preventDefault();
if (myCustomEvent()) {
window.location = this.href;
}
});
function myCustomEvent()
{
setTimeout(function() {
console.log('Execute some custom JS here before a href firing...');
return true;
}, 3000);
}
But it seems like the line "if (myCustomEvent()) {" is exectuted before myCustomEvent function is able to return true. Is there a better way to do this? And a way that actually works?
The jQuery click event does run before the location changes--but you're doing something async in the middle of the click handler.
The easiest thing to do would be to pass in what you want to have happen into myCustomEvent, roughly:
$('.external-url').on('click', function (e) {
const url = this.href
e.preventDefault()
myCustomEvent(function() {
window.location = url
});
});
function myCustomEvent(fn) {
setTimeout(function() {
console.log('Execute custom JS before firing navigation...');
fn();
}, 3000);
}
There are other ways to handle this depending on your actual requirements.
I'm somewhat new to Javascript. I'm trying to make it so that clicking on an image on one page takes you to a new page and shows a specific div on that new page, so I used sessionStorage to remember and booleans to keep track of which image is being clicked. Right now, the code always executes the first if statement, regardless of which image is clicked. This code works fine in normal java so I can't figure out why my if statements are being ignored in javascript. I also tried adding an 'else' at the end, and tried ===. Here's my javscript, and thank you!
sessionStorage.clickedLeft;
sessionStorage.clickedMiddle;
sessionStorage.clickedRight;
function openedProjectFromGallery() {
if(sessionStorage.clickedLeft) {
$(".left-project-pop-up").show();
} else if (sessionStorage.clickedMiddle) {
$(".middle-project-pop-up").show();
} else if (sessionStorage.clickedRight) {
$(".right-project-pop-up").show();
}
sessionStorage.clickedLeft = false;
sessionStorage.clickedMiddle = false;
sessionStorage.clickedRight = false;
}
$("document").ready(function () {
$(".pop-up .x-button").click(function(){
$(".pop-up").hide();
});
$(".project-description .x-button").click(function(){
$(".project-pop-up").hide();
});
$(".left-project-thumb img").on("click", ".left-project-thumb img", function(){
sessionStorage.clickedLeft = true;
sessionStorage.clickedMiddle = false;
sessionStorage.clickedRight = false;
openedProjectFromGallery();
});
$(".profile-left-project img").click(function(){
$(".left-project-pop-up").show(1000);
});
$(".middle-project-thumb img").on("click", ".middle-project-thumb img", (function(){
sessionStorage.clickedMiddle = true;
sessionStorage.clickedLeft = false;
sessionStorage.clickedRight = false;
openedProjectFromGallery();
});
$(".profile-middle-project img").click(function(){
$(".middle-project-pop-up").show(1000);
});
$(".right-project-thumb img").on("click", ".right-project-thumb img", (function(){
sessionStorage.clickedRight = true;
sessionStorage.clickedLeft = false;
sessionStorage.clickedMiddle = false;
openedProjectFromGallery();
});
$(".profile-right-project img").click(function(){
$(".right-project-pop-up").show(1000);
});
});
You are defining function openedProjectFromGallery() with in document.ready . Define it outside document.ready and also give your three booleans some initial value at the top of your code if not initialized with some value or they are empty. I hope this would help.
It is not really answer to your orginal question,as the main issue with your code is, as #njzk2 says, that openProjectFromGallery only being called once, and not on each event, however I wanted to put my two coins on how this code could look like.
This is good example where custom events should be used
$(document).on('showPopup', function( e, popup ) {
$('.'+popup + '-project-pop-up').show()
})
$(document).on('hidePopup', function( e ) {
$('.popup').hide()
})
$('.left-project-thumb img').on('click', function(e) {
$(document).trigger('showPopup', ['left'])
})
$('.right-project-thumb img').on('click', function(e) {
$(document).trigger('showPopup', ['right'])
})
I think you get an idea.
On the other hand, it always nice to use event delegation with a lot of similar events as well as dom data.
<div class='popup' data-popup='left'>
<img />
</div>
$(document).on('click','.popup', function( e ) {
$(document).trigger('showPopup', [$(this).data('popup')])
})
From what I can see openedProjectFromGallery is only getting called on document load.
Add a call to it into each of the event handling functions or use jQuery's delegate function to assign event handling to each image.
What I want to do is I have a code like below :
$(document).ready(
function(){
var currentPage = window.location.pathname;
$('#main-menu-list').find('a[href^="' + currentPage + '"]').closest('li').addClass('active');
}
)
And now I want to add this code to add and get work with other code. I need to add this code after this one:
function () {
/* If there are forms, make all the submit buttons in the page appear
disabled and prevent them to be submitted again to avoid accidental
double clicking. See Issue 980. */
jQuery(function() {
/* Delegate the function to document so it's likely to be the last event
in the queue because of event bubbling. */
jQuery(document).delegate("form", "submit", function (e) {
var form = jQuery(this);
if (form.hasClass("form_disabled")) {
e.preventDefault();
return false;
}
else {
form
.addClass("form_disabled")
.find(":submit")
.addClass("disabled");
}
// Reactivate the forms and their buttons after 3 secs as a fallback.
setTimeout(function () {
form
.removeClass("form_disabled")
.find(":submit")
.removeClass("disabled");
}, 3000);
});
});
}
How can I get this done. Please help me out to solve this problem.
You can create document.ready() anywhere in script. It is not necessary all of your code should be in ready function.
You can create instance variable for function and call it where you need:
$(document).ready(
var myFunc = function(){
var currentPage = window.location.pathname;
//other code
}
...
//and invoke it where you need
myFunc();
)
First, name the long function in your code section, for example, launchFormControls(). And then define the function outside of the document ready event. A good practice would be to do so and keep the ready event body clean.
For example:
function launchFormControls() {
//function code
}
Or, in other syntax:
var launchFormControls = function() {
//function code
}
Second, call your function from within the document ready event. Your function will be defined and able to call once the document is loaded. This code can be placed at the top or bottom of your javascript section or file.
For example:
$(document).ready(function(){
var currentPage = window.location.pathname;
$('#main-menu-list').find('a[href^="' + currentPage+'"]').closest('li').addClass('active');
launchFormControls();
});
I have a page loading content with the waypoints infinite scroller plugin.
On the success of the AJAX call and after DOM elements are added, a callback runs to re-initilize javascript functionality, like carousels, buttons and other animation.
On the first AJAX call, buttons tasked with toggling work properly. On the next AJAX call, the new DOM items work, but the previous buttons now execute toggles twice when clicked. On the third call, original items now run three times, the second items twice and the new ones once, so on and so fourth, continuing to compound as AJAX content is called.
How can I isolate the callback to not affect the previously loaded content, or, is there a way to set a global state for the JS, so that I don't need the callback each time?
Some pseudo code:
$('.infinite-container').waypoint('infinite', {
onAfterPageLoad: function() {
//Carousel options
$('.carousel-container').carousel({
options: here,
....
});
//Button Toggles
$('.button').click(function(){
var self = $(this);
$(this).siblings('.caption').animate({
height: 'toggle'
}, 200, function() {
// Callback after animate() completes.
if(self.text() == 'Hide Details'){
self.text('Show Details');
} else {
self.text('Hide Details');
}
});
});
}
});
Edit: Thanks everybody. All the answers lead me to differing but appropriate solutions. The selected was picked as it's a great collection of all the suggested issues and worth the read.
Check out this answer. I think it is the same situation you are having and has a solution:
Best way to remove an event handler in jQuery?
You are attaching a new click handler each time that block of code gets executed. The result is multiple click handlers being bound to your button. Use jQuery's unbind: http://api.jquery.com/unbind/ to remove any click handler(s) before adding a new one:
$('.infinite-container').waypoint('infinite', {
onAfterPageLoad: function() {
//Carousel options
$('.carousel-container').carousel({
options: here,
....
});
// Un-bind click handler(s)
$('.button').unbind('click');
//Button Toggles
$('.button').click(function(){
var self = $(this);
$(this).siblings('.caption').animate({
height: 'toggle'
}, 200, function() {
// Callback after animate() completes.
if(self.text() == 'Hide Details'){
self.text('Show Details');
} else {
self.text('Hide Details');
}
});
});
}
});
Try bind only once click event to button. Of course you can use on instead of live.
$('.button').live('click', function(){
var self = $(this);
$(this).siblings('.caption').animate({
height: 'toggle'
}, 200, function() {
// Callback after animate() completes.
if(self.text() == 'Hide Details'){
self.text('Show Details');
} else {
self.text('Hide Details');
}
});
});
$('.infinite-container').waypoint('infinite', {
onAfterPageLoad: function() {
//Carousel options
$('.carousel-container').carousel({
options: here,
....
});
//Button Toggles
}
});
$('.button').click(function(){
You add an event handler to every button that has the class button. When the second button is added then you add it to every ... which means button 1 and button 2. And so on.
Try
$('.button').last().click(function(){