carousel setInterval autoplay not working - javascript

the code: http://jsfiddle.net/n2m4absf/ (wont be functional, this is linked for code display purposes). trying to use:
setInterval(function(){slideCard();}
, 5000);
this carousel is a div box that moves in -883px chunks of margin-left. i want it to scroll automatically (thinking set interval would be the logic to use) every 5 seconds or so.
i have other js that handles the on click functions for navigating the carousel manually, but i dont think they should be effecting the autoplay. they do however live in the same file as the above js.
just need to get autoplay working and not sure why my js isnt doing it.

There are multiple problems in the script.
The variable count is declared as local to the method so in every call it will get initiated to 0 causing the first if block to execute.
Since you have used different if blocks, each if blocks will get evaluated in each iteration, so only the value of the last block will be affected
Since you don't have a constant logic for the margin value, I think you can use an array of margin values like
var slide = $('div.inner > ul');
var count = 0,
margins = ['-883px', '-1686px', 0];
function slideCard() {
slide.css('margin-left', margins[count++ % 3]);
};
setInterval(function () {
slideCard();
}, 1000);

Related

How to add a second slideshow on the same webpage

I want my webpage to have two slideshows. I have one at the moment that works fine, but having trouble adding the second slideshow, as the images for the second slideshow appear outside of it.
I thought I could probably just copy and paste the code I did for the first slideshow and just change the div class names, but this did not work. I also have javascript controlling my slideshow but I didn't think copying the function I did for the first slideshow, would work for the second.
Can someone give me advice on how I can create the second slideshow using HTML, javascript and css?
Well, part of the key is to parameterize all of the required details - that is, don't hard-code things like the output container's id or that of the target image element if you decide to use a single image and change it's source.
Some approaches use an unordered-list and set it (with css) so only the first item is visible. Changing slides then becomes a matter of moving the li items around inside their container. I.e if one calls appendChild on the parent with the first li item as a parameter, it will be hidden since it's now the last li item and the 2nd item will now be the first and this will be the one displayed.
While the second approach is a little more straight forward, the 1st has the benefits of (0) not needing to know or care how many images there are - you simply move the first li item to be the last, or move the last one to be first and, (1) all the images are loaded at the start, so you don't get a small delay as each slide is shown for the first time and loaded.
Other approaches change the src of an image element.
I've utilized the second here. I've not bothered with prev/next buttons - this may mean this answer is beyond you at the moment. I would add prev/next functions inside the startSlideshow function and return the function itself - i.e return this;, rather than the id of the timer (which is to allow it to be stopped via clearInterval)
JS
function newEl(tag){return document.createElement(tag)}
function byId(id){return document.getElementById(id)}
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded(evt)
{
var slideshow1TimerId = startSlideshow( ['uqrsGpO.jpg', 'vote-pedro.jpg'], 'slide1', 3000 );
var slideshow2TimerId = startSlideshow( ['zS0lOud.jpg', 'tree.png', 's13.bmp'], 'slide2', 1000 );
}
function startSlideshow(imgNameArray, idOfContainer, msPerSlide)
{
var container = byId(idOfContainer);
var tgtImgElem = newEl('img');
container.appendChild(tgtImgElem);
var timerId = setInterval(setSlideImg, msPerSlide);
var slideIndex = 0;
var numSlides = imgNameArray.length;
function setSlideImg()
{
tgtImgElem.src = imgNameArray[slideIndex];
slideIndex++;
if (slideIndex >= numSlides)
slideIndex = 0;
}
return timerId;
}
CSS
#slide1 img, #slide2 img
{
height: 128px;
}
HTML
<div id='slide1'></div>
<div id='slide2'></div>

Generic code to fade in divs with particular class, remove function after first run

I'm trying to create a generic function that can be placed just once in my site and work across multiple pages, nice and lightweight.
I want to be able to make certain divs on the site fade-in when you reach 10px above them on the scroll.
I want to do this by simply adding the following attributes to my divs:
.fade-in-block
#specific-block-name
The idea is that I could go through the site, add this class and an ID, and the animation would work.
I almost have it working except for one thing, the scroll listening constantly continues to console.log after the function has been called. I don't like this as it feels like it's going to be constantly trying to apply the animation, which won't really be seen from the front-end but I feel the constant maths behind the scenes could slow stuff down.
Here is my jQuery:
$('body .fade-in-block').each(function(){
var block = '#'+$(this).attr('id');
console.log('Block class is = '+block);
var offset = $(block).offset().top;
var $w = $(window).scroll(function () {
if ($w.scrollTop() > offset - 10) {
console.log('reached block turn-on point for '+block);
$(block).removeAttr('id'); // remove the ID from the element so the script doesn't continue to find the element
// fade and rise animation here
}
});
});
And here is a JSFiddle. It works just fine, but once you hit the block you'll see it logs constantly every pixel scrolled.
I tried to remedy this by removing the selecting id from the element once the event has occurred, but it continues to run.
Scroll and resize events both have this problem and the solution is said to be debouncing. However, I've never actually gotten debouncing to work properly. Instead I typically create a sort of switch that is turned off once the scroll condition has activated. In your case, since you have multiple elements, you would need to assign a switch to each element.
$(window).on('scroll', function(){
$('.fade-in-block').each(function(){
var appear = $(this).attr('data-appeared');
if(!appear){
$(this).attr('data-appeared', true);
//do something to $(this)
}
})
})
Here I'm adding a data attribute after it has appeared and checking for it again once it has.

Dynamic SVG animation only works once

