Triggers not working properly in Jquery slideshow - javascript

I made a slideshow in jquery but I am having a hard time to make a proper algorithm for triggers to become functional.
Any help in this regard would be highly appreciated.
Demo available here
HTML
<div class=slide-show>
<div id=slide1><h1>1</h1></div>
<div id=slide2><h1>2</h1></div>
<div id=slide3><h1>3</h1></div>
<div id=slide4><h1>4</h1></div>
</div>
<div class=slide-controls>
<div class=slide-controls-wrap>
<ul style="float:left;">
<li class=slide-cont id=1></li>
<li class=slide-cont id=2></li>
<li class=slide-cont id=3></li>
<li class=slide-cont id=4></li>
</ul>
<ul style="float:right;margin-right:50px;margin-top:2px;">
<li class=left-arrow></li>
<li class=right-arrow></li>
</ul>
</div>
</div>
JQUERY
$(document).ready(function () {
var delayInterval = 5000;
var delay = setTimeout;
function slide_show(cont) {
if (cont > 4) cont = 1;
$("#slide" + cont).fadeIn(1500);
$("#" + cont).css("background-position", '-69px -94px');
delay(function () {
$("#slide" + cont).fadeOut(1500);
$("#" + cont).css("background-position", '-19px -94px');
$('#1').click(function () {
slide_show(1);
});
$('#2').click(function () {
slide_show(2);
});
$('#3').click(function () {
slide_show(3);
});
$('#4').click(function () {
slide_show(4);
});
slide_show(cont + 1);
//$("#5").css("background-position",'-69px -94px');
}, delayInterval);
}
slide_show(1);
});
Thanks in advance.

Demo: http://codepen.io/anon/pen/azpwMy
Here is a better function for you :)
$(document).ready(function(){
$('.slide-cont').click(function(){
var slideId = $(this).attr('id');
currentSlide = slideId - 1;
$(slides).hide();
$('#slide' + slideId).fadeIn(1500);
})
})
var slides = $('.slide-show div');
currentSlide = 0;
function changeSlide(n) {
currentSlide += n;
if (currentSlide > slides.length - 1)
currentSlide = 0;
else if(currentSlide < 0)
currentSlide = slides.length -1;
$(slides).hide();
$(slides[currentSlide]).fadeIn(1500);
}
If you want to go one to the right you call with changeSlide(1), to the left changeSlide(-1)
To change the current slide based on time.
//Go one slide to the right every 2 seconds
setInterval(function(){changeSlide(1)}, 2000);
Hope i helped!

Related

Javascript run 2 functions on button click with multiple buttons and same class

I have a portfolio grid that has a screenshot of past work in each grid item.
Currently on button click, it calls a function to scroll the screenshot and stop once it reaches the bottom of the image.
I need to reverse the scroll once the button is clicked again. The scroll is created by a setInterval. I have a class of "down" on the button which is removed on click.
I have an if statement that does not work to check if the class of "down" is present and run a scrollUp function.
This is a PHP loop so there are multiple buttons with same class.
I cannot use jQuery.
Thanks for any help!
HTML:
<ul>
<li>
<div class="image-container overflow-hidden height-500">
<img class="item absolute pin-t w-full h-auto pin-l"
src="/image.jpg"/>
</div>
<button class="portScroll down">Scroll Down</button>
</li>
<li class="web-design-portfolio">
<div class="image-container overflow-hidden height-500">
<img class="item absolute pin-t w-full h-auto pin-l"
src="/image.jpg"/>
</div>
<button class="portScroll down">Scroll Down</button>
</li>
</ul>
JS:
function scrollDown() {
var portImg = this.parentNode.parentNode.querySelector('img.item');
var height = portImg.clientHeight;
var pos = 0;
var id = setInterval(frame, 5);
function frame() {
if (pos == height - 500) {
clearInterval(id);
} else {
pos++;
portImg.style.top = - + pos + 'px';
}
}
for (const button of document.querySelectorAll('button.portScroll')) {
button.classList.remove('down');
}
}
for (const button of document.querySelectorAll('button.portScroll')) {
if (button.classList.contains("down")) {
button.addEventListener("click", scrollDown);
} else {
button.addEventListener("click", scrollUp);
}
}
Here is the working Codepen for scroll down:
https://codepen.io/completewebco/pen/bZeVoz
I created a single function that does what is needed. I hope that is OK.
function scrollUpOrDown(_this, state) {
var portImg = _this.parentNode.parentNode.querySelector('img.item');
var height = portImg.clientHeight;
if(state.id > -1) {
clearInterval(state.id);
state.dir *= -1;
}
if(state.pos < 0) {
state.pos = 1;
}
state.id = setInterval(frame, 5);
function frame() {
if ((state.pos == height - 500 && state.dir > 0) || (state.pos == 0 && state.dir < 0)) {
clearInterval(state.id);
} else {
state.pos += state.dir;
portImg.style.top = -+state.pos + "px";
}
}
}
for (const button of document.querySelectorAll("button.portScroll")) {
let scollingState = {
pos: -1,
id: -1,
dir: 1
};
if (button.classList.contains("down")) {
button.addEventListener("click", function(){
scrollUpOrDown(this,scollingState);
});
}
}
https://codepen.io/prtjohanson/pen/QoEyQK
If you are wondering why/how it works, look at the output of this code
var array = [0,1,2,3,4,5];
for(const i in array) {
setTimeout(function(){console.log(i)}, Math.random()*1000)
}
and read https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let#Scoping_rules_2

