How to use setTimeout to toggle a class in jquery? - javascript

This code uses a mouse click to toggle a class on an image.
I'd like this transition to happen automatically using setTimeout.
$(document).ready(function() {
$("#cf_onclick").click(function() {
$("#cf2 img.top").toggleClass("transparent");
});
});

$(document).ready(function() {
$("#cf_onclick").click(function() {
setTimeout(function() {
$("#cf2 img.top").toggleClass("transparent");
}, 1000);
});
});
.transparent {
opacity: 0.5;
filter: alpha(opacity=50);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='cf2'>
<img class='top' src="https://loremflickr.com/640/360
" alt="Image not found!" height="100" width="100">
</div>
<button id='cf_onclick'>Click Me</button>
Note:- You can set image by using setTimeout function.

setTimeout(function () {
$('#cf2 img.top').toggleClass('transparent');
}, 0);

In the following example toggleClass will be called automatically in every second.
setTimeout(function() {
$("#cf2 img.top").toggleClass("transparent");
}, 1000 ); // put timeout here, e.g. 1000 milliseconds is 1 second

Related

Text animation: each and setTimeOut

I'm trying to animate some text. Different divs are displayed and hid one after another, so that it looks like a word is reduced to just a letter, and then completed again.
I need some sort of delay between the .each() cycles. I tried to use the setTimeOut() function, but I still see all the divs appearing and then disappearing together, instead of one by one.
function fadeInOut(element) {
$(element).fadeIn("slow", function() {
$(this).fadeOut("slow");
})
}
function displayStepWords() {
$('.stepWord').each(function(i) {
setTimeout(fadeInOut(this), 5000 * i);
})
}
displayStepWords();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="stepWord">BYE</div>
<div class="stepWord">BY</div>
<div class="stepWord">B</div>
<div class="stepWord">BY</div>
<div class="stepWord">BYE</div>
Unclear exactly what you are aiming at, but something like:
function fadeInOut(element) {
$(element).fadeIn("slow", function() {
$(this).fadeOut("slow");
})
}
function displayStepWords() {
$('.stepWord').each(function(i) {
var me = $(this);
setTimeout( function(){fadeInOut(me);}, 1000 * i );
})
}
displayStepWords();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="stepWord">BYE</div>
<div class="stepWord">BY</div>
<div class="stepWord">B</div>
<div class="stepWord">BY</div>
<div class="stepWord">BYE</div>
The window.setTimeout expects a function for the first parameter not a function call.
setTimeout(function, milliseconds, param1, param2, ...)
If you want to show the divs one after each other in one place - you have to add some css.
<style>
.step-word {
position: absolute;
display: none;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
<div class="step-word">BYE</div>
<div class="step-word">BY</div>
<div class="step-word">B</div>
<div class="step-word">BY</div>
<div class="step-word">BYE</div>
</div>
<script>
var delay = 500,
$stepWords = $('.wrapper .step-word');
function fadeInOut($element) {
$element.fadeIn("slow", function () {
$element.fadeOut("slow");
});
}
$stepWords.each(function(i, elem) {
setTimeout(function () {
fadeInOut($stepWords.eq(i));
}, delay * i);
});
</script>
Try this one:
function displayStepWords() {
$('.stepWord').each(function(i) {
var $el = $(this);
setTimeout(function(){fadeInOut($el)}, 300 * i);
})
}

How can I run a function several times continuously?

All I'm trying to do is making a winking box. In other word I want to call a function into itself. I have this function:
$(document).ready(function(){
$("button").click(function(){
$("#div1").fadeToggle("slow");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Click to fade in/out box</button><br /><br /><br />
<div id="div1" style="width:80px;height:80px;background-color:red;"></div>
I want when user clicks on the button, that box fade in/out several time continuously as long as the time a request (ajax) takes. Currently when user clicks on the button, that box fades in/out once. Now I want to start fading in/out until a request ends. How can I do that?
Actually I'm trying to make a blinking box when a request is sending.
$(document).ready(function(){
function toggleForever() {
$("#div1").fadeToggle("slow", toggleForever);
}
$("button#start").click(function () {
toggleForever();
});
$("button#stop").click(function () {
$("#div1").stop().animate({opacity:1}, "slow");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="start">Click to fade in/out box</button>
<button id="stop">Click to stop</button><br /><br /><br />
<div id="div1" style="width:80px;height:80px;background-color:red;"></div>
The function parameter to fadeToggle gets called when the animation is complete. On another button click, we stop the animation and fade the box in (so it's always visible when we're done, no matter where in the animation we were). In your real code, you'll do that when your AJAX call is complete.
UPDATE
Another approach, using CSS animations instead. One notable difference here is stopping the animation moves abruptly back to full opacity.
$(function () {
$('#start').click(function () {
$('#div1').addClass('blinking');
});
$('#stop').click(function () {
$('#div1').removeClass('blinking');
});
});
.blinking {
animation: blinker 600ms linear infinite alternate;
}
#keyframes blinker { to { opacity: 0; } }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="start">Click to fade in/out box</button>
<button id="stop">Click to stop</button><br /><br /><br />
<div id="div1" style="width:80px;height:80px;background-color:red;"></div>
In jQuery there are some global ajax events.
You may listen for ajaxStart, ajaxComplete like in:
$(function () {
$( document ).ajaxStart(function() {
// Start your animation
});
$( document ).ajaxComplete(function() {
// End your animation
});
});
My snippet:
// utility function to wait (simulate ajax)
$.wait = function(ms) {
var defer = $.Deferred();
setTimeout(function() { defer.resolve(); }, ms);
return defer;
};
var isAjaxEnded = true;
$(function () {
$("#div1").click(function(){
$(this).fadeToggle("slow", function() {
if (!isAjaxEnded)
$("#div1").trigger('click');
});
});
$( document ).ajaxStart(function() {
isAjaxEnded = false;
$("#div1").trigger('click');
});
$( document ).ajaxComplete(function() {
// the next line is commented because I'm simulating...
//isAjaxEnded = true;
// End your animation
});
$.getJSON('https://api.github.com/users').done(function(data) {
// just wait only 3 seconds
$.wait(3000).then(function() {
isAjaxEnded = true;
});
});
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<div id="div1" style="width:80px;height:80px;background-color:red;"></div>
You can use SetInterval to run the on off cycle continuously and end it with ClearInterval.
var _timer1;
var _timer2;
$(document).ready(function(){
$("#BtnStart").click(function(){
_timer1 = setInterval(function(){ $("#div1").fadeToggle("slow"); }, 500);
_timer2 = setInterval(function(){ $("#div1").fadeToggle("slow"); }, 1000);
});
//Call stop stop annimation
$("#BtnStop").click(function(){
clearInterval(_timer1);
clearInterval(_timer2);
});
});

Move/duplicate an element to another place on click with jQuery

I have a row of five boxes. When you click on any except the first one, the clicked box fades out, the ones before it slide to the right, and a new box appears on the far left as the new first element.
1) Instead of prepending the body with the div with classes "primaryfade," "primary," and "box", I'd rather prepend with the element I just clicked without the class "fade-out" but with new classes "primary" and "primary-fade" (while still retaining the class "box").
2) In my fiddle I realize that any box that previously had the class "primary" and then moved to a non-first position no longer triggers the animation if clicked on again. I don't know why that is, but I'd like any element to move back to the first position on click regardless.
I'm sure my jQuery can be written more elegantly. I'm not very experienced with it. This is for proof of concept.
http://jsfiddle.net/q6rtgh79/3/
HTML -
<div class="primary box">1</div>
<div class="box">2</div>
<div class="box">3</div>
<div class="box">4</div>
<div class="box">5</div>
CSS -
body {border:1px solid;}
.box {color:white;font-weight:bold;transition: opacity 1s, background 1s;display:inline-block;width: 40px;height:40px;background: gray;margin-left: 20px;}
.box:first-child {margin:0;}
.box4 {background: pink;}
.allmove .box {transition: transform .5s ease-in-out;transform: translate3d(150%,0,0);}
.allmove .fade-out ~ .box, .primary, .primary ~ .box {
transform: translate(0,0)!important;}
.primary {background:green;}
.fade-out, .primaryfade {opacity: 0;}
jQuery -
$(function() {
$(".box:not(:first-child)").click(function() {
$(this).addClass("fade-out");
$(".primary").removeClass("primary");
setTimeout(function() {
$("body").addClass("allmove");
}, 1000);
setTimeout(function() {
$("body").prepend("<div class=\"primaryfade primary box\">new</div>");
}, 1500);
setTimeout(function() {
$("div[class*='fade-out']").remove();
}, 1500);
setTimeout(function() {
$("body").removeClass("allmove");
}, 1500);
setTimeout(function() {
$("[class*='primaryfade']").removeClass("primaryfade")
}, 2000);
});
});
I Agree with Rohan, but to solve you first point of ", I'd rather prepend with the element I just clicked" instead of
setTimeout(function () {
$("body").prepend("<div class=\"primaryfade primary box\">new</div>");
$("div[class*='fade-out']").remove();
$("body").removeClass("allmove");
}, 1500);
use
var item = $(this);
setTimeout(function (item) {
$("body").prepend(item.removeClass('fade-out').addClass('primaryfade').addClass('primary').addClass('box').html('new'));
$("div[class*='fade-out']").remove();
$("body").removeClass("allmove");
}, 1500, item);
This will:
prepend the current item you clicked on
remove the fade-out class
add the primary and primaryfade and box classes
update the text to 'new'
I think you should use on() for dynamically added boxes like,
$(document).on('click',".box:not(:first-child)",function() {
....
....
});
It will solve your second point as well as first issue. See updated fiddle
You can merge the animation for 1500 seconds like,
$(function () {
$(document).on('click', ".box:not(:first-child)", function () {
$(this).addClass("fade-out");
$(".primary").removeClass("primary");
setTimeout(function () {
$("body").addClass("allmove");
}, 1000);
// merge the functions which are called after 1500ms
setTimeout(function () {
$("body").prepend("<div class=\"primaryfade primary box\">new</div>");
$("div[class*='fade-out']").remove();
$("body").removeClass("allmove");
}, 1500);
setTimeout(function () {
$("[class*='primaryfade']").removeClass("primaryfade")
}, 2000);
});
});
Updated Fiddle
use something like this :-
$(function() {
function clickEvent(){
$(".box:not(:first-child)").off("click");
$(".box:not(:first-child)").on("click",function() {
console.log('here')
$(this).addClass("fade-out");
$(".primary").removeClass("primary");
setTimeout(function() {
$("body").addClass("allmove");
}, 1000);
setTimeout(function() {
$("body").prepend("<div class=\"primaryfade primary box\">new</div>");
clickEvent();
}, 1500);
setTimeout(function() {
$("div[class*='fade-out']").remove();
}, 1500);
setTimeout(function() {
$("body").removeClass("allmove");
}, 1500);
setTimeout(function() {
$("[class*='primaryfade']").removeClass("primaryfade")
}, 2000);
});
}
clickEvent()
});
here is the link http://jsfiddle.net/q6rtgh79/5/

hide a textbox if mouseleave beyond a certain time in jQuery

I have to hide a textbox only if the user hovers out > 2 seconds.
<div id="content">
<input type="text" id="txt1" />
</div>
$('#content').on('mouseleave', function(){
$('#txt1').delay(2000).hide();
});
This will wait for 2 seconds before hiding the textbox. But if the user comes back within 2 seconds it will still hide. How to prevent that from happening?
Use setTimeout/clearTimeout instead:
var clr;
$('#content').on('mouseleave', function () {
clr = setTimeout(function () {
$('#txt1').hide();
}, 2000)
}).on('mouseenter', function () {
clearTimeout(clr)
})
Also note that the delay in your example won't work at all since the .delay() method delays the execution of functions that follow it in the standard effects queue or with a custom queue. It won't delay the no-arguments forms of .show() or .hide() which do not use the effects queue.
jsFiddle example
Use the good ol' fashion setTimeout and clearTimeout
var leaveTimeout;
$('#content').on('mouseleave', function() {
leaveTimeout = setTimeout(function() {
$('#txt1').hide();
}, 2000);
})
.on('mouseenter', function() {
clearTimeout(leaveTimeout);
});
How about a simpler CSS solution: http://jsfiddle.net/2Jtrb/2/.
HTML:
<div id="content">
<input type="text" id="txt1" />
</div>
CSS:
div {
outline: 1px dotted #000;
}
div > input {
visibility: hidden;
-webkit-transition: visibility 2s;
transition: visibility 2s;
}
EDIT: the input will also stay visible if it is focused.
div:hover > input, input:focus {
visibility: visible;
transition-duration: 0s;
}
Try this...
var theTimer;
$('#content').on('mouseleave', function(){
theTimer = setTimeout(function() {
$('#txt1').hide();
}, 2000);
});
$('#content').on('mouseenter', function(){
clearTimeout(theTimer);
});
DEMO
If you use setTimeout you can cancel the timeout if the user enters the text area again. That code looks something like:
var timeoutHandle;
$('#content').on('mouseleave', function(){
timeoutHandle = setTimout(
function () {
timeoutHandle = undefined;
$('#txt1').hide();
}, 2000);
});
$('#content').on('mouseenter', function(){
if (timeoutHandle) clearTimeout(timeoutHandle);
});
By the way, this is similar to what other plugins provide so you might consider looking at the hover intent plugin here: http://cherne.net/brian/resources/jquery.hoverIntent.html.
You can try this:-
var typingTimer;
$('#content').on('mouseleave', function(){
typingTimer = setTimeout(function(){
$('#txt1').hide();
},2000);
});
$('#content').on('mouseenter', function(){
clearTimeout(typingTimer);
});
Use setTimeout function.
var timeout = null;
$('#content').on('mouseleave', function() {
timeout = setTimeout(function() { $('#text1').hide();
});
Then when the user enters the div, clear the timeout.
$('#content').on('mouseenter', function() {
clearTimeout(timeout);
});
I wrote this without looking anything up, so I hope I didn't messed up ;)

How to add delay to jquery mouseover? [duplicate]

This question already has answers here:
Delay jquery hover event?
(6 answers)
Closed 7 years ago.
I have a bunch of images on one page and I am using the following to trigger an event:
$('.img').on('mouseover', function() {
//do something
});
Is there some way to add a delay such that if a user hovers for maybe 1 second, then it does "//do something" or actually triggers the "mouseover" event?
You can use setTimeout
var delay=1000, setTimeoutConst;
$('.img').on('hover', function() {
setTimeoutConst = setTimeout(function() {
// do something
}, delay);
}, function() {
clearTimeout(setTimeoutConst);
});
You could do that using a setTimeout along with a clearTimeout if the user leaves too soon:
var timer;
var delay = 1000;
$('#element').hover(function() {
// on mouse in, start a timeout
timer = setTimeout(function() {
// do your stuff here
}, delay);
}, function() {
// on mouse out, cancel the timer
clearTimeout(timer);
});
Use a timer and clear it when they mouseout incase they leave within 1000ms
var timer;
$('.img').on({
'mouseover': function () {
timer = setTimeout(function () {
// do stuff
}, 1000);
},
'mouseout' : function () {
clearTimeout(timer);
}
});
I was looking for something like this as well, but with a secondary delay as well. I took one of the answers here and expanded upon it
This example shows a div after X seconds of mouseover and hides it after X seconds of mouseout. But disables if you hover over the shown div.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<style type="text/css">
.foo{
position:absolute; display:none; padding:30px;
border:1px solid black; background-color:white;
}
</style>
<h3 class="hello">
<a href="#">Hello, hover over me
<span class="foo">foo text</span>
</a>
</h3>
<script type="text/javascript">
var delay = 1500, setTimeoutConst,
delay2 = 500, setTimeoutConst2;
$(".hello").mouseover(function(){
setTimeoutConst = setTimeout(function(){
$('.foo').show();
},delay);
}).mouseout(function(){
clearTimeout(setTimeoutConst );
setTimeoutConst2 = setTimeout(function(){
var isHover = $('.hello').is(":hover");
if(isHover !== true){
$('.foo').hide();
}
},delay2);
});
</script>
Working example
You can use jquery .Delay like this (not tested):
$("#test").hover(
function() {
$(this).delay(800).fadeIn();
}
);
http://api.jquery.com/delay/

Categories

Resources