I use the following script (along with external animate.css) which i call when I want to show a specific notification. The idea is simple; when triggered, animate - (slide in down) the notification box, along with changed notification message. When time is out, animate again (slide out up). Everything works fine, except for when i re-trigger notification function right at the time the previous call is animating out (between the timeout and start of slide up animation - see note in code).
// notification
var timer = '';
var notif = $('#notif');
var notif_txt = $('#notif #notif_txt');
var notif_orig = '#notif';
function err_notif(text = 'Prišlo je do napake!') {
clearTimeout(timer);
notif[0].style.display = 'none';
notif_txt.text(text);
notif[0].style.display = 'inline-block';
anim(notif_orig, 'slideInDown', function() {
timer = setTimeout(function(){
// if user re-triggers the notif() function in time between mark 1 and 2, it glitches out the notification system
// mark 1
anim(notif_orig, 'slideOutUp', function(){
// mark 2
notif[0].style.display = 'none';
});
}, 1500);
});
}
Other code resources:
Animate.css for css animations
https://raw.githubusercontent.com/daneden/animate.css/master/animate.css
anim() function (from animate.css's github page)
function anim(element, animationName, callback) {
const node = document.querySelector(element)
node.classList.add('animated', animationName)
function handleAnimationEnd() {
node.classList.remove('animated', animationName)
node.removeEventListener('animationend', handleAnimationEnd)
if (typeof callback === 'function') callback()
}
node.addEventListener('animationend', handleAnimationEnd)
}
If you want to prevent a concurring animation, you can check if the element already has the animated class.
if(document.querySelector(notif_orig).classList.contains("animated")){
console.log("Concurrent animation prevented.")
}else{
anim(notif_orig, 'slideInDown', function() {
//...
}
Related
I have an HTML page that has timeouts. I want to freeze them when you press a button (#pauseButton) and then resume when you press it again, preferably freezing all BS4 and jQuery animations also.
<button id="pauseButton"></button>
<script>
$(document).ready(function(){
setTimeout(function() {
alert("This is an alert")
},10000);
$("#pauseButton").click(function(){
// Pause timeouts and page
});
});
</script>
EDIT
I have been notified that there is a possible duplicate answer, so I am now focusing on pausing animations and other page elements.
That answer shows how to pause timeouts only.
There are many ways to solve this issue. Many of them are mentioned in this question as mentioned by #EmadZamout in the comments.
But, if you are looking for an easy and maybe an alternate way to solve this. Try this. Here I am using requestAnimationFrame to solve the issue
let ran = Date.now(); // contains the last updated time
let time = 0; // time in seconds
let paused = false; // store the state
const func = () => {
if (!paused && Date.now() - ran > 1000) {
time++;
ran = Date.now();
console.log('now')
}
if (time === 8)
return alert('This works!');
requestAnimationFrame(func);
}
func();
document.querySelector('button').addEventListener('click', () => paused = !paused);
<button>Change state</button>
For stopping all the animations of the website, you need to manually stop each animation.
For stopping a jQuery animation, you can use .stop() helper. An example:
let paused = false; // state of the animation
let dir = 'down'; // to store the direction of animation so that the next time continues in the correct direction
let timeDown = 2000; // to animate properly after resuming
let timeUp = 2000; // to animate properly after resuming
// the initial calling of the animation
(function() {
slideDown();
})();
// function which resumes the animation
function animate() {
switch (dir) {
case 'up':
slideUp();
break;
case 'down':
slideDown();
break;
}
}
// a function to animate in the uppward direction
function slideUp() {
dir = 'up'; // setting direction to up
timeDown = 2000; // resetting the duration for slideDown function
$('div').stop().animate({
left: 0
}, {
duration: timeUp,
complete: slideDown, // calling slideDown function on complete
progress: function (animation, progress, ms) {
timeUp = ms; // changing the duration so that it looks smooth when the animation is resumed
}
}); // actual animation
}
// a function to animate in the downward direction
function slideDown() {
dir = 'down'; // setting direction to down
timeUp = 2000; // resetting the duration for slideDown function
$('div').stop().animate({
left: 200
}, {
duration: timeDown,
complete: slideUp, // calling slideUp function on complete
progress: function (animation, progress, ms) {
timeDown = ms; // changing the duration so that it looks smooth when the animation is resumed
}
}); // actual animation
}
// button click event listener
$('button').click(function() {
if (paused)
animate(); // to resume the animation
else
$('div').stop(); // to stop all the animations on the object
paused = !paused; // toggling state
});
div {
position: relative;
width: 100px;
height: 100px;
background: dodgerblue;
}
<button>Pause</button>
<div></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
For bootstrap, I don't think you have any bootstrap animations which needed to be paused in this scenario which you have mentioned since bootstrap animations depend on user interactions. If you want to prevent user interaction, you can put an overlay over the website says "Paused". Or, if you don't want to do that you can use CSS property pointer-events: none to disable all the pointer events.
Now for CSS animations, you can set a property called animation-play-state to paused.
If you want to change the state of the animations to paused when the user is not on the page (As I understood for your updated questions) you can use the new visibilityState API for that. There is an event visibilitychange which is fired when there a change in visibility.
document.addEventListener("visibilitychange", function() {
console.log( document.visibilityState );
document.querySelector('div').innerHTML = document.visibilityState;
});
<div>
Try opening a different tab or change the focus to another app
</div>
I have to do some Special things for my Webpage to work on Android the correct way. Some Images are displayed (one visible, the other unvisible) and through swipe it should be possible to Change them. No Problem so far on all OS.
But it also should be possible to zoom. Now Android starts to be Buggy. It stops the zoom-gesture because of the swipe callback. The callback itself doesn't Change the page because the view is zoomed, so there should be no break.
Now I work arround through turning my swipeleft and swiperight off while two fingers touching the Display, and tourning back on if the fingers leave the Display.
On First run I can swipe, then I can zoom with no break, but then I can't swipe anymore. The function to set the callbacks back on again is called, it set's the callbacks, but they won't be executed...
Here's the code:
app.utils.scroll = (function(){
var $viewport = undefined;
var swipeDisabled = false;
var init = function(){
$viewport = $('#viewport');
$viewport.mousewheel(mayChangePage);
// On touchstart with two fingers, remove the swipe listeners.
$viewport.on('touchstart', function (e) {
if (e.originalEvent.touches.length > 1) {
removeSwipe();
swipeDisabled = true;
}
});
// On touchend, re-define the swipe listeners, if they where removed through two-finger-gesture.
$viewport.on('touchend', function (e) {
if (swipeDisabled === true) {
swipeDisabled = false;
initSwipe();
}
});
initSwipe();
}
var mayChangePage = function(e){
// If page is not zoomed, change page (next or prev).
if (app.utils.zoom.isZoomed() === false) {
if (e.deltaY > 0) {
app.utils.pagination.prev(e);
} else {
app.utils.pagination.next(e);
}
}
// Stop scrolling page through mouse wheel.
e.preventDefault();
e.stopPropagation();
};
var next = function (e) {
// If page is not zoomed, switch to next page.
if (app.utils.zoom.isZoomed() === false) {
app.utils.pagination.next(e);
}
};
var prev = function (e) {
// If page is not zoomed, switch to prev page.
if (app.utils.zoom.isZoomed() === false) {
app.utils.pagination.prev(e);
}
};
var initSwipe = function () {
// Listen to swipeleft / swiperight-Event to change page.
$viewport.on('swipeleft.next', next);
$viewport.on('swiperight.prev', prev);
};
var removeSwipe = function () {
// Remove listen to swipeleft / swiperight-Event for changing page to prevent android-bug.
$viewport.off('swipeleft.next');
$viewport.off('swiperight.prev');
};
$(document).ready(init);
}());
Pastebin
Any ideas what I can do to get the Events back on again?
Thanks for all Ideas.
Regards
lippoliv
Fixed it:
jQuery Mobile itself prevents the swipe Event if an handler is registered, to kill an "scroll".
So I overwrote the $.event.special.swipe.scrollSupressionThreshold value and set it to 10000, to prevent jQueryMobile's preventDefault-call:
$.event.special.swipe.scrollSupressionThreshold = 10000;
Now my Code Looks like
app.utils.scroll = (function(){
var $viewport = undefined;
var swipeDisabled = false;
var init = function(){
$viewport = $('#viewport');
$viewport.mousewheel(mayChangePage);
// See #23.
$.event.special.swipe.scrollSupressionThreshold = 10000;
// Listen to swipeleft / swiperight-Event to change page.
$viewport.on('swipeleft.next', next);
$viewport.on('swiperight.prev', prev);
}
var mayChangePage = function(e){
// If page is not zoomed, change page (next or prev).
if (app.utils.zoom.isZoomed() === false) {
if (e.deltaY > 0) {
app.utils.pagination.prev(e);
} else {
app.utils.pagination.next(e);
}
}
// Stop scrolling page through mouse wheel.
e.preventDefault();
e.stopPropagation();
};
var next = function (e) {
// If page is not zoomed, switch to next page.
if (app.utils.zoom.isZoomed() === false) {
app.utils.pagination.next(e);
}
};
var prev = function (e) {
// If page is not zoomed, switch to prev page.
if (app.utils.zoom.isZoomed() === false) {
app.utils.pagination.prev(e);
}
};
$(document).ready(init);
}());
Thanks to Omar- who wrote with me several minutes / hours in the jquery IRC and gave some suggestions regarding overwriting Standard values for jQueryMobile.
I'm trying to load my images and fade in. Its working. But lets suppose that I have 4 images. Right now, my script its working by loading the last image, not the first. How can I make my js load the first image, and just start loading the second after the first has been loaded?
Here's my code:
$(function(){
$("a").click(function(){
$("#load").load('load.html', function() {
$('#load img').hide();
alert($("#load img").length);
$('#load img').each( function(){
$(this).on('load', function () {
$(this).fadeIn();
});
});
});
return false;
});
});
See http://jsfiddle.net/5uNGR/15/
Try something where you are not trying to perform a fadeIn on each image as they load, but test the ok-ness of the next image in your animation queue each time ANY load event happens, then on the animation callback, see if the next one is ready. Here is a script that should work.
BTW, see http://www.sajithmr.me/javascript-check-an-image-is-loaded-or-not for more on image readiness testing.
$(function () {
// util fn to test if image loaded properly
var isImgLoadOk = function (img) {
if (!img.complete) { return false; }
if (typeof img.naturalWidth != "undefined" && img.naturalWidth == 0) {
return false;
}
return true;
};
$("a").on('click', function () {
$("#load").load('load.html', function () {
var imgs = $('#load img').hide(), //create image array and hide (chaining)
animIndex = 0, //position in the animation queue
isFading = false; //track state of whether an animation is in prog
// this is a load handler AND is called in the fadeIn callback if
// not at last image in the collection
var fadeNextImg = function () {
// make sure a load event didn't happen in the middle of an animation
if (isFading) return;
// last image in animation queue?
var isLast = animIndex == imgs.length - 1;
// get the raw image out of the collection and test if it is loaded happily
var targetImage = imgs[animIndex];
if (isImgLoadOk(targetImage)) {
// jQuery-up the htmlImage
targetImage = $(targetImage);
// increment the queue
animIndex++;
// set animation state - this will ignore load events
isFading = true;
// fade in the img
targetImage.fadeIn('slow', function () {
isFading = false;
// test to see if next image is ready to load by
// recursively calling the parent fn
if (!isLast) fadeNextImg();
});
}
};
imgs.on('load', fadeNextImg);
});
return false;
});
});
Ron's solution is a little over-engineered IMO. If your intention is indeed to load all of the images before the animation starts, then you could do something similar to the following:
$(function(){
$("a").click(function(){
$("#load").load('load.html', function() {
$('#load img').hide(); // I would recommend using css to hide the image instead
alert($("#load img").length);
$("#load img").each(function(i, image) {
setTimeout(function() { // For each image, set increasingly large timeout before fadeIn
$(this).fadeIn();
}, 2000 * i);
});
});
return false;
});
});
There are three images that I have made a tooltip for each.
I wanted to show tooltips within timed intervals say for 2 seconds first tooltip shows and for the second interval the 2nd tooltips fades in and so on.
for example it can be done with this function
function cycle(id) {
var nextId = (id == "block1") ? "block2": "block1";
$("#" + id)
.delay(shortIntervalTime)
.fadeIn(500)
.delay(longIntervalTime)
.fadeOut(500, function() {cycle(nextId)});
}
now what i want is to stop the cycle function when moseover action occurs on each of the images and show the corresponding tooltip. And again when the mouse went away again the cycle function fires.
If I understand everthing correctly, than try this code. Tt stops the proccess if you hover the image and continues if you leave the image. The stop() function will work on custom functions if you implement them like the fadeOut(), slideIn(), ... functions of jquery.
$('#' + id)
.fadeIn(500, function () {
var img = $(this).find('img'),
self = $(this),
fadeOut = true;
img.hover(function () {
fadeOut = false;
},
function () {
window.setTimeout(function () {
self.fadeOut(500);
}, 2000);
}
);
window.setTimeout(function () {
if (fadeOut === false) {
return;
}
self.fadeOut(500);
}, 2000);
});
I am able to find the cursor position. But I need to find out if the mouse is stable. If the mouse wasn't moved for more than 1 minute, then we have to alert the user.
How its possible, are there any special events for this? (Only for IE in javascript)
Set a timeout when the mouse is moved one minute into the future, and if the mouse is moved, clear the timeout:
var timeout;
document.onmousemove = function(){
clearTimeout(timeout);
timeout = setTimeout(function(){alert("move your mouse");}, 60000);
}
Here's a one-and-done function that can check any element for movement:
function mouse (element, delay, callback) {
// Counter Object
element.ms = {};
// Counter Value
element.ms.x = 0;
// Counter Function
element.ms.y = function () {
// Callback Trigger
if ((++element.ms.x) == delay) element.ms.callback(element, element.ms);
};
// Counter Callback
element.ms.callback = callback;
// Function Toggle
element.ms.toggle = function (state) {
// Stop Loop
if ([0, "off"][state]) clearInterval(element.ms.z);
// Create Loop
if ([1, "on"][state]) element.ms.z = setInterval(element.ms.y, 1);
};
// Function Disable
element.ms.remove = function () {
// Delete Counter Object
element.ms = null; return delete element.ms;
};
// Function Trigger
element.onmousemove = function () {
// Reset Counter Value
element.ms.x = -1;
};
// Return
return element.ms;
};
Usage:
mouse(element, delay, callback)
Examples:
Make a video player hide the mouse after 5 seconds when idle and fullscreen
let x = mouse(video, 5000, function (a) {
if (document.webkitIsFullScreen) video.style.cursor = "none";
});
x.toggle(1); addEventListener("mousemove", function () {
video.style.cursor = "auto";
});
Chat Room AFK (45 Seconds) (assuming you have a chat box and a send message function):
let x = mouse(chatBox, (45e3), function (a) {
chatBox.send({ text: chatBox.username + " is AFK.", italic: true });
});
x.toggle(1); x.addEventListener("mousemove", function () {
chatBox.send({ text: chatBox.username + " is no longer AFK", italic: true });
});
Is there not a way to set a timer to start incrementing after every mouse movement event?
If it gets to a minute then pop up the message box, but every time the mouse moves the timer gets reset.
Use a timer that resets its value on mousemove event.
If timer reaches 1 minute --> Do something.
More info on timer here http://www.w3schools.com/js/js_timing.asp
And more info on catchin mouse events here http://www.quirksmode.org/js/events_mouse.html
Yes, you have a onmousemove event in Javascript, so to achieve what you need you just have to do code something like this:
startTimer();
element.onmousemove = stopTimer(); //this stops and resets the timer
You can use it on the document body tag for instance.
UPDATE: #Marius has achieved a better example than this one.
You can use the onmousemove event. Inside it, clearTimeout(), and setTimeout(your_warning, 1 minute).
You could use this script/snippet to detect the mouse pointer position and "remember" it. Then use a timer "setTimeout(...)" to check the position let's say every second and remember that time.
If more than one minute passed and the position hasn't changed, you could alert the user.