I have this animation setup to indicate which SVG was selected. The animation adds a svg:use element, and 3 animate or animateTransform elements within the svg:use element. Thanks to some great help here on SO I was able to get this working properly.
My new problem however is that the animation only works once as designed once. If a second element is selected, the animation appears to try to take place, as you can see the stroke-width increase, but the scale doesn't happen.
I thought this would be a simple fix by using a setTimeout to call a function and remove the svg:use after the animation completed. I wasn't so lucky.
An example of my problem can be seen here: http://codepen.io/JoeyCinAZ/pen/GHhbw
The function I wrote to remove the animation is here
setTimeout( function() {removeAnimation(objID)}, 5000);
function removeAnimation(objID) {
var useEl = document.getElementById(objID);
useEl.nextSibling.remove();
}
You've two issues within the animation. The simplest is duration, it can't per the SVG specification begin with a . so
flash.setAttributeNS(null, 'dur', '.5s');
is strictly speaking not valid and Firefox rejects it. I believe there are plans to change the SVG specification to match Chrome's laxer behaviour but until that happens write it as
flash.setAttributeNS(null, 'dur', '0.5s');
Secondly your main issue is that once you run the animation the document timeline goes from 0 to 5.5 seconds (that's how long all your animations take). The next time you create the animation, the document timeline is therefore at 5.5 seconds and the initial animation doesn't run because it's in the past as it's supposed to start at 0s. You could solve this either by
a) calling setCurrentTime to reset the timeline to 0, or
b) having the initial animation trigger from the button press event.
I had a similar issue before and solved it by completely removing the content of the element that contains the generated SVG, and then simply reload the new SVG in the empty element.
Instead of using a setTimeout which make the whole thing a bit weird, I would simply call it on clicking the element selector:
var elem = document.getElementById('myElementSelector');
elem.addEventListener('click', function() {
document.getElementById(surroundingElementID).innerHTML = "";
//Check what has been clicked and call function that creates the SVG on the surroundingElementID
}, false);

Javascript - Possible to check if an interval is already set?

I have a div that is bouncing every 5 seconds using an interval.
When scrolling to the bottom of the page, this div fades out and the interval is cleared.
However, I think there is an issue with the interval being created multiple times and overlaps upon itself.
Is there a way to check if an interval is set, and if so clear it, and if not, to set it?
The reason I need to clear the interval is because the bounce effect of jquery causes the div to appear again even if it's hidden.
JSBIN: http://jsbin.com/ijuhok/4/
Seems that you set the interval whenever it is scrolled. So if I scroll down, and then scroll down again you set it twice.
Just clear it before hand every time you set it and you should be ok.
http://jsbin.com/ijuhok/6
You need to overwrite the existing interval so that you can clear it from everywhere: http://jsbin.com/ijuhok/5/.
$j("#more").fadeIn('slow',function(){
ResInterval = window.setInterval(bounceMore, 5000);
// no "var"
});
You can eliminate $(document).ready for window because it's always available.
Your issue is that you're defining ResInterval in a local scope, because you've used var:
$j("#more").fadeIn('slow',function(){
var ResInterval = window.setInterval('bounceMore()', 5000);
});
Remove the var prefix, and your code will work as expected: Currently, ResInterval is a local varibale of the callback function in fadeIn. When var is omitted, the interval will be assigned to the closest ResInterval declaration (using var).
I did this like below, My problem was solved. you should set the value like "false", when you clearTimeout the timer.
var timeer=false;
----
----
if(timeer==false)
{
starttimer();
}
-----
-----
function starttimer()
{
timeer=setInterval(activefunction, 1000);
}
function pausetimer()
{
clearTimeout(timeer);
timeer=false;
}

How to use javascript to monitor a change in a div value?

I have a page with a countdown in a DIV with id ="count"
I would like to monitor this div value so, when it reaches 0, a alert pops up.
I've gono so far as
if(parseInt(document.getElementById('count').innerHTML) < 2){}
But I don't know how to "listen" for the div changes
Can anyone help me?
Btw: it needs to be in pure javascript, with no such things as jquery.
Update:
I have no say so in the original code. It's an external page and I'm trying to run this code at the address bar
Presumably you have a function running based on setInterval or setTimeout. Have that function call your function when it gets to zero.
If you can't do that, you can try optimised polling - use setInterval to read the value, estimate when it might be near zero, check again and estimate when it might be zero, etc. When it is zero, do your thing.
There are DOM mutation events, but they are deprecated and were never well or widely supported anyway. Also, they are called when content changes so probably too often for your scenario anyway.
If you are changing the value of #count yourself then call the alert from that place. If not use:
window.setInterval(function(){
if(parseInt(document.getElementById('count').innerHTML) < 2) alert('Alarm!');
},1000); // 1s interval
UPDATE
To clear that interval:
var timer = window.setInterval(function(){
if(parseInt(document.getElementById('count').innerHTML) < 2) {
alert('Alarm!');
window.clearInterval(timer);
}
},1000); // 1s interval
//or by using non-anonymous function
function check(){
if(parseInt(document.getElementById('count').innerHTML) < 2) {
alert('Alarm!');
window.clearInterval(timer);
}
}
var timer = window.setInterval(check,1000);
The only efficient way to monitor this is to go to the code that is actually changing the div and modify it or hook it to call a function of yours whenever it updates the contents of the div. There is no universal notification mechanism for anytime the contents of div changes. You will have much more success looking into modifying the source of the change.
The only option I know of besides the source of the change would be using an interval timer to "poll" the contents of the div to notice when it has changed. But, this is enormously inefficient and will always have some of inherent delay in noticing the actual change. It's also bad for battery life (laptops or smartphones) as it runs continuously.
You don't listen for the div to change. The div is just there for a visual representation of the program's state.
Instead, inside whatever timing event is counting down the number, use a condition such as...
if (i < 2) {
// ...
}

Categories

Resources