Jquery Animation on click, stop it repeating on multiple clicks - javascript

I've got code like this:
$("#ajax_stuff").load("/site/method", $('.myselector').serializeArray()).delay(100).fadeOut('slow').delay(20).fadeIn('slow');
And basically, that is triggered each time someone clicks a checkbox in a list of checkboxes. What happens is if someone quickly clicks 20 checkboxes in a row, the effect repeats 20 times.
Ideally i just want it to do one effect for the last box they clicked and then stop.
I've tried
$("#ajax_stuff").load("/site/method", $('.myselector').serializeArray()).stop(true,true).delay(100).fadeOut('slow').delay(20).fadeIn('slow');
But that doesn't seem to do anything. Any advice would be very gratefully received!

var delay = (function () {
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
$(function(){
$("/*CHECKBOX SELECTOR*/").on("click",function(){
delay((function(){
$("#ajax_stuff").load("/site/method", $('.myselector').serializeArray()).stop(true,true).delay(100).fadeOut('slow').delay(20).fadeIn('slow');}),1000);
});
});
setTimeout is your friend in this case, I think. I haven't used it on checkbox clicks, but you might have to changed the event handler from click to select or something. I tried to put it in jsfiddle just now, but it's crashed maybe? Not loading regardless.

Related

alert() function is looping when called in focus() event

I Want an Alert pop-up when focusing on input. It pops up correctly but when I click on 'OK' or 'x' i.e cancel, it Loops infinitely and never closes.
$('input').focus(function () {
alert('hello');
});
This is because the input is assuming the focus again when the alert is closed (which is the new focus when it appears - notice the outline around the button in the dialogue?)
If you only want to make the alert show once, you could perhaps write something a resembling this:
let hasShownAlert = false
$('input').focus(function () {
if (!hasShownAlert) {
hasShownAlert = true
alert('hello')
}
})
Of course you could improve this with state containers or something, but this is the simplest way you could achieve it. (Note: the hasShownAlert variable has to be defined outside of the onfocus handler, otherwise it'll be cleared up by the garbage collector.)
Updated: So if you don't want it to only show once, there are a couple of things you could do. The first, the simpler, would be listening for the click event, rather than focus. The second way could be setting a didShowAlert variable -- inverting the value each time the handler is fired. E.g...
let didShowAlert = false
$('input').on('focus', (ev) => {
if (didShowAlert) {
didShowAlert = false
} else {
didShowAlert = true
alert('hello')
}
})
You could try a hack like
$(document).on("focus", 'input:not(.unFocus)', function() {
alert('hello');
$('input').addClass('unFocus');
setTimeout(function() {
$('input').removeClass('unFocus');
}, 10);
});
It may not be the ideal way to do it, but it works :)

Trigger mouse click on a button each 5 seconds

How to trigger a mouse click on the element (slider "next" button) each X seconds?
I have built a website in Adobe Muse, but the slider widget doesn’t have an auto play function, and I’m trying to make the next button click each 5 seconds to simulate autoplay. I’ve found the class for the button
<div class="fp-controlArrow fp-next"></div>
maybe there is even a chance to trigger clicking it somehow? Thanks
I had to specify both classes to trigger the button and use a bit more difficult command. This worked:
var interval = setInterval(function() {
document.querySelector('.fp-controlArrow.fp-next').click();
}, 5000);
Now I have additional question: is it possible to stop clicking after user will click either back or next button with a mouse?
As a half-measure I’ve set it to stop at about a time it returns to the first slide but it would be much better to stop it after user clicks any of the button...
var interval = setInterval(function() {
document.querySelector('.fp-controlArrow.fp-next').click();
}, 7000);
setTimeout(function( ) { clearInterval( interval ); }, 44000);
Thanks
Use setInterval():
setInterval(() => {
element.click()
}, 5000)
where element is a reference to your DOM element.
you can store your interval on a variable and stop it whenever you want
var interval = setInterval(function() {
button.click();
// [button] here is the element you found with the specified class
// if you're using jQuery
// you can get you button and trigger the event
// beware of other buttons using the same class
jQuery(".fp-next").trigger("click");
}, 5000);
//if you want to stop it
clearInterval(interval);

Having issues with session timeout

Need your valuable feedback on this. I have implemented idletimeout functionalty so that session will expire in 3 minutes if the user is idle.
In three scenario, I am resetting the timer.
On click or tap
after 2 seconds while processing is in progress
on scroll or scrollstart
The problem is sometimes session is getting timeout before the 3 minutes even if I tap, click or scroll and user is redirected to login page even if the function is gets called on tap click or scroll and resettimers is getting called. I am facing a bit hard time to figure out the loophole.
I am posting the code; please let me know if you notice anything.
// Set timeout variables.
var timoutNow = 180000 ;
var ua = navigator.userAgent;
var event = ((ua.match(/iPad/i)) || (ua.match(/iPhone/i)) || (ua.match(/iPod/i))) ? 'touchstart' : 'click';
var logoutUrl = Mobile+'/login.html'; // URL to logout page.
var timeoutTimer;
// Start timers.
function StartTimers() {
timeoutTimer = setTimeout("IdleTimeout()", timoutNow);
//console.log(timoutNow);
}
// Reset timers.
function ResetTimers() {
clearTimeout(timeoutTimer);
StartTimers();
}
// Processing time check.
function Laodtimercheck()
{
setInterval(function(){
if($("body").hasClass("loading-processing")==true)
{
ResetTimers();
}
}, 2000);
}
// Logout the user.
function IdleTimeout() {
sessionStorage.clear();
document.location.href = Mobile+'/login.html';
}
$(document).live(event, function(){
//console.log("Reset timers: ON TAP OR CLICK");
ResetTimers();
});
$(document).mouseover(function() {
//console.log("Reset timers: ONMOUSEOVER");
ResetTimers();
});
$(window).scroll(function() {
//console.log("Reset timers: SCROLL");
ResetTimers();
});
$(document).live("scrollstart", function(){
//console.log("Reset timers: SCROLLSTART");
ResetTimers();
});
EDIT: setTimeout only working first two times; next time ResetTimers are getting invoked but the setTimeout is not working or I might be missing something here as the session is getting timed out as per pervious two call time only....
The real problem that you're having is the folowing: "ResetTimers" not being invoke enough.
Why is not being invoked enough? I'll try to answer that.
All the logic is Ok with a few exceptions. There are two "problematic" events that not work or I think don't work like you want.
1.- LIVE (event)
That event is not being fired never. You cannot attach a live event to a document, yo need to specify a node, like html or body.
$("body").live(event, function(){
//console.log("Reset timers: ON TAP OR CLICK");
ResetTimers();
});
That's why when clicked the timer don't reset.
Another (and recomended) way to use a variable for binding events is to use .delegate().
Since jQuery 1.4.3+ is the recomended way of doing this.
$(document).delegate("body", event, function(){
//console.log("Reset timers: ON TAP OR CLICK (delegate)");
ResetTimers();
});
Any of those (live on body or delegate) would work and timer get reset on click or tap event.
2.- MOUSEOVER
There isn't a problem per se with this event, but I think it would be insuficient. MouseOver only fires where the pointer get on screen first time, if the mouse don't leave the window the mouseover never fires again. Maybe, a better or added way of control "mouse hovering" on the document is to use onmousemove event. Like I said in a comment before, I don't know if you want to be strict on this, so I left you a proposal and let's see if it fits your needs.
$(document).mouseover(function() {
console.log("Reset timers: ONMOUSEOVER");
ResetTimers();
});
In my tests, events get fires a lot, and the timers get reset on each event without problems. I hope it helps you.

How to show an alert message when no form field is used in 30 minutes using javascript/jquery?

I have a form with couple of input fields and i want a script that will show a pop up message IF no field is used after a certain time-frame, asking "Are you still there?" or something like that.
Is it possible? Please advice, thanks!
You'll want to start a timer for thirty minutes and attach a change event to all of your fields. On change, you want to erase the current timer, and create a new one for another 30 minutes.
For example, it would be something like this:
$('input[type=text]').bind('change', function (e) {
// .. Triggered every time a form text field is changed
// .. Do stuff here
});
And for the timer, you'd just use settimeout
Here is full sample in JsFiddle:
http://jsfiddle.net/Zsjtn/
What I recommend is using setTimeOut to call a method that you want to display a message or do whatever action you wanted to do. Then on change event on all your input types try to reset the TimeOut. Here is JS Code that simulates this scenario:
// Timer for 3 seconds to call formTimeOut function
var _timer = setTimeout("formTimeOut()",3000);
$(function(){
// Monitor Value change of Inputs in your HTML
$("input").change(function(){
// Clear previous timer
clearTimeout(_timer);
// Reset the timer to re-run after 3 seconds.
_timer = setTimeout("formTimeOut()",3000);
});
});
// This is the function that will run after time out
function formTimeOut(){
// Timeout Logic goes here
alert("Are you there?");
}
You can change $("input") to any criteria that may fit your project.

Execute button event handler the entire time mouse button is depressed

I'd like to create a javascript mousedown event handler for a button. While the button is depressed, I need the handler to execute repeatedly until the button is released (mouseup is fired). E.g. holding an Up button should cause a text box value to increment until it is released.
What's the best way to handle this?
You can make use of setInterval: http://jsfiddle.net/5wypC/1/.
var interval = null;
var i = 0;
$('button').mousedown(function() {
clearInterval(interval); // Make sure to clear any intervals
// that are occasionally still running
interval = setInterval(function() {
$('textarea').val(i++);
}, 100);
});
$('button').mouseup(function() {
clearInterval(interval);
});

Categories