Avoid mouseover mouseleave conflicts - javascript

I'm working with this js fiddle here: http://jsfiddle.net/tPx6x/
The animation works like so
You hover over the text, a circle fades in & begins to pulse 1 second later for as long as your mouse is over the text.
When your mouse pointer leaves the text, the pulse stops after one second and the circle fades out.
The issue arises when you do this:
Put your mouse over the text, remove the pointer from the text, THEN place the pointer back over the text before the script has a chance to finish(1-1.4s).
You won't be able to make the circle appear properly agin...you will have to allow the script to reset. That is the problem.
What is the best way to tackle this issue?
Example code:
<div class='circle__title_project-management'>
<h1>project management</h1>
</div>
<div class='circle__project-management hidden'></div>
.circle__project-management, .circle__title_project-management
{
display: inline-block;
cursor: pointer;
}
.circle__project-management
{
margin-left: 8px;
vertical-align: -4.07px;
background-color: transparent;
border: 2px solid #00DBFF;
width: 30px;
height: 30px;
border-radius: 90px;
top: 280px;
left: 40px;
}
.hidden
{
visibility: hidden;
}
.visible
{
visibility: visible;
}
.animate-infinite
{
animation-iteration-count: infinite;
-moz-animation-iteration-count: infinite;
-webkit-animation-iteration-count: infinite;
}
var circleTitle = $('.circle__title_project-management h1');
var circle = $('.circle__project-management');
var initTimeout = 1000;
var initTimeoutPlus = 1400;
circleTitle.mouseover( function() {
circle.removeClass('hidden');
circle.addClass('animated fadeIn');
setTimeout( function() {
circle.addClass('pulse animate-infinite');
circle.removeClass('fadeIn');
}, initTimeout);
});
circleTitle.mouseleave( function() {
setTimeout( function() {
circle.stop().removeClass('pulse animate-infinite visibility');
circle.addClass('fadeOut');
}, initTimeout);
setTimeout( function() {
circle.removeClass('fadeOut');
circle.addClass('hidden');
}, 1400);
});

