Reset slide interval JQuery - javascript

I've made a slide show width a javascript and Jquery. But I need to reset the slide interval when the user is navigating manualy to the next or previous slide. I am relatively new to javascipt and it's syntax. Any help will be appriciated. Here is my code:
<script type="text/javascript" src="/elements/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
var currentSlideId = 0;
var slidesAmount = 0;
function selectSlide(id) {
jQuery(".startpage-test.slide" + id).show().siblings(".startpage-test").hide();
jQuery(".slideshow-show-active.slide" + id).addClass("active").siblings(".slideshow-show-active").removeClass("active");
}
function nextSlide() {
currentSlideId++;
if (currentSlideId >= slidesAmount) currentSlideId = 0;
selectSlide(currentSlideId);
}
function prevSlide() {
currentSlideId--;
if (currentSlideId < 0) currentSlideId = slidesAmount - 1;
selectSlide(currentSlideId);
}
jQuery(document).ready(function() {
slidesAmount = jQuery(".startpage-test").length;
jQuery(".show_previous").click(function() {
prevSlide();
return false;
});
jQuery(".show_next").click(function() {
nextSlide();
return false;
});
window.setInterval(function() {
nextSlide();
}, 7000);
});
jQuery("object.flashContent").each(function () {
swfobject.registerObject(jQuery(this).attr("id"), "9.0.0");
});
</script>
The next-/prev-button looks like this:
<div class="show_next">
<span class="slide_nav"><img src="/elements/next.png" width="57" alt="Next"></span>
</div>
<div class="show_previous">
<span class="slide_nav"><img src="/elements/prev.png" width="57" alt="Previous"></span>
</div>
In all slides there is a link of course, and it would also be nice to stop the slide interval when hovering this a-tag. Unfortunately I don't know how to do this either.

