How do I pause and resume with a fadeLoop? - javascript

I have a show and hide div fade loop that I am using like a short interactive tutorial with tips. I can get the divs to cycle through in order; however, I would like to add a pause button inside of each tip that pauses the loop, with the ability to resume. How do I add that functionality into my script?
Here is my js:
$(document).ready(function(){
fadeLoop()
function fadeLoop() {
var counter = 0,
divs = $('.fader').css('visibility','visible').hide(),
dur = 100;
function showDiv() {
$("div.fader").fadeOut(dur) // hide all divs
.filter(function(index) {
return index == counter % divs.length;
}) // figure out correct div to show
.delay(dur) // delay until fadeout is finished
.fadeIn(dur); // and show it
counter++;
}; // function to loop through divs and show correct div
showDiv(); // show first div
return setInterval(function() {
showDiv(); // show next div
}, 4 * 1000); // do this every 4 seconds
};
$(function() {
var interval;
$("#start").click(function() {
if (interval == undefined){
interval = fadeLoop();
$(this).val("Stop");
}
else{
clearInterval(interval);
$(this).val("Start");
interval = undefined;
}
});
});
});
And here is my fiddle: Updated Fiddle

I have solved by using a global variable window.i as the counter
function fadeLoop() {
var divs = $('.fader').hide(),
dur = 200;
function showDiv() {
divs.fadeOut(dur) // hide all divs
.filter(function(index) {
return index == window.i % divs.length;
}) // figure out correct div to show
.delay(dur) // delay until fadeout is finished
.fadeIn(dur); // and show it
window.i++;
}; // function to loop through divs and show correct div
showDiv(); // show first div
return setInterval(function() {
showDiv(); // show next div
}, 1 * 1000); // do this every 5 seconds
};
$(function() {
var interval;
window.i = 0;
$("#start").click(function() {
if (interval == undefined){
interval = fadeLoop();
$(this).val("Stop");
}
else{
clearInterval(interval);
$(this).val("Start");
interval = undefined;
}
});
});

Related

Run a setInterval function, stop it for 3 seconds and continue running it

I have a setInterval function going trough some div classes, if it finds a div with a particular class it should stop for 3 seconds and then continue running. Notice how I am using:
clearInterval(myInterval);
but I need something else, to start the sequence again or make it to continue running from there.
e.g:
var myInterval = setInterval(function() {
move.removeClass( "girlFromRight" );
runFromRight -= 9;
move = $("#grid"+ runFromRight);
move.addClass("girlFromRight");
if (move.hasClass("man") === true ||
move.hasClass("man-right") === true ||
move.hasClass("man-left") === true )
{
clearInterval(myInterval);
move.addClass('inLove');
move.removeClass('girlFromRight');
setTimeout(function() {
move.removeClass('inLove');
move.addClass('man');
}, 3000);
}
if (c == 9){
clearInterval(myInterval);
}
}, 300);
keyPressed = false;
}, randomTime);
}
Consider using setTimeout and setting the interval (300 or 3000) after each run based on a test. That way you don't have to start and stop setInterval.
A quick example is below, it highlights each div in sequence, pausing longer on any where the text content is evenly divisible by 3 (as an example test).
function doLoop(){
var divs = document.querySelectorAll('div');
var i = 0;
function loop(){
var selected = document.querySelectorAll('.selected');
[].forEach.call(selected,function(el) {
el.className = 'notSelected';
});
divs[i].className = 'selected';
setTimeout(loop, divs[i].textContent % 3? 300 : 3000);
i = ++i % (divs.length - 2);
}
loop();
}
window.onload = doLoop;
.notSelected{}
.selected{
background-color: blue;
}
<div class="notSelected">0</div>
<div class="notSelected">1</div>
<div class="notSelected">2</div>
<div class="notSelected">3</div>
<div class="notSelected">4</div>
<div class="notSelected">5</div>

how to make hide/show text javascript smoother?

