I have a slider that I've built myself, which is a carousel that infinitely loops. I'm wanting to create a counter (1 of 4, 2 of 4) etc, with the last number being the total number of slides present and the 1/2/3/4 displays which slide you are viewing.
This is what I have so far for my counter:
var $tota = $('.past-project-container').find('span.total');
var $curr = $('.past-project-container').find('span.current');
function changeCurr(){
$tota.text(numberOfProjects);
$curr.text(1);
}
changeCurr();
HTML:
<span class="slide-count-container">
<span class="current">1</span> of <span class="total">1</span>
</span>
And this is my JS for the carousel if it helps
var $carousel = $('.past-project-slider'), carW = $carousel.outerWidth(), intv;
$carousel.wrapInner('<div id="slider" />');
var $slider = $('#slider');
numberOfProjects = $('.past-project-each').length;
$slider.css({position:'absolute',left:0, width:carW*numberOfProjects}).find('.past-project-each').css({'float':'left'});
function move(cb){
if(!$slider.is(':animated')){
if(cb=='next'){
$slider.animate({left:-carW},800,function(){
$slider.append($('.past-project-each:first'));
$slider.css({left:0});
});
}else{
$slider.prepend($('.past-project-each:last'));
$slider.css({left:-carW});
$slider.animate({left:0},800);
}
}
}
$('#next-past-project, #prev-past-project').click(function(){
var btn = this.id=='next-past-project' ? move('next') : move('prev');
});
Many thanks,
R
Rather than constantly reading and converting the contents of the $curr element its probably better to keep track in another variable, like so:
var $tota = $('.past-project-container').find('span.total');
var $curr = $('.past-project-container').find('span.current');
var currentIndex = 0;
function changeCurr(){
$tota.text(numberOfProjects);
// If we've not reached the final index, add one, else return to the start
currentIndex = (currentIndex == numberOfProjects) ? 1 : currentIndex + 1;
$curr.text(currentIndex);
}
changeCurr();
This will count up until the last slide. Be sure to call changeCurr() on each slide transition.
Related
I have simple code where is slideshow which automatic slides every 5000ms.
Now I tried to make button which when I click on this button next image will not slide every 5000ms but when I click.
When I make code like this browser giving me errors.
Is there any solutions or I need make ned slideshow?
This is original code:
function cycleBackgrounds() {
var index = 0;
$imageEls = $('.container .slide');
setInterval(function () {
index = index + 1 < $imageEls.length ? index + 1 : 0;
$imageEls.eq(index).addClass('show');
$imageEls.eq(index - 1).removeClass('show');
}, 5000);
};
$(function () {
cycleBackgrounds();
});
This is added code:
function rightSlide() {
index = index + 1 < $imageEls.length ? index + 1 : 0;
$imageEls.eq(index).addClass('show');
$imageEls.eq(index - 1).removeClass('show');
}
EDIT added HTML
<section class="slide show" style="background-image: url('https://s7img.ftdi.com/is/image/ProvideCommerce/FTD_19_EDAY_19M3_HP_HEROBANNER?$ftd-product-banner-lv$');">
<div class="slide-content-wrapper">
<div class="slide-content">
<h2>02</h2>
</div>
</div>
</section>
<section class="slide" style="background-image: url('https://s7img.ftdi.com/is/image/ProvideCommerce/FTD_19_EDAY_19M3_HP_HEROBANNER?$ftd-product-banner-lv$');">
<div class="slide-content-wrapper right">
<div class="slide-content">
<h2>01</h2>
</div>
</div>
</section>
The problem is that you are creating an interval and then never clearing it. This means that once the interval is created it will keep going on forever (currently). You can read more about intervals here.
To briefly explain how to solve it:
You need to assign the interval to a variable
When you want to manually change images then clear the interval
Code snippet from the site:
var myVar = setInterval(myTimer, 1000);
function myTimer() {
var d = new Date();
var t = d.toLocaleTimeString();
document.getElementById("demo").innerHTML = t;
}
function myStopFunction() {
clearInterval(myVar);
}
Inside of your code, when creating the interval you need to assign it into a variable and inside of the function rightSlide() you would need to clear it clearInterval(<yourIntervalHere>);
var intervalVariable = setInterval(function () {
index = index + 1 < $imageEls.length ? index + 1 : 0;
$imageEls.eq(index).addClass('show');
$imageEls.eq(index - 1).removeClass('show');
}, 5000);
function rightSlide() {
clearInterval(intervalVariable);
index = index + 1 < $imageEls.length ? index + 1 : 0;
$imageEls.eq(index).addClass('show');
$imageEls.eq(index - 1).removeClass('show');
}
You need to clear the interval but that's not the only problem:
Probably, the $imageEls and index variables are not in the scope of your custom click handler. It is definitely not the cleanest solution, but for now we will add them to the global window object
This is how I would write it (untested):
function cycleBackgrounds() {
window.index = (window.index + 1 < window.$imageEls.length) ? window.index + 1 : 0;
window.$imageEls.eq(index).addClass('show');
window.$imageEls.eq(index - 1).removeClass('show');
}
$(function () {
// add the new variables to window so they are globally accessible
window.index = 0;
window.$imageEls = $('.container .slide');
// start sliding images
window.slideshow_interval = setInterval(cycleBackgrounds, 5000);
// register onClick handler for the button with id "myButton"
$('#myButton').on('click', function(){
if (window.slideshow_interval != -1){
clearInterval(window.slideshow_interval);
window.slideshow_interval = -1;
}
cycleBackgrounds();
});
});
I'm currently working on a slider for a website.
This slider has three components.
Game list
Team overview
Awards
I have all games displayed at the same time, but only want the one corresponding to the current team be highlighted. The amount of games displayed is equal to the amount of teams and game[0] belongs to team[0] and so on.
EDIT I've changed the slider a bit :)
var slides = document.getElementsByClassName('slider');
[].forEach.call(slides, function (s) {
var next = s.getElementsByClassName('next')[0],
prev = s.getElementsByClassName('prev')[0],
inner = s.getElementsByClassName('inner')[0],
slides = inner.getElementsByClassName('slide'),
currentTeamIndex = 0,
width = 1344;
var $gameList = $('#gameList'),
$gameContainer = $gameList.find('.slides'),
$game = $gameContainer.find('.slide');
function switchSlide() {
inner.style.left = -width * currentTeamIndex + 'px';
}
next.addEventListener('click', function () {
currentTeamIndex++;
if (currentTeamIndex >= slides.length) {
currentTeamIndex = 0;
}
switchSlide();
});
prev.addEventListener('click', function () {
currentTeamIndex--;
if (currentTeamIndex < 0) {
currentTeamIndex = slides.length - 1;
}
switchSlide();
});
});
How can I do that? I'm fairly new to javascript and jQuery.
So here is the thing, I have a sidebar that has big height due the lots of navigation links. And I'm using jQuery nicescroll plugin to make it look fine. In the sidebar I also have h3 tag which makes a random effect of showing letters (see the code) every 4 seconds. So, when it's on - scroll is not working at all for these 4 seconds and you can't do any scrolling. I tried to use $("#sidebar").getNiceScroll().resize() but it doesn't work either. Is there any way to make it work?
<div id="sidebar">
<h3 id="output">Random</h3>
</div>
//Calling for nicescroll function for my sidebar
$(function(){
$("#sidebar").niceScroll({ cursorcolor:"#66aee9", cursorfixedheight: 400 });
})
//Random effect for my h3 tag
setInterval(function(){
$(document).ready(function(){
var theLetters = "abcdefghijklmnopqrstuvwxyz#%&^+=-"; //You can customize what letters it will cycle through
var ctnt = "Random"; // Your text goes here
var speed = 50; // ms per frame
var increment = 8; // frames per step. Must be >2
var clen = ctnt.length;
var si = 0;
var stri = 0;
var block = "";
var fixed = "";
//Call self x times, whole function wrapped in setTimeout
(function rustle (i) {
setTimeout(function () {
if (--i){rustle(i);}
nextFrame(i);
si = si + 1;
}, speed);
})(clen*increment+1);
function nextFrame(pos){
for (var i=0; i<clen-stri; i++) {
//Random number
var num = Math.floor(theLetters.length * Math.random());
//Get random letter
var letter = theLetters.charAt(num);
block = block + letter;
}
if (si == (increment-1)){
stri++;
}
if (si == increment){
// Add a letter;
// every speed*10 ms
fixed = fixed + ctnt.charAt(stri - 1);
si = 0;
}
$("#output").html(fixed + block);
block = "";
}
});
}, 4000);
I change to rows and check it in jsfiddle, looks like working scroll fine.
Before:
setInterval(function(){
$(document).ready(function(){
...
});
}, 4000);
After:
$(document).ready(function(){
setInterval(function(){
...
}, 4000);
});
New to web development and trying to create a gallery of images that cycle through with the click of a "previous" and "next" button. Does anybody know how to do this? I don't think I've done anything right but I'll include what I've done so far. The idea is to make this adaptable to n indefinite number of images.
code:
<img src= "photos/1.jpg" id="currentImage" height="288"/>
<button id= "prev" onclick="prevImage()" class="portfolioNavigation">Previous</button>
<button id= "next" onclick="nextImage()" class="portfolioNavigation">Next</button>
<script type= "text/javascript">
var counter = 2;
var 1 = "photos/1.jpg";
var 2 = "photos/2.jpg";
var 3 = "photos/3.jpg";
prev.onclick = function(){
document.getElementById("currentImage").src = counter - 1;
counter--;
}
next.onclick = function(){
document.getElementById("currentImage").src = counter + 1;
counter++;
}
if(counter == 3){
counter = 0;
};
</script>
There is no need of using "onclick" inside button tags.
<script type= "text/javascript">
var counter = 2;
var sourceUrl = "photos/" + counter + ".jpg";
var prev = document.getElementById("prev");
var next = document.getElementById("next");
prev.onclick = function(){
counter--;
document.getElementById("currentImage").src = sourceUrl;
}
next.onclick = function(){
counter++;
document.getElementById("currentImage").src = sourceUrl; }
if(counter == 3){
counter = 0;
};
</script>
As others have posted, you cannot use an int as a variable name.
You also had "onclick" events on each button and events set via jQuery, you just need one or the other.
Storing each src string in an array and accessing it by using "counter" will work for you. It will also allow you to use a variable amount of images.
HTML
<img src= "photos/1.jpg" id="currentImage" height="288"/>
<button id= "prev" class="portfolioNavigation">Previous</button>
<button id= "next" class="portfolioNavigation">Next</button>
JavaScript
var counter = 0;
var srcArray = ["photos/1.jpg", "photos/2.jpg", "photos/3.jpg"];
prev.onclick = function(){
document.getElementById("currentImage").src = srcArray[--counter];
}
next.onclick = function(){
document.getElementById("currentImage").src = srcArray[++counter];
}
if(counter == 3){
counter = 0;
};
If you inspect the image element in this JSFiddle, you'll see the src updating correctly.
There are couple of issues in your code right now. One of them is that your variables names are plain numbers. You cannot have variable names starting with numbers in JavaScript. Although not a great example, _1 is valid, image1 is a valid and even a more descriptive variable number.
Another issue is, when you are setting the src attribute of currentImage you are also setting that attribute to a value of plain number. That is not a valid image url.
You can put the photo URLs in an array and cycle through those images when next and previous buttons are pressed.
Try something like this (warning untested code):
var images = ["photos/1.jpg", "photos/2.jpg", "photos/3.jpg"];
var numImages = images.length;
prev.onclick = function(){
document.getElementById("currentImage").src = images[(counter - 1) % numImages];
counter--;
}
The significance of the % operator here is that it wraps around the value of [0, numImages).
I have programmed an image slider in javascript, and it's "functional," but it doesn't alternate the images except for the very first and last images. For example, if I'm on the first image and press the right button, it won't change to the next image in the array. However, if I were to push the left button, it will change to last image in the array. The same thing will happen for the last image. I don't know how to fix this. Can you help?
I think it might have to do something with the "total" variable, but I'm not sure.
Here's the code...
window.onload = function () {
var nmbr_imgs = 4;
var imgs_holder = ["IMGS/Actinium.png", "IMGS/Aluminum.png", "IMGS/Astatine.png", "IMGS/Barium.png"];
var total = imgs_holder.length;
var left_btn = document.getElementById('left_btn');
var right_btn = document.getElementById('right_btn');
var imgs_display = document.getElementById('imgs_display');
left_btn.addEventListener('click', function() {
var lefting = total - 1;
imgs_display.src = imgs_holder[lefting];
if (lefting < 0) {
imgs_display.src = imgs_holder[(nmbr_imgs - 1)];
}
}, false);
right_btn.addEventListener('click', function() {
var righting = total + 1;
imgs_display.src = imgs_holder[righting];
if (righting > (nmbr_imgs - 1)) {
imgs_display.src = imgs_holder[0];
}
}, false);
}
Your listeners are off a bit ...
total = total - 1;
imgs_display.src = imgs_holder[total];
if(lefting < 0) {
total = nmbr_imgs - 1;
imgs_display = imgs_holder[total]
}
... try incrementing/decrementing total, not lefting/righting which are reset to total +/- 1 each time.