execute Jquery when the mouse stops moving - javascript

I have a quick script that has a trail follow the cursor:
jQuery(document).ready(function(){
$(document).mousemove(function(e){
$('.fall').each(function(){
if ($(this).css("opacity") == 0){
$(this).remove();
};
});
t = (e.pageY - 10).toString() + 'px';
l = (e.pageX - 10).toString() + 'px';
$('.fall').css("margin_left",l);
$('.fall').css("margin_top",t);
var doit = '<div class="fall" style="position:fixed;margin-left:' + l + ';margin-top:' + t + ';">+</div>'
$('body').prepend(doit);
$('#status2').html(e.pageX +', '+ e.pageY);
$('.fall').animate({
marginTop: '+=50px',
opacity: 0
},1000);
});
});
Now I would like to remove the animate part and have something like the following when the mouse is not moving:
$('.fall').each(function(){
$(this).fadeOut('slow');
$(this).remove()
});
I just can't figure out how to execute this when the mouse is not moving for more than like a second. Any ideas?
Thanks, and here is a jsfiddle

You add a timeout that fires after one second of inactivity, and clear the timeout if the mouse moves within 1 second etc :
var timer;
$(document).on('mousemove', function(e){
clearTimeout(timer);
timer = setTimeout(function() {
$('.fall').fadeOut('slow', function() {
$(this).remove();
});
}, 1000);
});
FIDDLE
EDIT:
Here's how I'd do it
FIDDLE

is this what you require? jsFiddle
lastTimeMouseMoved = new Date().getTime();
var t = setTimeout(function() {
var currentTime = new Date().getTime();
if (currentTime - lastTimeMouseMoved > 1000) {
$('.fall').fadeOut('slow');
// $('.fall').remove();
}
}, 1000)

Related

Function not starting when scroll point is over top of the div

I use a scrollTop function to start animations, delays, etc when the div is scrolled to. It works for other things on my page, but for some reason, this function is not working and it loads on page load.
Does anyone see anything wrong in my code? This can be seen live here:
<div class="blue-box-container">
</div>
$(function() {
var oTop = $('.blue-box-container').offset().top - window.innerHeight;
$(window).scroll(function() {
var pTop = $('body').scrollTop();
console.log(pTop + ' - ' + oTop);
if (pTop > oTop) {
blueBoxDelays();
}
});
});
$('.fadeBlock').css('display', 'none');
blueBoxDelays();
function blueBoxDelays() {
var delay = 0;
$('.fadeBlock').each(function(i) {
$(this).delay(400 + delay).fadeIn(1000);
delay = 200 * (i + 1);
});
};
I extracted your code to a fiddle and it works correctly https://jsfiddle.net/26jw7Low/3/, you just need to remove the call to blueBoxDelays() which is outside of the initial function as seen below.
$(function() {
var oTop = $('.blue-box-container').offset().top - window.innerHeight;
$(window).scroll(function() {
var pTop = $('body').scrollTop();
console.log(pTop + ' - ' + oTop);
if (pTop > oTop) {
blueBoxDelays();
}
});
});
$('.fadeBlock').css('display', 'none');
// REMOVE THIS blueBoxDelays();
function blueBoxDelays() {
var delay = 0;
$('.fadeBlock').each(function(i) {
$(this).delay(400 + delay).fadeIn(1000);
delay = 200 * (i + 1);
});
};
Function $('.fadeBlock').css('display', 'none'); maybe not yet execute
You can put it to $(function(){}) end try again:
$(function() {
$('.fadeBlock').css('display', 'none');
var oTop = $('.blue-box-container').offset().top - window.innerHeight;
$(window).scroll(function() {
var pTop = $('body').scrollTop();
console.log(pTop + ' - ' + oTop);
if (pTop > oTop) {
blueBoxDelays();
}
});
});

javascript: how to exit a loop by clicking a button

