How to set this "slider" to change every 5 seconds - javascript

I developed this "slider" in jQuery
HTML:
<div class="col-md-6 pos-rel text-center">
<div class="slider-meio slider1">
<img class="img-responsive" src="http://www.novahidraulica.com.br/imgcategoria/1/2014-09-24-11-09-0420.jpg">
</div>
</div>
<div class="col-md-6 pos-rel text-center">
<div class="slider-meio active slider2">
<img class="img-responsive" src="http://www.novahidraulica.com.br/imgcategoria/1/2014-09-24-11-09-0420.jpg">
</div>
</div>
<div class="col-md-3">
<ul class="controle-slider">
<li class="active-slider"><a data-target=".slider1" >LINHA FACE PLANA</a></li>
<li class=""><a data-target=".slider2" >LINHA COLHEDORA</a></li>
</ul>
</div>
JS:
function montaSlider() {
$(".slider-meio").each(function () {
if($(this).hasClass("active")){
$(this).fadeIn();
}else {
$(this).fadeOut();
}
});
}
montaSlider();
$(".controle-slider li a").click(function () {
$(".controle-slider li a").parent().removeClass("active-slider");
$(this).parent().addClass("active-slider")
$(".slider-meio").removeClass("active");
$($(this).attr("data-target")).addClass("active")
montaSlider();
});
i want to change the slide every 5 seconds, but i cant think of how to do it
can anyone help me?

You can use the window.setInterval() javascript method to call your montarSlider() every 5 seconds. Example:
var timer = window.seInterval(montarSlider, 5000);
I recommend you to store the variable returned by the setInterval() method so you can later stop it if necessary.
EDIT: Since you also need to rotate the elements with the active class, you can first make a function called slide() to activate the next element before calling the montarSlider() function. Then, instead of set the interval to the montarSlider() function, you set it to the slide() function. Example:
function slide() {
var currentActive = $(".slider-meio.active");
var nextActive;
currentActive.removeClass("active");
if(currentActive.parent().next().children(".slider-meio").length > 0) {
nextActive = currentActive.parent().next().children(".slider-meio");
} else {
nextActive = $(currentActive.parent().siblings()[0]).children(".slider-meio");
}
nextActive.addClass("active");
montaSlider();
}
var timer = window.seInterval(slide, 5000);

Use the setInterval() function:
var intrvl = setInterval(function(){montaSlider()},5000);
I you need to stop it use:
clearInterval(intrvl);

Related

Creating a div slider in jquery