You should note that setTimeout has a return value. You want to clear previous timeouts before you start new ones; otherwise you can get a timeout queue which completely skews your animations. Something like this:
var myTimeout;
...
clearTimeout(myTimeout);
myTimeout = setTimeout(...);
Not sure if this is exactly what you were going for, but along these lines: http://jsfiddle.net/FYY38/
More info here: http://www.w3schools.com/js/js_timing.asp
Also, it looks like the circle.stop() call is doing nothing (as it's css-animated)

To avoid antagonist behaviours, maybe add a class to your element to tag it when the event is triggered and remove it when another is triggered.
That way you can stay in control of what's going on.

you can set time out to mouse over function to cover the time delay for mouseleave.
note that the first run must be without delay
var initTimeout = 1000;
var initTimeoutPlus = 1400;
var firstrun = true;
circleTitle.mouseover( function() {
if (firstrun) {
initTimeoutPlus = 0;
firstrun = false;
} else initTimeoutPlus = 1400;
setTimeout(function() {
circle.removeClass('hidden');
circle.addClass('animated fadeIn');
setTimeout( function() {
circle.addClass('pulse animate-infinite');
circle.removeClass('fadeIn');
}, initTimeout);
}, initTimeoutPlus);
});

Probably if you just add a key on mouseover, and toggle it after mouseleave, and before you trigger any mouseleave timeout events, check the key, if it is set, ignore, else go ahead and execute mouseleave
this way if the key is "on" it means a mouse over occurred, if it was off, it means the mouseleave occurred and it is still occurring
var key = false;
circleTitle.mouseover( function() {
key = true;
circle.removeClass('hidden');
circle.addClass('animated fadeIn');
setTimeout( function() {
circle.addClass('pulse animate-infinite');
circle.removeClass('fadeIn');
}, initTimeout);
});
circleTitle.mouseleave( function() {
key = false;
setTimeout( function() {
if (!key){
circle.stop().removeClass('pulse animate-infinite visibility');
circle.addClass('fadeOut');
}
}, initTimeout);
setTimeout( function() {
if (!key){
circle.removeClass('fadeOut');
circle.addClass('hidden');
}
}, 1400);
});

Related

Make a background fade in every time "onclick"

I would like the DIV to show a confirmed message where the css effect "animation" or "fade out" is activated with each click. It works fine on the first click, but not on the clicks that follow.
function clientedetail() {
document.getElementById("guardadoC").innerHTML = "Guardado.";
document.getElementById("guardadoC").style.cssText = "animation: background-fade 3s;padding:5px;";
}
#keyframes background-fade {
0% {
background-color: green;
}
100% {
background-color: none;
}
}
<input type="button" onclick="clientedetail()"></input>
<div id="guardadoC"></div>
You can add a addEventListener('animationend', function() { ... }); to reset the animation so you can run it again.
It's also a good idea to keep your CSS into your CSS file and not write it as a strings in JavaScript. Now, we are adding a class to the element to do what we want.
function clientedetail() {
var el = document.getElementById("guardadoC");
el.innerHTML = "Guardado.";
el.classList.add("animating");
//This function runs when the CSS animation is completed
var listener = el.addEventListener('animationend', function() {
el.classList.remove("animating");
//this removes the listener after it runs so that it doesn't get re-added every time the button is clicked
el.removeEventListener('animationend', listener);
});
}
#keyframes background-fade {
0% {
background-color: green;
}
100% {
background-color: none;
}
}
#guardadoC {
padding:5px;
}
#guardadoC.animating {
animation: background-fade 3s;
}
<button type="button" onclick="clientedetail()">click me</button>
<div id="guardadoC"></div>
You can use the animationend event to reset the animation.
The animationend event is fired when a CSS Animation has completed
(but not if it aborts before reaching completion, such as if the
element becomes invisible or the animation is removed from the
element).
You'll notice in this demo that I'm not using anonymous functions. With anonymous functions, we end up redefining the function over and over, which is not what you want regarding performance. Using a functional reference, we declare a function once and tie an event to it.
const btn = document.querySelector(".myButton");
const guardadoC = document.getElementById("guardadoC");
btn.addEventListener("click", clientedetail);
function clientedetail() {
guardadoC.innerHTML = "Guardado.";
guardadoC.style.cssText = "animation: background-fade 3s;padding:5px;";
}
function resetAnimation() {
guardadoC.innerHTML = "";
guardadoC.style.cssText = "";
}
guardadoC.addEventListener("animationend", resetAnimation);
#keyframes background-fade {
0% {
background-color: green;
}
100% {
background-color: none;
}
}
<input type="button" class="myButton">
<div id="guardadoC"></div>
jsFiddle
More about animationend
You could recreate the element each time you click the button. This will be a complete reset, and so it will even work when you interrupt the previous animation.
function clientedetail() {
var elem = document.getElementById("guardadoC");
var newElem = elem.cloneNode(true);
elem.parentNode.replaceChild(newElem, elem);
newElem.innerHTML = "Guardado.";
newElem.style.cssText = "animation: background-fade 3s;padding:5px;";
}
#keyframes background-fade {
0% {
background-color: green;
}
100% {
background-color: none;
}
}
<input type="button" onclick="clientedetail()"></input>
<div id="guardadoC"></div>
Trigger it based on class if you can, the way you're doing it it will only do it once.
Or you can destroy the element and re-create it kinda like this.
function clientedetail() {
var element = document.getElementById("guardadoC");
if (typeof(element) != 'undefined' && element != null)
{
document.getElementById("guardadoC").remove();
var remakeDiv = document.createElement("div");
remakeDiv.setAttribute("id", "guardadoC");
document.body.appendChild(remakeDiv)
}
document.getElementById("guardadoC").innerHTML = "Guardado.";
document.getElementById("guardadoC").style.cssText = "animation: background-fade 3s;padding:5px;";
}

How to make setTimeout activate on last time a Toggle is clicked?