I did some searching and I'm not even sure if what I want to do is good javascript practice.
I have a while loop that I would like to exit from early if a stop button is clicked.
$( "#go" ).click(function() {
var gotime = 1;
while (gotime < 100) {
for(i = 0; i < 2; i++){
var divName = "floatName" + i;
console.log(divName);
$( "#" + divName ).animate({
left: Math.random()*500 + "px",
top: Math.random()*500 + "px"
}, 500, function() {
// Animation complete.
});
};
gotime += 1;
$( "stop" ).click(function() {
gotime = 101;
});
};
});
This doesn't work though. I originally had an endless loop (not incrementing gotime).
http://jsfiddle.net/cvoxe465/
Actually it stops if you wait for some time. The problem is you execute animation very often and $.animate have to queue it. There is $.stop method that allow you to stop the currently-running animation. DEMO
$( "#stop" ).click(function() {
gotime = 101;
$('#floatName0, #floatName1').stop(true, true);
});
EDIT:
Note that in the code that you provided there is mistake. Instead $("stop") you need to use $("#stop").
You may use setInterval:
Js:
var interval;
$("#go").click(function () {
var gotime = 1;
interval = setInterval(function () {
for (i = 0; i < 2; i++) {
var divName = "floatName" + i;
console.log(divName);
$("#" + divName).css({
left: Math.random() * 500 + "px",
top: Math.random() * 500 + "px"
});
};
gotime += 1;
if (gotime > 100) {
clearInterval(interval);
}
}, 500)
});
$("#stop").on('click', function () {
clearInterval(interval);
});
css:
#randomFloat {
color: red;
}
#floatName1, #floatName0 {
transition : 0.5s left, 0.5s top;
}
Fiddle
animate doesn't block the loop. The animations are stacked up and then executed, but the loop finishes a lot earlier. Here is something that works:
var loopAllowed = false;
$('#go').click(function(){
loopAllowed = true;
var max = 2;
var loop = function(){
for(var i = 0; i < max; i++){
var divName = "floatName" + i;
$( "#" + divName ).animate({
left: Math.random()*500 + "px",
top: Math.random()*500 + "px"
}, 500, i === max - 1 && loopAllowed ? loop : undefined);
}
};
loop();
});
$('#stop').click(function(){
loopAllowed = false;
});
JSFiddle. We manually call the loop function after the animation has ended (by passing it as the callback function). If loopAllowed is false (e.g. set to false by clicking #stop), then it won't be passed as the callback function and the looping stops.

Smooth javascript navigation stops working after first click

This webpage http://www.eboxlab.net/ has a menu on the left side. What I need to achieve is to be able to go to a page section when the respective menu option is pressed. Here is my code (pretty sure it's quite bad, but I will clean it up later, after I make it work):
navigateMe();
navInit = 1;
navNext = 2;
function navigateMe() {
step = jQuery('ul#navigation li').size();
looper = setInterval(function(){
if(navNext > step + 1) {
navInit = 1;
navNext = 1;
}
var refLink = jQuery('ul#navigation li:nth-child(' + navInit + ') a').attr('href').replace('#', '');
var divLink = jQuery("div[id='" + refLink + "']").offset().top;
jQuery('ul#navigation li:nth-child(' + navInit + ') a').on('click', function() {
jQuery('html, body').animate({
scrollTop: divLink
}, 500);
});
navInit = navNext;
navNext = navNext + 1;
}, 0);
}
However the problem is that it only works once. After you click menu once, it doesn't slide up or down anymore. Please tell me what's wrong with it.
Many thanks in advance.

javascript - Need onclick to go full distance before click works again

I have this javascript function I use that when clicked goes a certain distance. This is used within a scroller going left to right that uses about 7 divs. My question is how do I get the click to go the full distance first before the click can be used again? The issue is if the user rapidly clicks on the arrow button it resets the distance and sometimes can end up in the middle of an image instead of right at the seam. What code am I missing to accomplish this?
$(function () {
$("#right, #left").click(function () {
var dir = this.id == "right" ? '+=' : '-=';
$(".outerwrapper").stop().animate({ scrollLeft: dir + '251' }, 1000);
});
});
I would've thought that the easiest way would be to have a boolean flag indicating whether or not the animation is taking place:
$(function () {
var animating = false,
outerwrap = $(".outerwrapper");
$("#right, #left").click(function () {
if (animating) {return;}
var dir = (this.id === "right") ? '+=' : '-=';
animating = true;
outerwrap.animate({
scrollLeft: dir + '251'
}, 1000, function () {
animating = false;
});
});
});
works for me: http://jsfiddle.net/BYossarian/vDtwy/4/
Use .off() to unbind the click as soon as it occurs, then re-bind it once the animation completes.
function go(elem){
$(elem).off('click'); console.log(elem);
var dir = elem.id == "right" ? '+=' : '-=';
$(".outerwrapper").stop().animate({ left: dir + '251' }, 3000, function(){
$("#right, #left").click(go);
});
}
$("#right, #left").click(function () {
go(this);
});
jsFiddle example
You can see in this simplified example that the click event is unbound immediately after clicking, and then rebound once the animation completes.
Use an automatic then call like this
var isMoving = false;
$(function () {
$("#right, #left").click(function () {
if (isMoving) return;
isMoving = true;
var dir = this.id == "right" ? '+=' : '-=';
$(".outerwrapper").stop().animate({ scrollLeft: dir + '251' }, 1000).then(function(){isMoving = false}());
});
});
I think that you miss the fact that when you make stop() you actually position the slider at some specific point. I.e. if your scroller is 1000px and you click left twice very quickly you will probably get
scrollLeft: 0 - 251
scrollLeft: -2 - 251
So, I think that you should use an index and not exactly these += and -= calculations. For example:
$(function () {
var numberOfDivs = 7;
var divWidth = 251;
var currentIndex = 0;
$("#right, #left").click(function () {
currentIndex = this.id == "right" ? currentIndex+1 : currentIndex-1;
currentIndex = currentIndex < 0 ? 0 : currentIndex;
currentIndex = currentIndex > numberOfDivs ? numberOfDivs : currentIndex;
$(".outerwrapper").stop().animate({ scrollLeft: (currentIndex * divWidth) + "px" }, 1000);
});
});
A big benefit of this approach is that you are not disabling the clicking. You may click as many times as you want and you can do that quickly. The script will still works.
This will work perfectly fine:
var userDisplaysPageCounter = 1;
$('#inventory_userdisplays_forward_button').bind('click.rightarrowiventory', function(event) {
_goForwardInInventory();
});
$('#inventory_userdisplays_back_button').bind('click.leftarrowiventory', function(event) {
_goBackInInventory();
});
function _goForwardInInventory()
{
//$('#inventory_userdisplays_forward_button').unbind('click.rightarrowiventory');
var totalPages = $('#userfooterdisplays_list_pagination_container div').length;
totalPages = Math.ceil(totalPages/4);
// alert(totalPages);
if(userDisplaysPageCounter < totalPages)
{
userDisplaysPageCounter++;
$( "#userfooterdisplays_list_pagination_container" ).animate({
left: "-=600",
}, 500, function() {
});
}
}
function _goBackInInventory()
{
//$('#inventory_userdisplays_back_button').unbind('click.leftarrowiventory');
if(userDisplaysPageCounter > 1)
{
userDisplaysPageCounter--;
$( "#userfooterdisplays_list_pagination_container" ).animate({
left: "+=600",
}, 500, function() {
});
}
}
I second BYossarian's answer.
Here is a variation on his demo, which "skips" the animation when the user clicks several times quickly on the buttons :
$(function () {
var targetScroll = 0,
outerwrap = $(".outerwrapper");
$("#right, #left").click(function () {
// stop the animation,
outerwrap.stop();
// hard set scrollLeft to its target position
outerwrap.scrollLeft(targetScroll*251);
if (this.id === "right"){
if (targetScroll < 6) targetScroll += 1;
dir = '+=251';
} else {
if (targetScroll > 0) targetScroll -=1;
dir = '-=251';
}
outerwrap.animate({ scrollLeft: dir }, 1000);
});
});
fiddle

how to use setInterval to continue animation while mouse is over div

I am trying to modify a slideshow to continuously animate while the mouse is over the back or next arrow. If the mouse leaves, I would like the animation to stop where it is.
I found this post and this post which are helpful in telling me I need to use setInterval, but because I am a beginner I am not sure how to implement it with the code I have. I tried updating the miliseconds set in the counter variable but that didn't change anything.
Here is the hover code so far. It advances the image on hover but not continuously.
$(document).ready(function(){
var thumbs = $('ul.thumbHolder li');
var bigImgs = $('ul.imgHolder li');
var mask = $('.imgHolder');
var imgW = $('ul.imgHolder li').width();
var speed = 800;
thumbs.removeClass('selected').first().addClass('selected');
thumbs.click(function () {
var target = $(this).index();
mask.animate({
'left': '-' + imgW * target + 'px'
}, speed);
thumbs.removeClass('selected');
$(this).addClass('selected');
});
$('.Bleft').on('mouseover', function () {
var i = $('ul.thumbHolder li.selected').index();
i--;
$('ul.thumbHolder li.selected').removeClass('selected');
thumbs.eq(i).addClass('selected');
if (i === -1) {
mask.animate({
'left': '-' + imgW * $('ul.thumbHolder li').index() + 'px'
}, speed);
} else {
mask.animate({
'left': '-' + imgW * i + 'px'
}, speed);
}
clearInterval(counter);
});
$('.Bright').on('mouseover', function () {
var i = $('ul.thumbHolder li.selected').index();
i = i >= thumbs.length - 1 ? 0 : i + 1;
$('ul.thumbHolder li.selected').removeClass('selected');
thumbs.eq(i).addClass('selected');
mask.animate({
'left': '-' + imgW * i + 'px'
}, speed);
clearInterval(counter);
});
var count = 0;
var counter = window.setInterval(timer, 5000);
function timer() {
count = count + 0;
if (count >= 0) {
count = 0;
return;
}
mask.animate({
'left': '-' + imgW * count + 'px'
}, speed);
thumbs.removeClass('selected');
thumbs.eq(count).addClass('selected');
}
});
This is an example of what I am trying to achieve (I know it is flash but I think it can be done with jQuery too).
This is a fiddle that has all my work so far.
Thank you for any help.
I think I am close to the solution. This is my idea.
Every ul.imgHolder li is divided in many blocks of 20px ( you can change the size of course ), so if a div has a size of 980px you will have 49 blocks for image.
When mouseover event is fired I will slide for a block every speed milliseconds until the mouseout is fired.
I've implemented only the slide right button, I've deleted partially some logic, sorry!
var $ = jQuery.noConflict(true);
$(document).ready(function(){
var thumbs = $('ul.thumbHolder li');
var bigImgs = $('ul.imgHolder li');
var mask = $('.imgHolder');
var imgW = $('ul.imgHolder li').width(); //Assuming imgW % 20 = 0
var blockSize = 20; //20px
var blocksPerThumb = imgW/blockSize;
var numBlocks = (blocksPerThumb)*thumbs.length;
var speed = 400;
var blockPos = 0;
var currentAnim = null;
thumbs.removeClass('selected').first().addClass('selected');
thumbs.click(function () {
var target = $(this).index();
mask.animate({
'left': '-' + imgW * target + 'px'
}, speed,'linear');
thumbs.removeClass('selected');
$(this).addClass('selected');
});
$('.Bleft').on('mouseover', function () {
});
$('.Bright').on('mouseover', function(){
currentAnim = setInterval(goRight,speed);
}).mouseout(function(){
clearInterval(currentAnim);
});
var goRight = function () {
blockPos = (blockPos+1)%numBlocks;
mask.animate({
'left': '-' + blockSize * blockPos + 'px'
}, speed,'linear');
};
});
Good Work!

Categories

Resources