Add class when X class is been removed via JS

I am trying to add a class to a div when another class is been removed with JS.
This is my HTML:
<body class="homepage">
<div id="wrap">
<div id="projects">
<section id="project-0" class="slide active"> Slide 1</section>
<section id="project-1" class="slide active"> Slide 2</section>
<section id="project-2" class="slide active"> Slide 3</section>
</div>
</div>
<div class="content"> Website main content </div>
This is a vertical slide, so when you scroll down, the active class is removed with JS. What I want to achieve is to add a class to body when the active is removed from project-2.
This is what I have so far, but it doesn't recognise the class active because it's been added via JS...
if(!$("#project-2").hasClass("active")){
$("body").addClass("shifted");
}
JS:
var delta = 0;
var currentSlideIndex = 0;
var scrollThreshold = 30;
var slides = $(".slide");
var numSlides = slides.length;
function elementScroll (e) {
console.log (Math.abs(delta));
// --- Scrolling up ---
if (e.originalEvent.detail < 0 || e.originalEvent.wheelDelta > 0) {
delta--;
if ( Math.abs(delta) >= scrollThreshold) {
prevSlide();
}
}
// --- Scrolling down ---
else {
delta++;
if (delta >= scrollThreshold) {
nextSlide();
}
}
// Prevent page from scrolling
return false;
}
function showSlide() {
// reset
delta = 0;
slides.each(function(i, slide) {
$(slide).toggleClass('active', (i >= currentSlideIndex));
});
}
function prevSlide() {
currentSlideIndex--;
if (currentSlideIndex < 0) {
currentSlideIndex = 0;
}
showSlide();
}
function nextSlide() {
currentSlideIndex++;
if (currentSlideIndex > numSlides) {
currentSlideIndex = numSlides;
}
showSlide();
}
$(window).on({
'DOMMouseScroll mousewheel': elementScroll
});
You can see here how it works
Thanks
By looking at your JS code I believe you want to add class to body while scrolling down. You may try below code:
function prevSlide() {
currentSlideIndex--;
if(currentSlideIndex == (numSlides-1))
{
$("body").removeClass("shifted"); // remove the class from body
}
if (currentSlideIndex < 0) {
currentSlideIndex = 0;
}
showSlide();
}
function nextSlide() {
currentSlideIndex++;
if (currentSlideIndex > numSlides) {
currentSlideIndex = numSlides;
$("body").addClass("shifted"); // add the class to body
}
showSlide();
}
Your check for the absence of the class is only started once. You had to do this with an interval from 100 ms or whatever you want:
setInterval(function()
{
if (!$("#project-2").hasClass("active")){
$("body").addClass("shifted");
}
}, 100);

Linking to a certain position of another page