I am using this script to hide and show text however, I want to make the transition smoother but I am not sure how to. Here's a demo of it: http://jsfiddle.net/LnE5U/.
Please help me change it to make it smoother.
hide/show text
<div id="showOrHideDiv" style="display: none">hidden text</div>
<script language="javascript">
function showOrHide()
{
var div = document.getElementById("showOrHideDiv");
if (div.style.display == "block")
{
div.style.display = "none";
}
else
{
div.style.display = "block";
}
}
</script>
Here is an example using jQuery's fadeToggle (a shortcut for a more complicated animate)
// assuming jQuery
$(function () { // on document ready
var div = $('#showOrHideDiv'); // cache <div>
$('#action').click(function () { // on click on the `<a>`
div.fadeToggle(1000); // toggle div visibility over 1 second
});
});
HTML
<a id="action" href="#">hide/show text</a>
<div id="showOrHideDiv" style="display: none;">hidden text</div>
DEMO
An example of a pure JavaScript fader. It looks complicated because I wrote it to support changing direction and duration mid-fade. I'm sure there are still improvements that could be made to it, though.
function generateFader(elem) {
var t = null, goal, current = 0, inProgress = 0;
if (!elem || elem.nodeType !== 1) throw new TypeError('Expecting input of Element');
function visible(e) {
var s = window.getComputedStyle(e);
return +!(s.display === 'none' || s.opacity === '0');
}
function fader(duration) {
var step, aStep, fn, thisID = ++current, vis = visible(elem);
window.clearTimeout(t);
if (inProgress) goal = 1 - goal; // reverse direction if there is one running
else goal = 1 - vis; // else decide direction
if (goal) { // make sure visibility settings correct if hidden
if (!vis) elem.style.opacity = '0';
elem.style.display = 'block';
}
step = goal - +window.getComputedStyle(elem).opacity;
step = 20 * step / duration; // calculate how much to change by every 20ms
if (step >= 0) { // prevent rounding issues
if (step < 0.0001) step = 0.0001;
} else if (step > -0.0001) step = -0.0001;
aStep = Math.abs(step); // cache
fn = function () {
// console.log(step, goal, thisID, current); // debug here
var o = +window.getComputedStyle(elem).opacity;
if (thisID !== current) return;
if (Math.abs(goal - o) < aStep) { // finished
elem.style.opacity = goal;
if (!goal) elem.style.display = 'none';
inProgress = 0;
return;
}
elem.style.opacity = (o + step).toFixed(5);
t = window.setTimeout(fn, 20);
}
inProgress = 1; // mark started
fn(); // start
}
return fader;
}
And using it
window.addEventListener( // this section matches the code above
'load',
function () {
var fader = generateFader(document.getElementById('showOrHideDiv'));
document.getElementById('action').addEventListener(
'click',
function () {
fader(1000);
}
);
}
);
DEMO of this
This is quite simple. I have just made a demo and i used setInterval
Here's how it works
var fadeout = function( element ) { // 1
element.style.opacity = 1; // 2
window.setInterval(function() { // 3
if(element.style.opacity > 0) { // 4
element.style.opacity = parseFloat(element.style.opacity - 0.01).toFixed(2); // 5
} else {
element.style.display = 'none'; // 6
}
}, 50);
};
JSFiddle Demo Link
Steps
Create a function that accepts a DOM element
Set the opacity of the element to 1
Create a function that loops every 50ms
If the opacity is greater than 0 -> continue
Take away 0.01 from the opacity
if it's less than 0 the animation is complete and hide it completely
Note this is a really simple example and will need a bit of work
You can use somthing like this
$('.showOrHideDiv').toggle(function() {
$('showOrHideDiv').fadeIn('slow', function() {
//fadeIn or fadeOut, slow or fast, all the stuffs you want to trigger, "a function to execute every odd time the element is clicked," says the [jquery doc][1]
});
}, function() {
//here comes "additional handlers to cycle through after clicks," says the [jquery doc][1]
});
I used OPACITY to make it show/hide. See this Example, Full code (without jQuery):
Click here
<div id="MyMesage" style="display:none; background-color:pink; margin:0 0 0 100px;width:200px;">
blablabla
</div>
<script>
function ShowDiv(name){
//duration of transition (1000 miliseconds equals 1 second)
var duration = 1000;
// how many times should it should be changed in delay duration
var AmountOfActions=100;
var diiv= document.getElementById(name);
diiv.style.opacity = '0'; diiv.style.display = 'block'; var counte=0;
setInterval(function(){counte ++;
if ( counte<AmountOfActions) { diiv.style.opacity = counte/AmountOfActions;}
},
duration / AmountOfActions);
}
</script>
I followed iConnor solution and works fine but it had a small issue setInterval will not stop after the element be hidden I added stop interval to make it better performance
var fadeout = function( element ) { // 1
element.style.opacity = 1; // 2
let hidden_process = window.setInterval(function() { // 3
if(element.style.opacity > 0) { // 4
element.style.opacity = parseFloat(element.style.opacity - 0.01).toFixed(2); // 5
} else {
element.style.display = 'none'; // 6
console.log('1');
clearInterval(hidden_process);
}
}, 50);
};

show div after click and start timer

want to show a div after click on a button and then the time start and count from 10 to 0 .
my probelm is i don't know how to start count ?
javascript :
<script>
$("button").click(function() {
$('div#test').hide().delay(200).fadeIn('slow');
});
</script>
button :
<div id="test" style="display:none;">click</div>
html :
<div id="test" style="display:none;">here you are !</div>
You can use setInterval for counting.
var count = 10;
var temp = setInterval(function(){
if(count < 0) {
clearInterval(temp);
}
// show count
count--;
}, 1000);
You can use either setTimeout() or setInterval() to get it working:
Below is how I did it:
$(function() {
$("button").click(function() {
function counter() {
var i = 10;
$("body").append('<div style="border:1px solid red;">Div Created on the Fly</div>')
function showDIV() {
if (i < 0)
return
setTimeout(showDIV, 1000);
$("span").text(i);
i--;
}
showDIV();
}
counter(10);
});
});
DEMO
var count = 15;
var timerID = 0;
$("button").click(function() {
$('div#test').hide().delay(200).fadeIn('slow', function() {
timerID = setInterval(function() {countDown();}, 1000); // count every 1000 ms, change this to whatever you want
});
$("#wait").show(); // or you could fade this in if you want. Maybe that's what you intended with #test.
});
function countDown() {
count--;
$("#count").text(count);
// do whatever you want to do with your count
if (count <= 0) {
clearInterval(timerID);
}
}
HTML:
<p id="wait" style="display:none">Please wait<span id="count">15</span> seconds...</p>
Assuming you wanted to start the count down after the fadeIn. Otherwise, just pull that piece out and setInterval after the fadeIn line which will start the countdown when the button is first clicked.