I am trying to make an image change when I click on a piece of text on a website that I am building.
At this moment I have created a class called device with one of them being device active as shown below:
<div class="col-md-3">
<div class="device active">
<img src="app/assets/images/mockup.png" alt="">
</div>
<div class="device">
<img src="app/assets/images/mockup.png" alt="">
</div>
<div class="device">
<img src="app/assets/images/mockup.png" alt="">
</div>
</div>
And then what i am currently trying to do is remove the class of active when I click on some text with the i.d of #search2. This is my whole jquery script so far:
$("#search2").click(function() {
var currentImage = $('.device.active');
var nextImage = currentImage.next();
currentImage.removeClass('active');
});
However this does not seem to remove the class of active and the image is still displayed? any ideas?
Your selection is done right and it is working for me (the active class is removed from that item). The problem must be somewhere else in your code.
Here is an alternative:
var activeDeviceIndex = 0;
$("#search2").click(function() {
var devicesContainer = $('.device');
$(devicesContainer[activeDeviceIndex]).removeClass('active');
activeDeviceIndex === devicesContainer.length - 1 ? activeDeviceIndex = 0 : activeDeviceIndex++;
$(devicesContainer[activeDeviceIndex]).addClass('active');
});
.device {
display: none;
}
.device.active {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-3">
<div class="device active">
<p>Device 1</p>
</div>
<div class="device">
<p>Device 2</p>
</div>
<div class="device">
<p>Device 3</p>
</div>
</div>
<button id="search2">click</button>
Check on the following, the id on the button to click should be search2 and not #search2, may be just typo stuffs.
after that update your code as follows
/**
*#description - gets the next image to slide, if the last image is the current image, it will loop the sliding
*#param {Element} current - the currently active image
*#param {Boolean} islooped - boolean value indicating if a looping just started
*/
var nextImage = function(current, islooped) {
var next = islooped? current : current.nextSibling;
while(next && next.nodeName.toLowerCase() !== 'div') {
next = next.nextSibling;
}
next = next? next : nextImage(current.parentNode.firstChild, true);
return next;
};
$('#search2').bind('click', function(event) {
var current = $('.device.active').removeClass('active').get(0);
var next = nextImage(current, false);
$(next).addClass('active');
});

set and clear interval multiple times

On the first slide of my slider I've got some text that changes within an interval.
This is the jQuery to do this:
<script>
var x = 0;
var text = ["STRATEGICALLY", "COST-EFFECTIVELY", "EFFICIENTLY", "EXCEPTIONALLY"];
var counter = 0;
var elem = document.getElementById("banner-change");
var intervalID = setInterval(change, 1500);
function change() {
jQuery(elem).fadeOut('slow', function() {
jQuery(elem).text(text[counter++]);
if (counter >= text.length) {
counter = 0;
}
jQuery(elem).fadeIn('fast');
if (++x === 5) {
window.clearInterval(intervalID);
}
});
}
</script>
The slider looks something like this (The shortened code):
<div id="myCarousel" class="hp-top carousel fade" data-ride="carousel" data-interval="6000">
<div class="carousel-inner">
<div class="item active"><img src="" alt="Chicago"/><div class="carousel-caption">
<div class="carousel-caption-inner">
<p class="slider-text small"><span class="slider-padding">What makes</span> us <span class="slider-green">specialists?</span></p>
<p class="slider-text">We just do ip</p>
<p class="slider-text"><span id="banner-change" class="slider-green">exceptionally</span></p>
</div>
</div>
</div>
So the words in <span id="banner-change" class="slider-green"> keep changing. This works fine. However, it only works for the first time the first banner is shown. Which makes sense as I'm clearing the interval as each word is only supposed to show once, but not sure how to do this so that every time the first banner shows it starts the interval again?
You can use the carousel evelts to trigger action.
e.relatedTarget will then refer to the slide, that is sliding into view.
So if you give it a unique id, you can identify it and run whatever action afterwards.
$('#myCarousel').on('slide.bs.carousel', function (e) {
if (e.relatedTarget.id === 'firstSlide') // do something
})

jQuery .click() activates addClass() & class uses transform: translate to move element

I am making an image slider with two arrows on either side of the slider. For instance, when .click() the .rightArrow, a class is added ( .addClass() ) called .moveRight.
.moveRight{
transform: translate(760px,0);
-webkit-transform: translate(760px,0); /** Safari & Chrome **/
-o-transform: translate(760px,0); /** Opera **/
-moz-transform: translate(760px,0); /** Firefox **/
}
The problem is that this click event only triggers once. I imagine this is because I am telling the moveable element to go to a specific location.
I want to the element to keep moving right for a certain amount of px every time I .click() the .rightArrow.
The jQuery
$( document ).ready(function() {
$('.rightArrow').click( function() {
$('.imgGluedToThis').removeClass("moveLeft");
$('.imgGluedToThis').addClass("moveRight");
});
$('.leftArrow').click( function() {
$('.imgGluedToThis').removeClass("moveRight");
$('.imgGluedToThis').addClass("moveLeft");
});
});
Here is the HTML
<img src="rightArrow.png" class="rightArrow">
<img src="leftArrow.png" class="leftArrow">
<div class="pictures-container">
<div class="imgGluedToThis">
<div class="picture-container">
<a href="#openModal1">
<img src="house.png" class="picture">
</a>
</div>
<div class="picture-container">
<a href="#openModal1">
<img src="building.png" class="picture">
</a>
</div>
<div class="picture-container">
<a href="#openModal1">
<img src="house2.png" class="picture">
</a>
</div>
<div class="picture-container">
<a href="#openModal1">
<img src="house.png" class="picture">
</a>
</div>
<div class="picture-container">
<a href="#openModal1">
<img src="building.png" class="picture">
</a>
</div>
<div class="picture-container">
<a href="#openModal1">
<img src="house2.png" class="picture">
</a>
</div>
</div>
</div>
Use css() method in jQuery
$(document).ready(function() {
$('.rightArrow').click( function() {
$('.imgGluedToThis').css('left','+=10px');
});
$('.leftArrow').click( function() {
$('.imgGluedToThis').css('left','-=10px');
});
});
FIDDLE
Or use animate() method
$(document).ready(function() {
$('.rightArrow').click( function() {
$('.imgGluedToThis').animate({'left':'+=10px'});
});
$('.leftArrow').click( function() {
$('.imgGluedToThis').animate({'left':'-=10px'});
});
});
FIDDLE
The click event is triggering correctly every time - translate will move an element to a specific position. If it is already 760px across and click is called again to move it to 760px, nothing appears to happen.
You could set up a few classes to define where the leftmost, rightmost etc images should display, updating the classes for each element accordingly.
If the slider needs to be infinite, you will need to update the DOM too to set the elements to the correct order, updating the classes again once you have done so.
If you want to use translate, specifically, you will need to track it and change it with code, perhaps like this:
jQuery(function ($) {
// closures
var iImageIndex = 0;
var iSlideWidth = 760;
var iImageMax = $('.picture-container').size();
var $slides = $('.imgGluedToThis');
var fTranslate = function (iDirection) {
iDirection = (iDirection && (iDirection < 0) ) ? -1 : 1; // normalize direction
iImageIndex = iImageIndex + iDirection; // increment direction
iImageIndex = iImageIndex < 0 ? iImageMax + iImageMax : iImageIndex; // check left end
iImageIndex = iImageIndex % iImageMax; // check right end
$slides.css('transform', 'translate(' + (iSlideWidth * iImageIndex) + 'px, 0)');
}
// event methods (closures)
var fClickLeft = function () {
fTranslate(-1);
};
var fClickRight = function () {
fTranslate(1);
};
// event handlers
$('.rightArrow').click(fClickRight);
$('.leftArrow').click(fClickLeft);
});

Add Class to Following Element

I had a look out on the interwebs for a jQuery image gallery and couldn't find one that suited what I wanted to do. So I, ended up creating one myself and am trying to figure out how to get the prev and next buttons to work.
<div class="gallery portrait">
<nav>
<div class="close"></div>
<div class="prev"></div>
<div class="next"></div>
</nav>
<div class="cover">
<img src="image.jpg">
</div>
<ul class="thumbs">
<li class="thumb">
<img src="image.jpg">
</li>
...
</ul>
</div>
I'm also using a bit of jQuery to add a class of .full to the .thumb a element, which makes the thumbnails go fullscreen.
$( ".thumb a" ).click(function() {
$( this ).toggleClass( "full" );
$( "nav" ).addClass( "show" );
});
Now I can't work out this next bit, I need a way when the .prev or .next buttons are clicked for it to remove the class of .full from the current element and add it to the next or previous .thumb a element, depending on which was clicked.
I've got a demo setup here: http://codepen.io/realph/pen/hjvBG
Any help is appreciated, thanks in advance!
P.S. If this turns out well, I plan on releasing it for free. I guess you can't have too many jQuery image galleries, eh?
You can use $.next() and $.prev():
$(".prev").click(function () {
var current = $('.full');
current.prev('.thumb').addClass('full');
current.removeClass('full');
return false; // stop propagation; prevents image click event
});
$(".next").click(function () {
var current = $('.full');
current.next('.thumb').addClass('full');
current.removeClass('full');
return false; // stop propagation; prevents image click event
});
I suggest the following additions to your code to handle wrapping around with your next and previous links:
$(".next").click(function (event) {
navigate("next");
return false;
});
$(".prev").click(function (event) {
navigate("prev");
return false;
});
function navigate(operation) {
var $thumbs = $(".thumb"),
$full = $thumbs.find("a.full").closest(".thumb"),
$next;
$thumbs.find('a').removeClass('full');
if (operation == 'prev' && $full.is($thumbs.first()))
$next = $thumbs.last();
else if (operation == 'next' && $full.is($thumbs.last()))
$next = $thumbs.first();
else
$next = $full[operation]();
$next.find('a').click();
}
Here is a forked CodePen.
Something like this will get you started, but what you're wanting to do takes a little time to get just right.
<script type="text/javascript">
var imgSrcs = ['/imgs/this.jpg', '/imgs/will.jpg', '/imgs/work.jpg', '/imgs/just.jpg', '/imgs/fine.jpg'];//img url loaded into an array
var btnPrev = document.getElementById('prev'),
btnNext = document.getElementById('next'),
cover = document.getElementById('cover'),
thumb = document.getElementById('thumb'),
currImgIx = 0;
btnPrev.onclick = function () {
if (currImgIx === 0) { return; };
currImgIx--;
cover.src = imgSrcs[currImg];
thumb.src = imgSrcs[currImgIx];
};
btnNext.onclick = function () {
if (currImgIx === imgSrcs.length - 1) { return; };
currImgIx++;
cover.src = imgSrcs[currImgIx];
thumb.src = imgSrcs[currImgIx];
};
</script>
<div class="gallery portrait">
<nav>
<div class="close">X</div>
<div id="prev" class="prev">Prev</div>
<div id="next" class="next">Next</div>
</nav>
<div class="cover">
<img id="cover" src="image.jpg">
</div>
<ul class="thumbs">
<li class="thumb">
<img id="thumb" src="image.jpg">
</li>
...
</ul>
</div>

Firefox setTimeout + jQuery fade loop inconsistent, stops early, won't cycle

http://jsfiddle.net/x6PCD/11/
I'm trying to make a slideshow that fades between several absolute-positioned div's. On Chrome, IE9, Opera the code below works fine. But on Firefox, the timeout goes once or twice, then stops. If you remove the JS section marked below, it loops properly.
<style>
.slide {position:absolute; top:0; left:0; width:300px; height:200px}
</style>
<div id="slides" class="slides">
<div class="slide slide1" style="background:#c66">
<div class="swap_links">
1
2
3
</div>
</div>
<div class="slide slide2" style="background:#6c6">
<div class="swap_links">
1
2
3
</div>
</div>
<div class="slide slide3" style="background:#36c">
<div class="swap_links">
1
2
3
</div>
</div>
</div>
<script type="text/javascript">
$(function() {
var fp = '#slides .slide';
var fs = 300;
var t = window.setTimeout(swap, 1000);
$(fp).slice(1).hide();
function swap(to) {
//removing this section, loop plays in FF
if (to) {
$(fp + to).fadeIn(fs);
$(fp).not('.slide' + to).fadeOut(fs);
window.clearTimeout(t);
return;
}
$(fp).eq(1).fadeIn(fs);
$(fp).eq(0).fadeOut(fs, function() {
$(this).appendTo('#slides');
t = window.setTimeout(swap, 1000);
});
}
$('#slides .swap_links a').click(function() {
swap($(this).html());
});
});
</script>
FireFox appears to have been passing arbitrary numeric values to the to variable within your function causing the if(to){...} statement to execute if the passed value was anything but 0.
To fix this execute the swap() function without arguments in the setTimeout() like this:
var t = window.setTimeout(function(){ swap(); }, 1000);
Here is the updated demo: http://jsfiddle.net/x6PCD/14/
I hope this helps!

Categories

Resources