You can assign the result of setInterval() to a variable, then call clearInterval() passing in that variable whenever you need. So in your case, change this code:
window.setInterval(function() {
nextSlide();
},
to this:
var interval = window.setInterval(function() {
nextSlide();
},
Then, in any.hover(), .mouseenter(), .click() or whatever other mouse event handler you are using, simply call:
window.clearInterval(interval);
Of course, you need to reinstate the interval when you want to restart it!

Related

Iterate through list of url's with start and Stop button

I have a list of URL's and i need it to run as slide show on Start and Stop Of button. Currently it is running as a slideshow with out start and stop button.
Additionally I need to design a homepage with thumbnail of all those URL's.On click of thumbnail it has to redirect to that page
<html>
<head>
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
$(function () {
var urls = ["URL1", "URL2", "URL3","URL4", "URL5", "URL6","URL7", "URL8", "URL9"];
var i = 0;
function loadIframe(url)
{
$('#iframe').attr('src', url);
}
setInterval(function() {
// update the index
i = (i + 1) % urls.length;
loadIframe(urls[i]);
}, 13000);
loadIframe(urls[i]);
});
</script>
</head>
<body>
<iframe id="iframe" height="100%" width="100%"></iframe>
</body>
</html>
You need to trigger the setInterval and save it, to clear it later.
var intvl = false; //Global Variable
$('#StartButton').on('click', function()
{
(!intvl) ? intvl = setInterval(...) : return;
});
$('#StopButton').on('click', function()
{
clearInterval(intvl);
intvl = false;
});
EDIT: changed to disable multiple intervals
You can achieve this by storing setInterval in a variable so that you can use clearInterval() on it. clearInterval() will allow you to stop/pause the setInterval you created.
You also don't need the $(function() {...}) component anymore as you will be the one controlling when the slider starts/stops:
var slideInterval;
var urls = ["URL1", "URL2", "URL3", "URL4", "URL5", "URL6", "URL7", "URL8", "URL9"];
var i = 0;
function loadIframe(url) {
//$('#iframe').attr('src', url);
$('#iframe').html(url);
}
function start() {
if (!slideInterval) { // If an interval is already in-use (ie if the slider is running) don't allow another slider to be made -> continue using the current one.
slideInterval = setInterval(function() {
// update the index
i = (i + 1) % urls.length;
loadIframe(urls[i]);
}, 1000);
}
}
function stop() {
if (slideInterval) { // If an interval doe exsist, we can then clear it, if it doesn't exsist then we have no interval to "clear", and so we don't run this code if one isn't in use
clearInterval(slideInterval);
slideInterval = null;
}
}
loadIframe(urls[0]);
#iframe {
border: 1px solid black;
}
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<div id="iframe" height="100%" width="100%"></div>
<button onclick="start()">Start</button>
<button onclick="stop()">Stop</button>

Show reset button after counter reaches zero

I would like to hide and then show the "Reset" button as soon as the counter reaches zero.
Index.html:
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
</script>
<script type="text/javascript" src="countdown.js"></script>
</head>
<body>
<input type="text" id="timer">
<script type="text/javascript">
timer = new Countdown();
timer.init();
</script>
<button id="reset">Reset</button>
<script type="text/javascript">
$("#reset").click(function(){
//timer = new Countdown();
timer.reset();
});
</script>
</body>
</html>
Please see http://jsfiddle.net/orokusaki/o4ak8wzs/1/ for countdown.js
AWolf's answer is a bit fancier than mine, and they made some good points about your code, but I tried to keep mine simple and tried not to change your original code too much.
Your init() function will now hide the Reset button, and I had the update_target() function show the Reset button when the timer expired.
Fiddle: http://jsfiddle.net/rgutierrez1014/o4ak8wzs/4/
In this jsFiddle you'll find the updated code and how you could add that behaviour.
I've also improved your code a bit. It's easier to write Countdown.prototype = { init: function() {...}, ...} then writing Countdown.prototype.init = function() {...}
I also changed your setInterval to setTimeout and start a new timeout every second. That's easier and you don't need to clear the interval at the end. Also the callback function for your interval seemed a bit strange and that probably won't work.
You could add your click handlers in the init method of your countdown object like this $('#start').click(this.start.bind(this)); the .bind(this) is used to change the context inside the click handler to the currently used object. Then this inside of the handler is your object and you can access everything with this.
To hide the reset button at start I've used the css display: none; and if you are at zero then show the button with $('#reset').fadeIn('slow'); or $('#reset').show(); if you don't want the animation.
Update 13.03.2015
As mentioned in the comments I've improved the code and now I'm using a jQuery Countdown plugin.
Please have a look at the latest version in this jsFiddle.
I think it's much better then the other code.
(function () {
function Countdown() {
this.start_time = "00:30";
this.target_id = "#timer";
//this.name = "timer";
}
Countdown.prototype = {
init: function () {
console.log('init called');
this.reset();
$('#start').click(this.start.bind(this));
$('#reset').click(this.reset.bind(this));
},
reset: function () {
time = this.start_time.split(":");
//this.minutes = parseInt(time[0]);
this.seconds = parseInt(time[1]);
this.update_target();
},
tick: function () {
if (this.seconds > 0) //|| this.minutes > 0)
{
if (this.seconds == 0) {
// this.minutes = this.minutes - 1;
this.seconds = 59
} else {
this.seconds = this.seconds - 1;
}
this.start();
}
else {
// show reset button
$('#reset').fadeIn('slow');
}
this.update_target();
},
start: function() {
console.log('start called');
//setTimeout(this.name + '.tick()', 1000);
setTimeout(this.tick.bind(this), 1000);
},
update_target: function () {
seconds = this.seconds;
if (seconds < 10) seconds = "" + seconds;
$(this.target_id).val(this.seconds);
}
};
var counter = new Countdown();
counter.init();
})();
#reset {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="timer">
<button id="start">Start</button>
<button id="reset">Reset</button>

Javascript Text Slideshow Start from Beginning on Hover

I have added a text slideshow to a div that is called by JQuery on hover. How do I get the slideshow to start from the beginning each time the user hovers on the div? Right now it just continues to loop after the first time it is activated.
Thanks in advance!
<script>
$(document).ready(function(){
$('#mercury .infos').hover(
function () {
if($("a.active").is('.mercury')){
$("#descriptionls").fadeIn("2000");
};
var quotes = [
"Who’s the one who’s always there when that keeps happening?",
"Learn to dismantle self-defeating behaviors",
"JOIN THE FLOW TODAY",
];
var i = 0;
setInterval(function() {
$("#lstextslide").html(quotes[i]);
if (i == quotes.length)
i=0;
else
i++;
}, 1 * 4000);
});
});
</script>
You have to cancel the previous interval and call the function that updates the HTML immediately. See http://jsfiddle.net/xozL96fj/
$(document).ready(function(){
var intervalTimer = null;
$('#mercury .infos').hover(
function () {
if($("a.active").is('.mercury')){
$("#descriptionls").fadeIn("2000");
}
if (intervalTimer !== null) {
clearInterval(intervalTimer);
}
var quotes = [
"Who’s the one who’s always there when that keeps happening?",
"Learn to dismantle self-defeating behaviors",
"JOIN THE FLOW TODAY",
];
var i = 0;
function update() {
$("#lstextslide").html(quotes[i]);
i = (i + 1) % quotes.length;
}
// Call it immediately, don't wait until the interval
update();
intervalTimer = setInterval(update, 4000);
});
});
You need to make a check if your slider has already been activated. If you hover over your slider when the slider is already active, you will have to reset $i, and call setInterval() again.

jQuery setInterval too fast when tab is inactive

When the tab my website is on is inactive, my slideshow starts switching pictures too fast and mess the whole thing up.
Is there a way i could fix this?
var img_src = ["1.png", "2.png", "3.png", "4.png"];
var delay = 8000;
var first_run = true;
function switch_pic(position){
$("#show").attr("src", img_src[position]).fadeOut(0).fadeIn(4000).fadeOut(4000);
}
$(document).ready(function(){
var i = 0;
if(first_run){
switch_pic(i);
first_run = false;
i++;
}
window.setInterval(function(){
switch_pic(i);
delay += 8000;
i++;
if(i > 3){
i = 0;
window.clearInterval();
}
}, delay);
});
Could wrap the code in this:
$(document).ready(function(){
$([window, document]).focusin(function(){
//code run when tab is selected
}).focusin(function(){
//code to stop all animation
});
});
That would only let the slideshow run when the user is viewing your site.
I'm not sure why things speed up. Normally the timers on background tabs will be slowed down to at least one second, but this shouldn't affect your scenario. I suggest using console.log() to track the calls to your functions.
Also, you can simplify your main loop a bit:
$(document).ready(function(){
var i = 0;
window.setInterval(function(){
switch_pic(i++); // increase i after call
if(i > 3) i = 0; // reset i
}, 8000);
});
I think that the answer good for actual version of jQuery should look like this:
var intervalId;
$([window, document]).on('focusin', function(){
intervalId = setInterval(function() {
// Action in interval
}, 3000);
}).on('focusout', function(){
if (intervalId) {
clearInterval(intervalId);
}
});
Pleas remember, that first time your 'focusin' is not tigger when page is loaded, so you should use this construction for this:
intervalFunction();
$([window, document]).on('focusin', function(){
if (!intervalId){
intervalFunction();
}
}).on('focusout', function(){
if (intervalId) {
clearInterval(intervalId);
intervalId = undefined;
}
});
function intervalFunction() {
// Your function hire
}

Making tabs automatically rotate?

I am not very proficient in JS and would like to help me with an issue I have.
I want to make the tabs on a Drupal website automatically rotate but still the user to be able to click on them.
This is the code I have:
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script type="text/javascript">
$('ul.checklist-select li').click(function () {
var selectID = $(this).attr('id');
$('ul.checklist-select li').removeClass('active');
$(this).addClass('active');
$('.first-box, .second-box, .third-box, .fourth-box').fadeOut(300);
$('.' + selectID + '-box').delay(300).fadeIn(300);});
</script>
I tried few options but it wasn't working.Thanks very much! I appreciate your time and help.
Well, you want to add an interval that updates the view and rotates to the next one (or first if it's the last).
Try this (not tested):
<script type="text/javascript">
var index = 0, // Index of current tab
interval = setInterval(function () { rotate(); }, 5000), // Interval
$tabs = $('ul.checklist-select'),
$content = $('.checklist_wrap');
// Click handler
$('ul.checklist-select li').each(function (i) {
$(this).click(function () {
index = i;
switchElement();
});
});
function rotate() {
// Update index to next one
index++;
// Check if this is a valid index, or reset to 0
if (index >= $tabs.children('li').length)
index = 0;
switchElement();
}
function switchElement() {
clearInterval(interval);
// Remove class from current tab
$('ul.checklist-select li').removeClass('active');
$('.checklist_wrap .box').fadeOut(300);
// Show
$tabs.children('li').eq(index).addClass('active');
$content.children('.box').eq(index).delay(300).fadeIn(300);
// Reset interval
interval = setInterval(function () { rotate(); }, 5000);
}
</script>
Something you might want to add is that the interval is reset when someone clicks a tab.

Categories

Resources