I have a mainpage called index.html with a menu linking to certain positions (parts) on this mainpage. This is done via the variable 'data-slide' (see below) that is behind the 'buttons' in the menu. This works well on the mainpage. However, how can I do this when I'm on another html page than the mainpage, jumping to a certain position (part) of the mainpage?
<div id="nav" class="right">
<ul class="navigation">
<li data-slide="1">Home</li>
<li data-slide="2">Products</li>
<li data-slide="4">Trade fairs</li>
<li data-slide="6">Company</li>
<li data-slide="8">Careers</li>
<li data-slide="10">Contact</li>
<li class="clear"></li>
</ul>
</div>
Javascript:
var links = $('.navigation').find('li');
slide = $('.slide');
button = $('.button');
mywindow = $(window);
htmlbody = $('html,body');
slide.waypoint(function (event, direction) {
dataslide = $(this).attr('data-slide');
if (direction === 'down') {
$('.navigation li[data-slide="' + dataslide + '"]').addClass('active').prev().removeClass('active');
$('.navigation li[data-slide="1"]').removeClass('active');
}
else {
$('.navigation li[data-slide="' + dataslide + '"]').addClass('active').next().removeClass('active');
}
});
mywindow.scroll(function () {
if (mywindow.scrollTop() == 0) {
$('.navigation li[data-slide="1"]').addClass('active');
$('.navigation li[data-slide="2"]').removeClass('active');
}
});
function goToByScroll(dataslide) {
var goal = $('.slide[data-slide="' + dataslide + '"]').offset().top;
if (mywindow.scrollTop()<goal) {
var goalPx = goal + 1;
} else {
var goalPx = goal - 1;
}
htmlbody.animate({
scrollTop: goalPx
}, 2500, 'easeInOutQuint');
}
links.click(function (e) {
e.preventDefault();
dataslide = $(this).attr('data-slide');
goToByScroll(dataslide);
});
button.click(function (e) {
e.preventDefault();
dataslide = $(this).attr('data-slide');
goToByScroll(dataslide);
});
window.setTimeout(function(){
if(window.location.hash){
var $target = $(window.location.hash).closest("#bgaboutbody");
if($target.length)
$('html, body').animate({scrollTop: $target.offset().top}, 1000);
}
}, 100);
Please try this link:-anchor linking to a certain position of the page

menu traversing on next and prev button click

can any one optimize this code i am new to jquery .
i want add class on next and previous button click.any way i wrote this code it's working for me but if any one optimize this code using jquery predefined methods .then it will more helpful..
Thanks in advance
$(document).ready(function () {
var length = $('#slides li').size() - 1;
var curren = 0;
console.log(length);
$('.next').on('click', function () {
if (curren >= 0 && curren < length) {
curren++;
$('.selected').removeClass('selected');
$('#slides li:eq(' + curren + ')').addClass('selected');
}
});
$('.prev').on('click', function () {
if (curren >= 1) {
curren--;
$('.selected').removeClass('selected');
$('#slides li:eq(' + curren + ')').addClass('selected');
}
});
});
my html code
<ul id="slides">
<li class="selected">first</li>
<li>second</li>
<li>third</li>
<li>fourth</li>
<li>five</li>
<li>six</li>
</ul>
You should have a look at $.next and $.prev.
Your code can easily be altered into something along these lines:
$(".next").on("click", function() {
var selected = $("#slides li.selected");
var next = selected.next();
if(next.length){next.addClass("selected");selected.removeClass("selected");}
});
$(".prev").on("click", function() {
var selected = $("#slides li.selected");
var prev = selected.prev();
if(prev.length){prev.addClass("selected");selected.removeClass("selected");}
});
Example can be found here: jsbin

I want to create image gallery with infinite loop using jquery