jQuery pause function on hover?

I have a jQuery/JS function that is using setInterval to loop through some image slides I have. It just flips through every 5 seconds...
Now I want it to pause if my mouse is hovered over it. How do I go about doing that on the setInterval function?
var current = 1;
function autoAdvance() {
if (current == -1) return false;
jQuery('#slide_menu ul li a').eq(current % jQuery('#slide_menu ul li a').length).trigger('click', [true]);
current++;
}
// The number of seconds that the slider will auto-advance in:
var changeEvery = jQuery(".interval").val();
if (changeEvery <= 0) {
changeEvery = 10;
}
var itvl = setInterval(function () {
autoAdvance()
}, changeEvery * 1000);
Something like this would work assuming interval is defined in an outer scope:
$('.slideshow img').hover(function() {
interval = clearInterval(interval);
}, function() {
interval = setInterval(flip, 5000);
});
(function () {
var imgs = $('#your_div img'), index = 0, interval,
interval_function = function () {
imgs.eq(index).hide();
index = (index + 1) % imgs.length;
imgs.eq(index).show();
};
imgs.eq(0).show();
interval = setInterval(interval_function, 5000);
$('#your_div').hover(function () {
clearInterval(interval);
}, function () {
interval = setInterval(interval_function, 5000);
});
}());
Example: http://jsfiddle.net/Zq7KB/3/
I reused some old code I wrote for a question the other day, but I figured it didn't matter that much. The trick is to store your interval in a variable that you keep in the background. Then, when you hover over the container, clear the interval. When you hover out of the container, re-set the interval. To get a better feel of how this works, change those 5000s to 1000s so it passes more quickly for testing.
Hope this helps.

How can i stop this countdown on mouseleave?

Here is the code:
//Mouseover start countdown
$("#icon_no_1").mouseover(function()
{
$(this).fadeTo("slow", 0.23);
//Countdown
var counter = 0;
var interval = setInterval(function() {
counter++;
// Display 'counter' wherever you want to display it.
if (counter == 1) {
//Display 1
$('#login_icon_1').fadeIn();
//Fade in
}
if (counter == 2) {
//Display 2
$('#login_icon_1').fadeOut(750);
//Fade in login icon 2
$('#login_icon_2').fadeIn();
}
if (counter == 3) {
//Display 3
//Display 2
$('#login_icon_2').fadeOut(500);
//Fade in login icon 2
$('#login_icon_3').fadeIn();
}
if (counter == 4) {
//Display 4
//Display 2
$('#login_icon_3').fadeOut(500);
//Fade in login icon 2
$('#login_icon_4').fadeIn();
}
if (counter == 5) {
//Display 2
$('#login_icon_4').fadeOut(500);
//Fade in login icon 2
$('#login_icon_5').fadeIn();
//Display 2
$('#login_icon_5').fadeOut(1000);
}
if (counter == 6) {
counter = 7;
window.location.replace("/wahalu/index.php/login_advisor.php");
}
}, 1000);
}
);
$("#icon_no_1").mouseleave(function()
{
counter = 0;
$(this).fadeTo("slow", 1);
$('#login_icon_1').hide();
$('#login_icon_2').hide();
$('#login_icon_3').hide();
$('#login_icon_4').hide();
$('#login_icon_5').hide();
}
);
});
Another way to do it would be to take the variable out of the mouseover so that it can be shared with the mouseleave.
var interval; // <-- is in scope of both events now
$("#icon_no_1").mouseover(function()
{
$(this).fadeTo("slow", 0.23);
//Countdown
var counter = 0;
interval = setInterval(function() {
counter++;
// Display 'counter' wherever you want
// etc etc etc
Now the interval is accessible to mouseleave
$("#icon_no_1").mouseleave(function()
{
counter = 0;
clearInterval( interval )
// etc etc etc
It is not a global variable if you are running your code inside of $(document).ready()
Store the interval with the element, instead of this:
var interval = setInterval(function() {
//code
}, 1000);
Do this:
$.data(this, 'interval', setInterval(function() {
//code
}, 1000));
Then in your mouseleave handler, clear it using clearInterval(), like this:
$("#icon_no_1").mouseleave(function() {
clearInterval($.data(this, 'interval'));
counter = 0;
$(this).fadeTo("slow", 1);
$('#login_icon_1, #login_icon_2, #login_icon_3, #login_icon_4, #login_icon_5').hide();
});
This style of doing timeouts/intervals eliminates the global variables and if needed you can have a timeout/interval per element (instead of a global variable per timeout/interval, per element).

Categories

Resources