I'm using a .slideToggle to show a div once an image is clicked. I want the div to disappear 10 seconds after the last time the toggle is clicked. The problem is that if I click the image a few times, the duration is 10 seconds after the first click and not the last. If you view the fiddle (I used a shorter duration for testing) and click the image a few times you will see what I mean.
Does anyone have any idea how I can get this working as desired? Any help would be greatly appreciated!
Fiddle: https://jsfiddle.net/7fy536nv/
Requirements...
The div should show for 10 seconds then disappear
The div will disappear if the image is clicked again
The div will disappear if something outside the div is clicked
HTML
<div class="box-new">
<a href="box-link" id="box-link">
<img src="https://dummyimage.com/100x60/ff0000/fff.png">
</a>
</div>
<div id="empty-box">jkhsahg akjfhsajk fhas jklsad flkasd hfjkashd fjka sdkjfh adskjfhs dakjfh kafh sdah dhjaf</div>
CSS
body, html {
margin: 0;
}
#empty-box {
display: none;
position: absolute;
background: #000;
top: 60px;
width: 240px;
padding: 20px;
left: 0;
color: #fff;
text-align: center;
font-family: "open sans", "arial";
font-size: 14px;
font-weight: 600;
line-height: 18px;
z-index: 1;
}
JS
$('#box-link').click(function(event){
event.stopPropagation();
$("#empty-box").slideToggle(400);
setTimeout(function() {
$("#empty-box").slideUp();
}, 5000);
return false;
});
$("#empty-box").on("click", function (event) {
event.stopPropagation();
});
$(document).on("click", function () {
$("#empty-box").slideUp(400);
});
Assign your call to setTimeout to a variable declared in the outer scope and clear it with clearTimeout in every subsequent event:
var timeout;
$('#box-link').click(function(event){
clearTimeout(timeout);
event.stopPropagation();
$("#empty-box").slideToggle(400);
timeout = setTimeout(function() {
$("#empty-box").slideUp();
}, 5000);
return false;
});
The setTimeout function returns a value that you can cancel using clearTimeout.
So in your code, store the return value, and each time it is clicked, cancel the previous timeout and restart a new one.
var timeout = null;
function test()
{
if( timeout !== null )
clearTimeout(timeout);
timeout = setTimeout(..., 10000);
}
It's quite simple, really. The key is placing your setTimeout in a variable and calling clearTimeout(variable).
Example:
let someVar = false,
someTime = 5000,
msgTimer = document.getElementById('timer'),
timer,
current,
displayTimer = false;
$('.yourButton').on('click', someFunc)
function someFunc() {
if (someVar) {
clearTimeout(someVar) // <<< juice is here
console.log('cleared timeout!')
}
timer = performance.now()
someVar = setTimeout(function () {
clearInterval(displayTimer)
console.log(someTime / 1000 +
' seconds passed since last click...')
someVar = false
displayTimer = false
msgTimer.innerHTML = ''
}, someTime)
/**
* ¯\_(ツ)_/¯
* ignore past this point, rest is timer
*
* ˙ʇᴉ pǝǝu ʇ,uop no⅄ ˙ʎllɐǝɹ
**/
if (displayTimer) {
clearInterval(displayTimer)
displayTimer = false
}
displayTimer = setInterval(function () {
current = performance.now()
msgTimer.innerHTML = Math.max(timer + 5000 - current,0)
.toFixed(2) + 'ms'
}, 15)
}
#timer {
font-family: monospace;
text-align:right;
display: inline-block;
width: 100px;
font-size: 1.2rem;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="yourButton">Don't click. Think.</button>
<span id="timer"></span>
Reduced interval to 5 seconds for faster testing.
Here is a solution to show a div for a maximum of 10 seconds...
And hide it if user clicks anywhere before this delay.
There is no problem with the delay if user clicks often or repeately...
Because I took care of resets.
I created a CodePen, with a timer displayed aside the cart link, to show the time passing.
And here is a CodePen with the exact same code as in the below snippet, if your want to play with it.
var emptyCart = $("#emptyCart");
var cartTimer;
var carMaxTime = 10000;
// Function to hide the cart
var hideCart = function(){
emptyCart.dequeue().slideUp("slow");
}
// Function to show the cart
var showCart = function(){
emptyCart.dequeue().slideDown("slow");
clearTimeout(cartTimer); // Just to be sure We have only one timer running
cartTimer = setTimeout(function(){
hideCart();
},carMaxTime);
}
// Function to handle click on the cart link
$("#clickCart").click(function(){
$(document).off("click",hideCart()); // Just to prevent a slideUp which would counter-act a slideUp
if(emptyCart.is(":hidden")){
showCart();
}
setTimeout(function(){ // 1ms delay to use this event handler on next click.
$(document).on("click",function(){
hideCart();
$(document).off("click",hideCart()); // Unbind this handler once used.
});
},1);
});
#emptyCart{
display:none;
width:100px;
background:#000;
color:#fff;
height:30px;
margin-top:10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="clickCart">
Cart
</div>
<div id="emptyCart">
No items
</div>

javascript delay popup