I want to create an image gallery, I wrote for a slideshow, but I don't know how to code for the previous and next buttons. These should work like an infinite loop (last image jumps back to the first).
How should I get started? This is what I have so far:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#play").click(function () {
$("#img1").fadeOut(2000);
$("#img2").fadeIn();
$("#img2").fadeOut(4000);
$("#img3").fadeIn();
});
});
</script>
<body>
<div id=outer>
<div id=inner>
<img id="img1" src="img1.jpg"/>
<img id="img2" src="img2.jpg" style="display:none"/>
<img id="img3" src="img3.jpg" style="display:none"/>
</div>
<div id=button>
<button id="bwd"><<</button>
<button id="play"><></button>
<button id="fwd">>></button>
</div>
</div>
</body>
You can use setInterval() .
This link can help you to understand much more
Call function with setInterval in jQuery?
may be this can help you too :
http://jquery.malsup.com/cycle/
you're going to want to use the javascript timing function. Something like:
$('#play').click(function(){
window.setInterval(function(){
if($('#img1').is(:visible)){
$("#img2").show()
$("#img1").hide()
}
if($('#img2').is(:visible)){
$('#img3').show()
$('#img2').hide()
}
if($('#img3').is(:visible)){
$('#img1').show()
$('#img3').hide()
}
}, 1000);
});
You can also condense this logic down, but this gets you the basic idea. Then if you look carefully the functions for next is already in the code and it can be extracted out and reuses. Once you have the next function it's pretty straight forward that the back function will be the exact opposite.
To answer your question below you can change the img's to have the same class and then apply show and hide based on which one is visible and the image immediately after the visible one:
#find the one currently being shown
$(".images:visible")
#find the one after the visible one
$(".images:visible").next()
#keep an id on the last image so that you can do something like
if($('.images:visible') == $('#last_image')){
$('.images').first().show()
}
Hi i have created Carousel without using any third party plugin.If you want please refer.Reference Link
Js Code is.
$(document).ready(function () {
var currentPosition = 0;
var slideWidth = 300;
var slides = $('.slide');
var numberOfSlides = slides.length;
var timer = 3000;
var img1, img2;
var sliderLink = $("#slider a");
var direction = 1;
// Remove scrollbar in JS
$('#slidesContainer').css('overflow', 'hidden');
// Wrap all .slides with #slideInner // Float left to display horizontally, readjust .slides width
slides.wrapAll('<div id="slideInner"></div>').css({
'float': 'left',
'width': slideWidth
});
// Set #slideInner width equal to total width of all slides
$('#slideInner').css('width', slideWidth * numberOfSlides);
// Insert left and right arrow controls in the DOM
$('#slideshow').prepend('<span class="control" id="leftControl">Move left</span>').append('<span class="control" id="rightControl">Move right</span>');
// Hide left arrow control on first load
// manageControls(currentPosition);
// manageSlide();
// Create event listeners for .controls clicks
$('#rightControl').bind('click', rightControl);
$('#leftControl').bind('click', leftControl);
function leftControl() {
var butonid = 0;
direction = 0;
$("#slideInner").stop();
$("#slideInner").dequeue();
$('#timer').stop();
$('#timer').dequeue();
$('#leftControl').unbind('click');
manageSlide(0, direction);
setTimeout(function () {
$('#leftControl').bind('click', leftControl);
}, timer, null);
}
function rightControl() {
var butonid = 1;
direction = 1;
$("#slideInner").stop();
$("#slideInner").dequeue();
$('#timer').stop();
$('#timer').dequeue();
$('#rightControl').unbind('click');
manageSlide(0, direction);
setTimeout(function () {
$('#rightControl').bind('click', rightControl);
}, timer, null);
}
var slideIndex = 0;
var data = $("#slideInner .slide").toArray();
$("#slideInner").empty();
function manageSlide(auto, idButtonid) {
$("#slideInner").empty();
// console.log(slideIndex);
if (idButtonid == 0) {
$("#slideInner").css({ 'marginLeft': "-300px" });
$(data).each(function (index) {
// if (index == slideIndex - 1) {
// $(this).show();
// } else {
$(this).hide();
// }
});
$(data[slideIndex - 1]).show();
if (slideIndex == numberOfSlides - 1) {
slideIndex = 0;
img1 = data[0];
img2 = data[numberOfSlides - 1];
$("#slideInner").append(img1);
$("#slideInner").append(img2);
$(img2).show();
$(img1).show();
} else {
img1 = data[slideIndex];
img2 = data[slideIndex + 1];
$("#slideInner").append(img2);
$("#slideInner").append(img1);
$(img1).show();
$(img2).show();
slideIndex = slideIndex + 1;
}
$('#slideInner').animate({
'marginLeft': "0px"
}, 'slow', function () {
$('#timer').animate({
opacity: 1
}, timer, function () {
console.log('leftControl');
manageSlide(1, direction);
});
});
}
// right move here
else if (idButtonid == 1) {
$("#slideInner").css({ 'marginLeft': "0px" });
$(data).each(function (index) {
if (index == slideIndex + 1) {
$(this).show();
} else {
$(this).hide();
}
});
if (slideIndex == numberOfSlides - 1) {
slideIndex = 0;
img1 = data[0];
img2 = data[numberOfSlides - 1];
$("#slideInner").append(img2);
$("#slideInner").append(img1);
$(img2).show();
$(img1).show();
} else {
img1 = data[slideIndex];
img2 = data[slideIndex + 1];
$("#slideInner").append(img1);
$("#slideInner").append(img2);
$(img1).show();
$(img2).show();
slideIndex = slideIndex + 1;
}
$('#slideInner').animate({
'marginLeft': slideWidth * (-1)
}, 'slow', function () {
console.log('rightControl');
$('#timer').animate({
opacity: 1
}, timer, function () {
manageSlide(1, direction);
});
});
}
if (auto == 1) {
sliderLink.each(function () {
$(this).removeClass();
if ($(this).text() == (slideIndex + 1)) {
$(this).addClass('active');
}
});
}
auto = 1;
}
$("#slider a").click(function () {
sliderLink.each(function () {
$(this).removeClass();
});
slideIndex = $(this).addClass('active').text() - 1;
$('#timer').stop();
$('#timer').dequeue();
$("#slideInner").stop();
$("#slideInner").dequeue();
manageSlide(0, direction);
});
manageSlide(1, direction);
});
Demo Link
Hope it helps you.

Categories