Image Slider not go to next or prev item - javascript

(I face a problem when i click on prev chevron the slider works for once and stops after the next click)
I am a beginner in JavaScript and I am trying to build my own slider code. at first when you click on the next chevron the code is working well but when I click on the prev chevron the code is stopped after the second click.
$(document).ready(function(){
var currentImg = $('.slider-img .active');
var nextImg = currentImg.next();
var prevImg = currentImg.prev();
//slide to right
$('.next').on('click', function(){
if(!currentImg.is(':last-child')){
currentImg.delay(1000).removeClass('active');
nextImg.addClass('active');
}else{
currentImg.delay(1000).removeClass('active');
$('.slider-img div').eq(0).addClass('active');
}
});
//Slide to left
$('.prev').on('click', function(){
if(!currentImg.is(':first-child')){
currentImg.delay(1000).removeClass('active');
prevtImg.addClass('active');
}else{
currentImg.delay(1000).removeClass('active');
$('.slider-img div:last-child').addClass('active');
}
});
});
there is the full code on codepen bellow

Because you declare your variable outside of click event, when document is ready currentImg is first element, after you click, currentImg need to detect again because right now it's second element, so for avoid this issue, move your variable inside your click handler:
$('.next').on('click', function(){
var currentImg = $('.slider-img .active');
var nextImg = currentImg.next();
var prevImg = currentImg.prev();
if(!currentImg.is(':last-child')){
currentImg.delay(1000).removeClass('active');
nextImg.addClass('active');
}else{
currentImg.delay(1000).removeClass('active');
$('.slider-img div').eq(0).addClass('active');
}
});
An improved version is:
$(document).ready(function() {
var firstChild = $('.slider-img div.item').eq(0);
var lastChild = $('.slider-img div.item:last-child');
//slide to right
$('.next').on('click', function() {
var currentImg = $('.slider-img .active');
var nextImg = currentImg.next();
if (!currentImg.is(':last-child')) {
currentImg.delay(1000).removeClass('active')
nextImg.addClass('active')
} else {
currentImg.delay(1000).removeClass('active')
firstChild.addClass('active');
}
});
//Slide to left
$('.prev').on('click', function() {
var currentImg = $('.item.active');
var prevImg = currentImg.prev();
if (currentImg.is(':first-child')) {
currentImg.delay(1000).removeClass('active')
lastChild.addClass('active')
} else {
currentImg.delay(1000).removeClass('active')
prevImg.addClass('active');
}
});
});
* {
padding: 0;
margin: 0;
}
.slider {
position: relative;
width: 600px;
height: 500px;
margin: 30px auto 0;
}
.slider ul {
position: absolute;
bottom: 20px;
width: 100%;
text-align: center;
z-index: 3;
}
.slider ul li {
width: 12px;
height: 12px;
border-radius: 50%;
background-color: #cccccc;
list-style: none;
margin: 0 10px;
display: inline-block;
cursor: pointer;
}
.slider ul li.active {
background-color: #000;
}
.slider-img div {
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
opacity: 0;
}
.slider-img div.active {
opacity: 1;
}
.slider-img img {
max-width: 100%;
height: 100%;
}
.slider p {
position: absolute;
z-index: 2;
top: 50%;
color: #cccccc;
padding: 20px;
cursor: pointer;
}
.slider .next {
right: 0;
}
.item1 {
background-color: red
}
.item2 {
background-color: green
}
.item3 {
background-color: purple
}
.item4 {
background-color: yellow
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section class="slider">
<ul>
<li class="dot active" onclick="currentSlide(1)"></li>
<li class="dot" onclick="currentSlide(2)"></li>
<li class="dot" onclick="currentSlide(3)"></li>
<li class="dot" onclick="currentSlide(4)"></li>
</ul>
<div class="slider-img">
<div class="item item1 active"></div>
<div class="item item2"></div>
<div class="item item3"></div>
<div class="item item4"></div>
</div>
<p class="next">
>
</p>
<p class="prev">
< </p>
</section>

The problem is that you do not set the variable to the new value once the prev or next button is clicked.
That is how it works, even though your approach is a bit complicated:
(Also I recommend to use let instead of var for your variable declaration)
$(document).ready(function(){
let currentImg = $('.slider-img .active');
let nextImg = currentImg.next();
let prevImg = currentImg.prev();
//slide to right
$('.next').on('click', function(){
if(!currentImg.is(':last-child')){
currentImg.delay(1000).removeClass('active');
nextImg.addClass('active');
currentImg = nextImg;
nextImg = currentImg.next();
}else{
currentImg.delay(1000).removeClass('active');
$('.slider-img div').eq(0).addClass('active');
currentImg = $('.slider-img .active');
nextImg = currentImg.next();
}
});
$('.prev').on('click', function(){
if(!currentImg.is(':first-child')){
currentImg.delay(1000).removeClass('active');
prevImg.addClass('active');
currentImg = prevImg;
prevImg = currentImg.prev();
}else{
currentImg.delay(1000).removeClass('active');
$('.slider-img div:last-child').addClass('active');
currentImg = $('.slider-img .active');
prevImg = currentImg.prev();
}
});
});
*{
padding: 0;
margin: 0;
}
.slider{
position: relative;
width:600px;
height: 500px;
margin: 30px auto 0;
}
.slider ul{
position: absolute;
bottom: 20px;
width: 100%;
text-align: center;
z-index: 3;
}
.slider ul li{
width:12px;
height: 12px;
border-radius: 50%;
background-color: #cccccc;
list-style: none;
margin:0 10px;
display: inline-block;
cursor: pointer;
}
.slider ul li.active{
background-color: #000;
}
.slider-img div{
position: absolute;
top:0;
left:0;
bottom: 0;
right: 0;
opacity: 0;
}
.slider-img div.active{
opacity: 1;
}
.slider-img img{
max-width: 100%;
height: 100%;
}
.slider p{
position: absolute;
z-index: 2;
top: 50%;
color: #cccccc;
padding: 20px;
cursor: pointer;
}
.slider .next{
right: 0;
}
.item1{background-color:red}
.item2{background-color:green}
.item3{background-color:purple}
.item4{background-color:yellow}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<section class="slider">
<ul>
<li class="dot active" onclick="currentSlide(1)"></li>
<li class="dot" onclick="currentSlide(2)"></li>
<li class="dot" onclick="currentSlide(3)"></li>
<li class="dot" onclick="currentSlide(4)"></li>
</ul>
<div class="slider-img">
<div class="item item1 active"></div>
<div class="item item2"></div>
<div class="item item3"></div>
<div class="item item4"></div> </div>
<p class="next">
<i class="fas fa-chevron-right">next</i>
</p>
<p class="prev">
<i class="fas fa-chevron-left">prev</i>
</p>
</section>

Related

click button scroll to specific div

I have a page that has a fixed menu and content box(div).
When click the menu, content box scroll to specific div.
So far so good.
This is the sample here.
https://jsfiddle.net/ezrinn/8cdjsmb9/11/
The problem is when I wrap this whole div and, make them as show/hide toggle button, the scroll is not working.
This is the sample that not working.
https://jsfiddle.net/ezrinn/8cdjsmb9/10/
Also here is the snippet
$('.btn').click(function() {
$(".wrap").toggleClass('on');
});
var div_parent_class_name;
var divs_class;
var id_offset_map = {};
$(document).ready(function() {
div_parent_class_name = "wrap_scroll";
divs_class = "page-section";
var scroll_divs = $("." + div_parent_class_name).children();
id_offset_map.first = 0;
scroll_divs.each(function(index) {
id_offset_map["#" + scroll_divs[index].id] = scroll_divs[index].offsetTop
});
$('a').bind('click', function(e) {
e.preventDefault();
var target = $(this).attr("href")
$('.wrap_scroll').stop().animate({
scrollTop: id_offset_map[target]
}, 600, function() {
/* location.hash = target-20; */ //attach the hash (#jumptarget) to the pageurl
});
return false;
});
});
$(".wrap_scroll").scroll(function() {
var scrollPos = $(".wrap_scroll").scrollTop();
$("." + divs_class).each(function(i) {
var divs = $("." + divs_class);
divs.each(function(idx) {
if (scrollPos >= id_offset_map["#" + this.id]) {
$('.menu>ul>li a.active').removeClass('active');
$('.menu>ul>li a').eq(idx).addClass('active');
}
});
});
}).scroll();
body,
html {
margin: 0;
padding: 0;
height: 3000px;
}
.wrap { display:none;}
.wrap.on { display:block;}
.menu {
width: 100px;
position: fixed;
top: 40px;
left: 10px;
}
.menu a.active {
background: red
}
.wrap_scroll {
position: absolute;
top: 20px;
left: 150px;
width: 500px;
height: 500px;
overflow-y: scroll
}
#home {
background-color: #286090;
height: 200px;
}
#portfolio {
background: gray;
height: 600px;
}
#about {
background-color: blue;
height: 800px;
}
#contact {
background: yellow;
height: 1000px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="btn">show/hide</button>
<div class="wrap">
<div class="menu">
<ul>
<li><a class="active" href="#home">Home</a> </li>
<li>Portfolio </li>
<li>About </li>
<li>Contact </li>
</ul>a
</div>
<div class="wrap_scroll">
<div class="page-section" id="home">hh</div>
<div class="page-section" id="portfolio">pp</div>
<div class="page-section" id="about">aa</div>
<div class="page-section" id="contact">cc</div>
</div>
</div>
What Do I need to fix the code? please help.
When you calculate your offset, the div is hidden with display: none. This results in the offsets being set/calculated to zero.
Here's a quick fix I threw together: https://jsfiddle.net/hrb58zae/
Basically, moved the logic to determine offset after clicking show/hide.
var setOffset = null;
...
if (!setOffset) {
var scroll_divs = $("." + div_parent_class_name).children();
id_offset_map.first = 0;
scroll_divs.each(function(index) {
id_offset_map["#" + scroll_divs[index].id] = scroll_divs[index].offsetTop
});
setOffset = true;
}
In your CSS, instead of using display: none and display: block, try using visible instead:
.wrap { visibility:hidden;}
.wrap.on { visibility:visible;}
This will hide the element without affecting the layout.
Updated fiddle: https://jsfiddle.net/a5u683es/
The problem was you are trying to update id_offset_map when content was hidden. When you use 'display:none' prop you won't get dimensions for that element and so its not working.
I updated the logic please check the fiddle https://jsfiddle.net/qfrsmnh5/
var id_offset_map = {};
var div_parent_class_name = "wrap_scroll";
var divs_class = "page-section";
var scroll_divs = $("." + div_parent_class_name).children();
function updateOffsets(){
id_offset_map.first = 0;
scroll_divs.each(function(index) {
id_offset_map["#" + scroll_divs[index].id] = scroll_divs[index].offsetTop
});
}
$(document).ready(function() {
$('.btn').click(function() {
$(".wrap").toggleClass('on');
if($(".wrap").hasClass("on")){
updateOffsets();
}
});
$('a').on('click', function(e) {
e.preventDefault();
var target = $(this).attr("href")
$('.wrap_scroll').stop().animate({
scrollTop: id_offset_map[target]
}, 600, function() {
/* location.hash = target-20; */ //attach the hash (#jumptarget) to the pageurl
});
return false;
});
});
$(".wrap_scroll").on('scroll',function() {
var scrollPos = $(".wrap_scroll").scrollTop();
$("." + divs_class).each(function(i) {
var divs = $("." + divs_class);
divs.each(function(idx) {
if (scrollPos >= id_offset_map["#" + this.id]) {
$('.menu>ul>li a.active').removeClass('active');
$('.menu>ul>li a').eq(idx).addClass('active');
}
});
});
}).scroll();
body,
html {
margin: 0;
padding: 0;
height: 3000px;
}
.wrap { display:none;}
.wrap.on { display:block;}
.menu {
width: 100px;
position: fixed;
top: 40px;
left: 10px;
}
.menu a.active {
background: red;
}
.wrap_scroll {
position: absolute;
top: 20px;
left: 150px;
width: 500px;
height: 500px;
overflow-y: scroll;
}
#home {
background-color: #286090;
height: 200px;
}
#portfolio {
background: gray;
height: 600px;
}
#about {
background-color: blue;
height: 800px;
}
#contact {
background: yellow;
height: 1000px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="btn">show/hide</button>
<div class="wrap">
<div class="menu">
<ul>
<li><a class="active" href="#home">Home</a></li>
<li>Portfolio </li>
<li>About </li>
<li>Contact </li>
</ul>
</div>
<div class="wrap_scroll">
<div class="page-section" id="home">hh</div>
<div class="page-section" id="portfolio">pp</div>
<div class="page-section" id="about">aa</div>
<div class="page-section" id="contact">cc</div>
</div>
</div>
works perfectly, it's just that when you use display: none you can not do the offsetTop calculations because in fact the element is not rendered, I'm not sure if all the values ​​give 0 or undefined, I guess undefined, a solution is always calculate Positions using a function:
var div_parent_class_name;
var divs_class;
var id_offset_map = {};
function calcTops(){
div_parent_class_name = "wrap_scroll";
divs_class = "page-section";
var scroll_divs = $("." + div_parent_class_name).children();
id_offset_map.first = 0;
scroll_divs.each(function(index) {
id_offset_map["#" + scroll_divs[index].id] = scroll_divs[index].offsetTop
});
}
https://jsfiddle.net/561oe7rb/1/
is not the optimal way, but it is to give you an idea. Sorry for my English.
Just Checkout This Working page I have designed
jQuery(document).on('scroll', function(){
onScroll();
});
jQuery(document).ready(function($) {
div_slider();
showhide();
});
/*show hide content*/
function showhide(){
$('.toggle-wrapper button').on('click', function(){
$('.wrapper').toggle();
// div_slider();
})
}
/*scrolling page on header elements click*/
function div_slider(){
$('ul li a').on('click', function(e){
e.preventDefault();
$('ul li a').removeClass('active');
$(this).addClass('active');
var attrval = $(this.getAttribute('href'));
$('html,body').stop().animate({
scrollTop: attrval.offset().top
}, 1000)
});
}
/*adding active class on header elements on page scroll*/
function onScroll(event){
var scrollPosition = $(document).scrollTop();
$('ul li a').each(function () {
var scroll_link = $(this);
var ref_scroll_Link = $(scroll_link.attr("href"));
if (ref_scroll_Link.position().top <= scrollPosition && ref_scroll_Link.position().top + ref_scroll_Link.height() > scrollPosition) {
$('ul li a').removeClass("active");
scroll_link.addClass("active");
}
else{
scroll_link.removeClass("active");
}
});
}
body {
margin: 0;
}
.toggle-wrapper {
position: fixed;
top: 0;
left: 0;
right: 0;
background-color: #ccd2cc;
text-align: center;
}
.toggle-wrapper button {
background-color: #ED4C67;
color: #ffffff;
padding: 10px 20px;
border: 0;
cursor: pointer;
border-radius: 5px;
}
.toggle-wrapper button:active{
background-color: #B53471;
}
header {
background-color: #6C5CE7;
position: fixed;
top: 36px;
z-index: 99;
left: 0;
right: 0;
}
header ul {
list-style: none;
display: flex;
justify-content: space-between;
align-items: center;
padding: 0;
margin: 0;
}
ul li {
flex: 1 100%;
display: flex;
justify-content: center;
}
.wrapper {
margin-top: 36px;
}
header a {
color: #ffffff;
padding: 15px;
display: block;
text-decoration: navajowhite;
text-transform: uppercase;
width: 100%;
text-align: center;
}
header a.active {
color: #000000;
background-color: #ffffff;
}
section {
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
section.section1 {
background-color: #FFEAA7;
}
section.section2{
background-color:#FAB1A0;
}
section.section3{
background-color:#7F8C8D;
}
section.section4{
background-color:#4CD137;
}
section.section5{
background-color:#A3CB38;
}
section.section6{
background-color:#70A1FF;
}
section.section7{
background-color:#079992;
}
<div class="toggle-wrapper">
<button>Toggle</button>
</div>
<div class="wrapper" style="display: none;">
<header>
<ul>
<li><a class="active" href="#one">one</a></li>
<li>two</li>
<li>three</li>
<li>four</li>
<li>five</li>
<li>six</li>
<li>seven</li>
</ul>
</header>
<section class="section1" id="one">SECTION ONE</section>
<section class="section2" id="two">SECTION TWO</section>
<section class="section3" id="three">SECTION THREE</section>
<section class="section4" id="four">SECTION FOUR</section>
<section class="section5" id="five">SECTION FIVE</section>
<section class="section6" id="six">SECTION SIX</section>
<section class="section7" id="seven">SECTION SEVEN</section>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Custom jQuery carousel transition bug

I am working on a custom image carousel, with jQuery and CSS. I am trying to avoid using a multiple-features carousel plugin download from Github, for performance reasons.
My aim is to obtain a vertical transition, like the one on www.pcgarage.ro, but without using the plugin they (might) have used. For this purpose, I have written:
var $elm = $('.slider'),
$slidesContainer = $elm.find('.slider-container'),
slides = $slidesContainer.children('a'),
slidesCount = slides.length,
slideHeight = $(slides[0]).find('img').outerHeight(false);
//Set slide height
$(slides).css('height', slideHeight);
// Append bullets
for (var i = 0; i < slidesCount; i++) {
var bullets = '' + i + '';
if (i == 0) {
// active bullet
var bullets = '' + i + '';
// active slide
$(slides[0]).addClass('active');
}
$('.slider-nav').append(bullets);
}
// Set (initial) z-index for each slide
var setZindex = function() {
for (var i = 0; i < slidesCount; i++) {
$(slides[i]).css('z-index', slidesCount - i);
}
}
setZindex();
$('.slider-nav a').on('click', function() {
activeIdx = $(this).text();
$('.slider-nav a').removeClass('activeSlide');
$(this).addClass('activeSlide');
setActiveSlide();
slideUpDown();
});
var setActiveSlide = function() {
$(slides).removeClass('active');
$(slides[activeIdx]).addClass('active');
}
var slideUpDown = function() {
// set top property for all the slides
$(slides).css('top', slideHeight);
// then animate to the next slide
$(slides[activeIdx]).animate({
'top': 0
});
}
body {
margin: 0;
padding: 0;
}
body * {
box-sizing: border-box;
}
.container {
max-width: 1200px;
margin: 0 auto;
}
.slider {
width: 100%;
height: 300px;
position: relative;
overflow: hidden;
}
.slider .slider-nav {
position: absolute;
left: 10px;
bottom: 10px;
z-index: 30;
}
.slider .slider-nav a {
display: block;
float: left;
width: 10px;
height: 10px;
border-radius: 50%;
margin-right: 3px;
text-indent: -9999px;
background: #fff;
}
.slider .slider-nav a.activeSlide {
background: transparent;
border: 2px solid #fff;
}
.slider .slider-container {
width: 100%;
text-align: center;
}
.slider .slider-container a {
display: block;
position: absolute;
top: 0;
left: 0;
right: 0;
}
.slider .slider-container img {
transform: translateX(-50%);
margin-left: 50%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div class="container">
<div class="slider slider-homepage">
<div class="slider-nav"></div>
<div class="slider-container">
<a href="#">
<img src="https://picsum.photos/1200/300/?gravity=east" alt="">
</a>
<a href="#">
<img src="https://picsum.photos/1200/300/?gravity=south" alt="">
</a>
<a href="#">
<img src="https://picsum.photos/1200/300/?gravity=north" alt="">
</a>
</div>
</div>
</div>
The problem with my code is the (obvious) white screen that accompanies every transition, whose cause I do not understand.
Where is my mistake?
I have added some variable and function to fix this issue kindly check the script.
var $elm = $('.slider'),
$slidesContainer = $elm.find('.slider-container'),
slides = $slidesContainer.children('a'),
slidesCount = slides.length,
slideHeight = $(slides[0]).find('img').outerHeight(false);
//Set slide height
$(slides).css('height', slideHeight);
// Append bullets
for (var i = 0; i < slidesCount; i++) {
var bullets = '' + i + '';
if (i == 0) {
// active bullet
var bullets = '' + i + '';
// active slide
$(slides[0]).addClass('active');
}
$('.slider-nav').append(bullets);
}
// Set (initial) z-index for each slide
var setZindex = function () {
for (var i = 0; i < slidesCount; i++) {
$(slides[i]).css('z-index', slidesCount - i);
}
}
setZindex();
var displayImageBeforeClick = null;
$('.slider-nav a').on('click', function () {
displayImageBeforeClick = $(".slider-container .active");
activeIdx = $(this).text();
if($(slides[activeIdx]).hasClass("active")){ return false; }
$('.slider-nav a').removeClass('activeSlide');
$(this).addClass('activeSlide');
setActiveSlide();
slideUpDown();
});
var setActiveSlide = function () {
$(slides).removeClass('active');
$(slides[activeIdx]).addClass('active');
}
var slideUpDown = function () {
// set top property for all the slides
$(slides).not(displayImageBeforeClick).css('top', slideHeight);
// then animate to the next slide
$(slides[activeIdx]).animate({
'top': 0
});
$(displayImageBeforeClick).animate({
'top': "-100%"
});
}
body {
margin: 0;
padding: 0;
}
body * {
box-sizing: border-box;
}
.container {
max-width: 1200px;
margin: 0 auto;
}
.slider {
width: 100%;
height: 300px;
position: relative;
overflow: hidden;
}
.slider .slider-nav {
position: absolute;
left: 10px;
bottom: 10px;
z-index: 30;
}
.slider .slider-nav a {
display: block;
float: left;
width: 10px;
height: 10px;
border-radius: 50%;
margin-right: 3px;
text-indent: -9999px;
background: #fff;
}
.slider .slider-nav a.activeSlide {
background: transparent;
border: 2px solid #fff;
}
.slider .slider-container {
width: 100%;
text-align: center;
}
.slider .slider-container a {
display: block;
position: absolute;
top: 0;
left: 0;
right: 0;
}
.slider .slider-container img {
transform: translateX(-50%);
margin-left: 50%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div class="container">
<div class="slider slider-homepage">
<div class="slider-nav"></div>
<div class="slider-container">
<a href="#">
<img src="https://picsum.photos/1200/300/?gravity=east" alt="">
</a>
<a href="#">
<img src="https://picsum.photos/1200/300/?gravity=south" alt="">
</a>
<a href="#">
<img src="https://picsum.photos/1200/300/?gravity=north" alt="">
</a>
</div>
</div>
</div>
Add Transition to your ".slider .slider-container a" with a transition-duration and transition-timing-function.... for reference you can see https://www.w3schools.com/css/css3_transitions.asp

Making a jQuery carousel automatically slide

So I've created my image slider and it is set to slide when one of the buttons is clicked. But now I'm struggling to make the slide automatically and stop when the mouse hovers over the sider. Could you show me or at least tell me how to do this? Thanks
$(document).ready(function(){
var slide_count = $(".carousel li").length;
var slide_width = $(".carousel li").width();
var slide_height = $(".carousel li").height();
var cont_width = slide_width * slide_count;
$(".cont").css({ height: slide_height, width: slide_width});
$(".carousel").css({ width: cont_width, marginLeft: - slide_width });
$(".carousel li:last-child").prependTo(".carousel");
function next_slide(){
$(".carousel").animate({
left: + slide_width
}, 400, function(){
$(".carousel li:last-child").prependTo(".carousel");
$('.carousel').css('left', 0);
}
);
}
function prev_slide(){
$(".carousel").animate({
left: - slide_width
}, 400, function(){
$(".carousel li:first-child").appendTo(".carousel");
$(".carousel").css("left", 0);
}
);
}
$("#next").click(function(){
next_slide();
});
$("#prev").click(function(){
prev_slide();
});
});
*{
padding: 0;
margin: 0;
}
body{
margin: 0;
padding: 0;
}
.cont{
position: relative;
text-align: center;
font-size: 0;/*removes white space*/
margin: 60px auto 0 auto;
padding: 0;
overflow: hidden;
}
.carousel{
position: relative;
margin: 0;
padding: 0;
list-style-type: none;
height: 100%;
max-height: 600px;
}
.carousel li{
float: left;
width: 750px;
height: 350px;
}
.carousel li img{
width: 100%;
height: auto;
}
#next{
position: absolute;
top: 45%;
right: 0;
width: 40px;
height: 40px;
background-color: blue;
font-size: 0;
z-index: 1;
}
#prev{
position: absolute;
top: 45%;
left: 0;
width: 40px;
height: 40px;
background-color: blue;
z-index: 1;
}
<div class="cont">
<div id="next">
</div>
<div id="prev">
</div>
<ul class="carousel">
<li>
<img src="http://lorempixel.com/output/abstract-q-c-1500-700-2.jpg" alt="" />
</li>
<li>
<img src="http://lorempixel.com/output/abstract-q-c-1500-700-6.jpg" alt="" />
</li>
<li>
<img src="http://lorempixel.com/output/abstract-q-c-1500-700-1.jpg" alt="" />
</li>
<li>
<img src="http://lorempixel.com/output/abstract-q-c-1500-700-3.jpg" alt="" />
</li>
</ul>
</div>
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
You can achieve that by creating a setInterval() where you call your slider function every x seconds, and put a flag on it to not run if the mouse is over it.
Something like
var SECONDS_INTERVAL = 1000; // 1s
var mouseHoverFlag = false;
setInterval(function() {
if (!mouseHoverFlag) {
next_slide();
}
}, SECONDS_INTERVAL);
And change that mouseHoverFlag to true whenever the user has the mouse over the div that contains it.
$('.carousel').hover(function() {
mouseHoverFlag = true;
}, function () {
mouseHoverFlag = false;
});
You could use setTimeout and kill it every time that the mouse gets in but I think that's too heavy, performance wise.
Here is my edited version. We have to use setInterval function for automatic slide. Next we add hover event listener to carousel. If we are hovering, our variable preventSlide will change to true and if we stop hovering, variable will be changed back to false, which means auto slide.
var preventSlide = false;
$(".carousel").hover(function() {
preventSlide = true;
}, function() {
preventSlide = false;
});
setInterval(function () {
if (!preventSlide)
next_slide();
}, 3500);
$(document).ready(function(){
var slide_count = $(".carousel li").length;
var slide_width = $(".carousel li").width();
var slide_height = $(".carousel li").height();
var cont_width = slide_width * slide_count;
$(".cont").css({ height: slide_height, width: slide_width});
$(".carousel").css({ width: cont_width, marginLeft: - slide_width });
$(".carousel li:last-child").prependTo(".carousel");
function next_slide(){
$(".carousel").animate({
left: + slide_width
}, 400, function(){
$(".carousel li:last-child").prependTo(".carousel");
$('.carousel').css('left', 0);
}
);
}
function prev_slide(){
$(".carousel").animate({
left: - slide_width
}, 400, function(){
$(".carousel li:first-child").appendTo(".carousel");
$(".carousel").css("left", 0);
}
);
}
var preventSlide = false;
$(".carousel").hover(function() {
preventSlide = true;
}, function() {
preventSlide = false;
});
setInterval(function () {
if (!preventSlide)
next_slide();
}, 3500);
/*$("#next").click(function(){
next_slide();
});
$("#prev").click(function(){
prev_slide();
});*/
});
*{
padding: 0;
margin: 0;
}
body{
margin: 0;
padding: 0;
}
.cont{
position: relative;
text-align: center;
font-size: 0;/*removes white space*/
margin: 60px auto 0 auto;
padding: 0;
overflow: hidden;
}
.carousel{
position: relative;
margin: 0;
padding: 0;
list-style-type: none;
height: 100%;
max-height: 600px;
}
.carousel li{
float: left;
width: 750px;
height: 350px;
}
.carousel li img{
width: 100%;
height: auto;
}
#next{
position: absolute;
top: 45%;
right: 0;
width: 40px;
height: 40px;
background-color: blue;
font-size: 0;
z-index: 1;
}
#prev{
position: absolute;
top: 45%;
left: 0;
width: 40px;
height: 40px;
background-color: blue;
z-index: 1;
}
<div class="cont">
<div id="next">
</div>
<div id="prev">
</div>
<ul class="carousel">
<li>
<img src="http://lorempixel.com/output/abstract-q-c-1500-700-2.jpg" alt="" />
</li>
<li>
<img src="http://lorempixel.com/output/abstract-q-c-1500-700-6.jpg" alt="" />
</li>
<li>
<img src="http://lorempixel.com/output/abstract-q-c-1500-700-1.jpg" alt="" />
</li>
<li>
<img src="http://lorempixel.com/output/abstract-q-c-1500-700-3.jpg" alt="" />
</li>
</ul>
</div>
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
You should add a setInterval and clearInterval for automatic slide. Also it is good to calculate which slide you are in at the current animation. Briefly,
var timer;
var rotator = function(){
nextSlide();
};
timer = setInterval(rotator, 5000); // your desired timer
$('.carousel').hover(function(){ clearInterval(timer), function(){ timer = setInterval(rotator, 5000); });
you can optimize the code far better, but the basic solution is like this.
$(function(){
setInterval(function () {
moveRight();
}, 3000);
});
check here
You can set the time interval as an option in the carousel. You can also set the pause option on hover.
$("#myCarousel").carousel({interval: 500, pause: "hover"});

where am i going wrong with my rolling banner code to get it scrolling correctly

I was wondering could any one help me with my rolling banner. the problem i am having is that when it loads up on the screen it only moves threw one pic. the code i am using is measured to fit across the top of my page just over the nav bar.
$(function () {
//settings for slider
var width = 1165;
var animationSpeed = 2000;
var pause = 1000;
var currentSlide = 1;
//cache DOM elements
var $slider = $('#slider');
var $slideContainer = $('.slides', $slider);
var $slides = $('.slide', $slider);
var interval;
function startSlider() {
interval = setInterval(function () {
$slideContainer.animate({
'margin-left': '-=' + width
}, animationSpeed, function () {
if (++currentSlide === $slides.length) {
currentSlide = 1;
$slideContainer.css('margin-left', 0);
}
});
}, pause);
}
function pauseSlider() {
clearInterval(interval);
}
$slideContainer.on('mouseenter', pauseSlider)
.on('mouseleave', startSlider);
startSlider();
});
#slider {
width: 1165px;
height: 100px;
overflow: hidden;
}
#slider .slides {
display: block;
width: 1165px;
height: 100px;
margin: 0;
padding: 0;
}
#slider .slide {
float: left;
list-style-type: none;
width: 1165px;
height: 100px;
}
.slide1 {
background: red;
}
.slide2 {
background: blue;
}
.slide3 {
background: green;
}
.slide4 {
background: purple;
}
.slide5 {
background: pink;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="Container">
<div id="slider">
<ul class="slides">
<li class="slide slide1">slide1</li>
<li class="slide slide2">slide2</li>
<li class="slide slide3">slide3</li>
<li class="slide slide4">slide4</li>
<li class="slide slide5">slide5</li>
<li class="slide slide1">slide1</li>
</ul>
</div>
</div>
i think my problem is with my measurements i don't fully understand it, to know what to change???? the pictures i am using are width 2192px * height 220px, that might explain were i am getting my measurements
Your code is fine I think. The actual problem is that your li elements are stacked vertically, because they are all floated and floats line-wrap when they get too big for their parent.
Instead of floating them all, you can try using display: inline-block; on each .slide, and white-space: nowrap; on the .slides
Here is an example, the only changes from your original are CSS:
$(function () {
//settings for slider
var width = 1165;
var animationSpeed = 2000;
var pause = 1000;
var currentSlide = 1;
//cache DOM elements
var $slider = $('#slider');
var $slideContainer = $('.slides', $slider);
var $slides = $('.slide', $slider);
var interval;
function startSlider() {
interval = setInterval(function () {
$slideContainer.animate({
'margin-left': '-=' + width
}, animationSpeed, function () {
if (++currentSlide === $slides.length) {
currentSlide = 1;
$slideContainer.css('margin-left', 0);
}
});
}, pause);
}
function pauseSlider() {
clearInterval(interval);
}
$slideContainer.on('mouseenter', pauseSlider)
.on('mouseleave', startSlider);
startSlider();
});
#slider {
width: 1165px;
height: 100px;
overflow: hidden;
}
#slider .slides {
display: block;
width: 1165px;
height: 100px;
margin: 0;
padding: 0;
white-space: nowrap;
font-size: 0em;
}
#slider .slide {
list-style-type: none;
width: 1165px;
height: 100px;
display: inline-block;
font-size: 1rem;
}
.slide1 {
background: red;
}
.slide2 {
background: blue;
}
.slide3 {
background: green;
}
.slide4 {
background: purple;
}
.slide5 {
background: pink;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="Container">
<div id="slider">
<ul class="slides">
<li class="slide slide1">slide1</li>
<li class="slide slide2">slide2</li>
<li class="slide slide3">slide3</li>
<li class="slide slide4">slide4</li>
<li class="slide slide5">slide5</li>
<li class="slide slide1">slide1</li>
</ul>
</div>
</div>

Implement nav dots to my slider?

I've been messing around with my slider and I got it to slide by itself. The problem is, there is no way you can manually view the slides. I would like to add navigation dots on the bottom so you can skim through the slides without having to view them as the slider goes along. If you could help me with this it would be greatly appreciated.
My slider html:
<div id="slider-container">
<div style="position: relative">
<div class="slide"><img id="slide_1" src="images/slide_1.jpg"/></div>
<div class="slide"><img id="slide_2" src="images/slide_2.jpg"/></div>
<div class="slide"><img id="slide_3" src="images/slide_3.jpg"/></div>
<div class="slide"><img id="slide_4" src="images/slide_4.jpg"/></div>
<div class="slide"><img id="slide_5" src="images/slide_5.jpg"/></div>
<div class="slide"><img id="slide_6" src="images/slide_6.jpg"/></div>
</div>
</div>
My slider css:
.slide-container {
display:block;
}
.slide {
top:0;
width:760px;
height:420px;
display:block;
position:absolute;
transform:scale(0);
transition:all .7s;
}
.slide img {
width:100%;
height:100%;
border-radius:6px;
border:1px solid #95ca1a;
}
My slider javascript:
$(document).ready(function() {
(function (){
var count = $(".slide > img").length;
var current = 1;
var sliderNext = 2;
$("img[id^='slide_']").fadeOut(0);
$("#slide_" + current).fadeIn(300);
var loop = setInterval(function() {
$("#slide_" + current).fadeOut(300);
$("#slide_" + sliderNext).fadeIn(300);
(sliderNext >= count) ? sliderNext = 1 : sliderNext++;
(current >= count) ? current = 1 : current++;
}, 3000)
})()
});
Here's an example of what I mean by nav dots:
CSS Slider - Codepen
First create list of dots, you can do it manually by creating list of "li" tags or can create it via jQuery.
here is code
<ol>
<li></li>
<li></li>
<li></li>
</ol>
number of "li" element should match with number of images
then have following css
#slider-container {
position:relative;
overflow:hidden;
width:100%;
height:380px;
display:inline-block;
}
.slide {
top:0;
width:100%;
display:inline-block;
}
.slide img {
width:100%;
height:100%;
border-radius:6px;
border:1px solid #95ca1a;
}
/******* css of dots ****/
ol{
list-style= none;
width:100%;
}
ol li{
background: #888;
border-radius: 50%;
display: inline-block;
width:20px;
height:20px;
cursor: pointer;
}
then add following jQuery stuff
$('ol li').bind('click', function(){
var index = $(this).index() + 1;
$(".active").fadeOut(300);
$("#slide_" + index).fadeIn(300);
$(".slide").removeClass("active");
$("#slide_" + index).addClass("active");
});
this code will hide active image and shows selected image
here is Fiddle example
hope it will help you
Here is a carousel script I wrote for a project. This allows you to click forward and backward and also on the dots. It's also dynamic so if you have 1 image, there are no dots or scroll bars, if you have 2 images there are the bars to go right and left but no dots, once you have three or more images the dots will be applied.
JsFiddle
HTML
<div class="carousel-container">
<div class="left-arrow"></div>
<div class="right-arrow"></div>
<div class="carousel-image-holder">
<img src="http://digitaljournal.com/img/8/7/8/4/4/i/1/1/7/o/ulingan_kids.jpg" />
<img src="http://freethoughtblogs.com/taslima/files/2012/06/22-funny2.jpg" />
<img src="http://blog.metrotrends.org/wp-content/uploads/2013/09/childPoverty.jpg" />
<img src="http://www.chinadaily.com.cn/china/images/2010WenUN/attachement/jpg/site1/20100921/0013729ece6b0e01d9691a.jpg" />
</div>
</div>
<div class="clear"></div>
<div class="carousel-buttons-container">
<ul></ul>
</div>
CSS
.clear{clear:both;}
.carousel-container{
width: 600px;
height: 360px;
float: left;
margin: 0;
padding: 0;
position: relative;
overflow: hidden;
}
.right-arrow{
width: 60px;
height: 100%;
background-color: rgba(0,0,0,.5);
position: absolute;
right: 0;
margin: 0;
padding: 0;
z-index: 2;
}
.left-arrow{
width: 60px;
height: 100%;
background-color: rgba(0,0,0,.5);
position: absolute;
left: 0;
margin: 0;
padding: 0;
z-index: 2;
}
.carousel-image-holder{
height:360px;
width: 2400px;
margin: 0;
padding: 0;
position: absolute;
z-index: 1;
}
.carousel-image-holder img{
width: 600px;
float: left;
margin: 0;
padding: 0;
display: inline-block;
}
.carousel-buttons-container{
width: 600px;
text-align: center;
margin: 15px 0 0 0;
padding: 0;
}
.carousel-buttons-container ul{
list-style-type: none;
margin: 0;
padding: 0;
}
.carousel-buttons{
background-color: #dddddd;
height: 18px;
width: 18px;
border-radius: 50%;
display: inline-block;
margin: 0 10px 0 0;
padding: 0;
cursor: pointer;
}
.carousel-buttons:last-of-type{
margin: 0;
}
.active{
background-color: #e67e22;
}
JQUERY
$(".left-arrow").hide();
var numImgs = $('div.carousel-image-holder img').length;
var addId = numImgs;
if(numImgs == 2){
var clicked = 0;
imgCount = numImgs-2;
}else if(numImgs <= 1){
$(".right-arrow").hide();
}else{
var clicked = 1;
imgCount = numImgs-1;
}
if(numImgs > 2){
for (var i=0; i<numImgs; i++){
$("ul").prepend('<li class="carousel-buttons" id="carousel'+addId+'"></li>');
var addId = addId - 1;
}
}else{
}
$(".carousel-buttons").click(function(){
var findIdClicked = $(this).attr("id");
var splitString = findIdClicked.split("carousel")
var findTheNumb = splitString[1];
$(".carousel-buttons").removeClass("active");
$(this).addClass("active");
clicked = parseInt(findTheNumb);
var adjustNumberforSlide = findTheNumb-1;
$(".carousel-image-holder").animate({"left": -(600*adjustNumberforSlide)+"px"});
console.log(clicked);
if(findTheNumb == 1){
$(".left-arrow").hide();
$(".right-arrow").show();
}else if (findTheNumb == numImgs){
$(".right-arrow").hide();
$(".left-arrow").show();
}else{
$(".right-arrow").show();
$(".left-arrow").show();
}
});
$(".carousel-buttons-container").find("li").first().addClass("active");
$(".right-arrow").click(function(){
if (clicked < imgCount){
$(".carousel-image-holder").animate({"left": "-=600px"});
console.log(clicked);
}else{
$(".carousel-image-holder").animate({"left": "-=600px"});
$(".right-arrow").hide();
console.log(clicked);
}
clicked = clicked+1;
$(".left-arrow").show();
$(".carousel-buttons").removeClass("active");
$("#carousel"+clicked).addClass("active");
});
$(".left-arrow").click(function(){
if (clicked > 2){
$(".carousel-image-holder").animate({"left": "+=600px"});
console.log(clicked);
}else{
$(".carousel-image-holder").animate({"left": "+=600px"});
$(".left-arrow").hide();
console.log(clicked);
}
$(".right-arrow").show();
clicked = clicked-1;
$(".carousel-buttons").removeClass("active");
$("#carousel"+clicked).addClass("active");
});
I'll clean up the spacing, just wanted to get this posted

Categories

Resources