im having a prob with javascript which has been bugging me for hours now. I need to delay a css popup so that if you just scroll mouse around page you wont get loads of popups.
Whatever i try it either makes the popup act goofy, poping up after x seconds with a swipe of any link, auto closing etc etc. if i add a timer to the mouseover it starts acting weird, if i then delete the timer for mouseout it works fine but you can no longer mouseover menu before it closes, also tried adding negative margin and it autocloses
cheers all
javscript
<script type="text/javascript">
var span = document.querySelectorAll('.pop');
for (var i = span.length; i--;) {
(function () {
var t;
span[i].onmouseover = function () {
hideAll();
clearTimeout(t);
this.className = 'popHover';
};
span[i].onmouseout = function () {
var self = this;
t = setTimeout(function () {
self.className = 'pop';
}, 300);
};
})();
}
function hideAll() {
for (var i = span.length; i--;) {
span[i].className = 'pop';
}
};
</script>
css
.pop {
position:relative;
}
.pop div {
display: none;
}
.popHover {
position:absolute;
}
.popHover div {
background-color:#FFFFFF;
border-color:#AAAAAA;
border-style:solid;
border-width:1px 2px 2px 1px;
color:#333333;
padding:5px;
position:absolute;
z-Index:9999;
width:150px;
display: inline-block;
margin-top: -20px;
}
Using jquery might be a little more helpful for what you are trying to do. Try something like this:
// Use a CDN to take advantage of caching
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript">
var t;
$('.pop').on('mouseover', $.proxy(function () {
hideAll();
clearTimeout(t);
this.addClass('popHover');
this.removeClass('pop');
}, this));
$('.pop').on('mouseout', $.proxy(function () {
var self = this;
t = setTimeout(function () {
self.addClass('pop');
self.removeClass('popHover');
}, 300);
},this));
function hideAll() {
// Since you are calling this from the mouseover function of all the
// elements with the 'pop' class, I dont understand what the purpose of this class
// is so it might not be entirely correct.
$('.pop').addClass('pop');
}
</script>
Let me know if this helps. If you still need it. It would be helpful to have a fiddle to maybe tweak to give you a more accurate response.

Button hiding not functioning properly

HTML Code:
<div id="slick-slidetoggle">wxyz</div>
<div id="slickbox" >abcd</div>​
JavaScript:
var hoverVariable=false;
var hoverVariable2=false;
$('#slickbox').hide();
$('#slick-slidetoggle').mouseover(function() {
hoverVariable2=true;
$('#slickbox').slideToggle(600);
return false;
})
$('#slick-slidetoggle').mouseleave(function() {
hoverVariable2=false;
setTimeout(function (){
if(!hoverVariable && !hoverVariable2){
$('#slickbox').slideToggle(600);
return false;}
}, 1000);
})
$('#slickbox').mouseleave(function() {
hoverVariable=false;
setTimeout(function (){
if(!hoverVariable && !hoverVariable2){
$('#slickbox').slideToggle(600);
return false;}
return false;
}, 1000);
})
$('#slickbox').mouseover(function() {
hoverVariable2=false;
hoverVariable=true;
})​
CSS Code:
#slickbox {
background: black;
width:100px;
height: 135px;
display: none;
cursor:pointer;
color:white;
}
#slick-slidetoggle{
background: yellow;
width:100px;
height: 135px;
cursor:pointer;
color:black;
}
​
Now the desired behaviour is that when mouse is slide over yellow div("wxyz") black div("abcd") should slide down and if mouse is moved out of yellow without moving on to black div, the black div should hide after two seconds.
This is happening. If mouse is moved over black div immediately after moving out of yellow div the black div should not hide as long as the mouse is on the black div. This is also happening.
Next steps are bit difficult to explain but I'll try, when mouse is moved over yellow div and black div comes out then mouse is moved over black div and within two seconds if it moved out of it(black div) then the whole animation goes haywire. Its behaviour is reversed. But if the mouse is kept on black div for more than two seconds and then it is moved out then the whole script runs fine.
This is the link to explain better. http://jsfiddle.net/HAQyK/381/
Try replacing slideToggle() with the appropriate slideUp() and slideDown() calls. http://jsfiddle.net/tppiotrowski/HAQyK/386/
var hoverVariable = false;
var hoverVariable2 = false;
$('#slickbox').hide();
$('#slick-slidetoggle').mouseover(function() {
hoverVariable2 = true;
$('#slickbox').slideDown(600);
return false;
})
$('#slick-slidetoggle').mouseleave(function() {
hoverVariable2 = false;
setTimeout(function() {
if (!hoverVariable && !hoverVariable2) {
$('#slickbox').slideUp(600);
return false;
}
}, 1000);
})
$('#slickbox').mouseleave(function() {
hoverVariable = false;
setTimeout(function() {
if (!hoverVariable && !hoverVariable2) {
$('#slickbox').slideUp(600);
return false;
}
return false;
}, 1000);
})
$('#slickbox').mouseover(function() {
hoverVariable2 = false;
hoverVariable = true;
})​
I re-coded a solution. Checkout the fiddle here
var hideB;
var $black = $('#slickbox');
var $yellow = $('#slick-slidetoggle');
function showBlack() {
if( hideB ) window.clearTimeout( hideB );
$black.stop( true, true );
$black.slideDown(600);
}
function hideBlack() {
hideB = setTimeout( function( ) {
$black.stop( true, true );
$black.slideUp( 600 ); }
, 1000 );
}
$black.hide();
$yellow.mouseenter(function() {
showBlack();
})
$yellow.mouseleave(function() {
hideBlack();
});
$black.mouseleave( function( ) {
hideBlack();
});
$black.mouseenter( function( ) {
showBlack();
});
Your problem seems to be that the slideToggle in firing twice in quick succession because of your duplicate timeout functions. The cleanest way to deal with timeouts or intervals is to store them in a variable to give you the control of removing them when not needed:
// Defined in global scope
var timer;
$('#slick-slidetoggle').mouseleave(function() {
hoverVariable2=false;
// Timer set as function
timer = setTimeout(function (){
if(!hoverVariable && !hoverVariable2){
$('#slickbox').slideToggle(600);
// Timer no longer need and so cleared
clearTimeout(timer);
return false;}
}, 1000);
});
EDIT: Neglected to add the slideUp/slideDown instead of Toggle as per the correct answer above. See the updated jsFiddle which is now correct: http://jsfiddle.net/HAQyK/390/
Another way you could approach your script is to use jQuerys delay funciton and the stop(); method for animation. Wrap the divs in a container and you've got a much simpler block of code:
$('#slick-container').mouseenter(function() {
$('#slickbox').stop().slideDown(600);
}).mouseleave(function(){
$('#slickbox').stop().delay(1000).slideUp(600);
});
Check it out here: http://jsfiddle.net/HAQyK/387/

How do I clear this setInterval inside a function?

Normally, I’d set the interval to a variable and then clear it like var the_int = setInterval(); clearInterval(the_int); but for my code to work I put it in an anonymous function:
function intervalTrigger() {
setInterval(function() {
if (timedCount >= markers.length) {
timedCount = 0;
}
google.maps.event.trigger(markers[timedCount], "click");
timedCount++;
}, 5000);
};
intervalTrigger();
How do I clear this? I gave it a shot and tried var test = intervalTrigger(); clearInterval(test); to be sure, but that didn’t work.
Basically, I need this to stop triggering once my Google Map is clicked, e.g.
google.maps.event.addListener(map, "click", function() {
//stop timer
});
The setInterval method returns a handle that you can use to clear the interval. If you want the function to return it, you just return the result of the method call:
function intervalTrigger() {
return window.setInterval( function() {
if (timedCount >= markers.length) {
timedCount = 0;
}
google.maps.event.trigger(markers[timedCount], "click");
timedCount++;
}, 5000 );
};
var id = intervalTrigger();
Then to clear the interval:
window.clearInterval(id);
// Initiate set interval and assign it to intervalListener
var intervalListener = self.setInterval(function () {someProcess()}, 1000);
function someProcess() {
console.log('someProcess() has been called');
// If some condition is true clear the interval
if (stopIntervalIsTrue) {
window.clearInterval(intervalListener);
}
}
the_int=window.clearInterval(the_int);
Simplest way I could think of: add a class.
Simply add a class (on any element) and check inside the interval if it's there. This is more reliable, customisable and cross-language than any other way, I believe.
var i = 0;
this.setInterval(function() {
if(!$('#counter').hasClass('pauseInterval')) { //only run if it hasn't got this class 'pauseInterval'
console.log('Counting...');
$('#counter').html(i++); //just for explaining and showing
} else {
console.log('Stopped counting');
}
}, 500);
/* In this example, I'm adding a class on mouseover and remove it again on mouseleave. You can of course do pretty much whatever you like */
$('#counter').hover(function() { //mouse enter
$(this).addClass('pauseInterval');
},function() { //mouse leave
$(this).removeClass('pauseInterval');
}
);
/* Other example */
$('#pauseInterval').click(function() {
$('#counter').toggleClass('pauseInterval');
});
body {
background-color: #eee;
font-family: Calibri, Arial, sans-serif;
}
#counter {
width: 50%;
background: #ddd;
border: 2px solid #009afd;
border-radius: 5px;
padding: 5px;
text-align: center;
transition: .3s;
margin: 0 auto;
}
#counter.pauseInterval {
border-color: red;
}
<!-- you'll need jQuery for this. If you really want a vanilla version, ask -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="counter"> </p>
<button id="pauseInterval">Pause/unpause</button></p>

Categories