How to translateX to a position without removing transition property? - javascript

I want to translateX to a position if change is more than -150, but due to having transition property in container it shows the animation of travelling to the new translate value. I want it to have directly jump to the -400px translateX value without showing the animation to going to it and still have the transition property in place for future scrolls
const config = {
individualItem: '.slide', // class of individual item
carouselWidth: 400, // in px
carouselId: '#slideshow', // carousel selector
carouselHolderId: '#slide-wrapper', // carousel should be <div id="carouselId"><div id="carouselHolderId">{items}</div></div>
}
document.addEventListener("DOMContentLoaded", function(e) {
// Get items
const el = document.querySelector(config.individualItem);
const elWidth = parseFloat(window.getComputedStyle(el).width) + parseFloat(window.getComputedStyle(el).marginLeft) + parseFloat(window.getComputedStyle(el).marginRight);
// Track carousel
let mousedown = false;
let movement = false;
let initialPosition = 0;
let selectedItem;
let currentDelta = 0;
document.querySelectorAll(config.carouselId).forEach(function(item) {
item.style.width = `${config.carouselWidth}px`;
});
document.querySelectorAll(config.carouselId).forEach(function(item) {
item.addEventListener('pointerdown', function(e) {
mousedown = true;
selectedItem = item;
initialPosition = e.pageX;
currentDelta = parseFloat(item.querySelector(config.carouselHolderId).style.transform.split('translateX(')[1]) || 0;
});
});
const scrollCarousel = function(change, currentDelta, selectedItem) {
let numberThatFit = Math.floor(config.carouselWidth / elWidth);
let newDelta = currentDelta + change;
let elLength = selectedItem.querySelectorAll(config.individualItem).length - numberThatFit;
if(newDelta <= 0 && newDelta >= -elWidth * elLength) {
selectedItem.querySelector(config.carouselHolderId).style.transform = `translateX(${newDelta}px)`;
// IMPORTANT LINE
if(newDelta <= 0 && newDelta <= -150) {
selectedItem.querySelector(config.carouselHolderId).style.transform = `translateX(-1000px)`;
}
}
}
document.body.addEventListener('pointermove', function(e) {
if(mousedown == true && typeof selectedItem !== "undefined") {
let change = -(initialPosition - e.pageX);
scrollCarousel(change, currentDelta, document.body);
movement = true;
}
});
['pointerup', 'mouseleave'].forEach(function(item) {
document.body.addEventListener(item, function(e) {
selectedItem = undefined;
movement = false;
});
});
});
.slide-wrapper {
transition: 400ms ease;
transform: translateX(0px);
width: 400px;
height: 400px;
}
.slide-number {
pointer-events: none;
}
<!DOCTYPE html>
<html>
<head>
<title>HTML and CSS Slideshow</title>
<style>
body {
font-family: Helvetica, sans-serif;
padding: 5%;
text-align: center;
font-size: 50;
overflow-x: hidden;
}
/* Styling the area of the slides */
#slideshow {
overflow: hidden;
height: 400px;
width: 400px;
margin: 0 auto;
}
/* Style each of the sides
with a fixed width and height */
.slide {
float: left;
height: 400px;
width: 400px;
}
/* Add animation to the slides */
.slide-wrapper {
/* Calculate the total width on the
basis of number of slides */
width: calc(728px * 4);
/* Specify the animation with the
duration and speed */
/* animation: slide 10s ease infinite; */
}
/* Set the background color
of each of the slides */
.slide:nth-child(1) {
background: green;
}
.slide:nth-child(2) {
background: pink;
}
.slide:nth-child(3) {
background: red;
}
.slide:nth-child(4) {
background: yellow;
}
/* Define the animation
for the slideshow */
#keyframes slide {
/* Calculate the margin-left for
each of the slides */
20% {
margin-left: 0px;
}
40% {
margin-left: calc(-728px * 1);
}
60% {
margin-left: calc(-728px * 2);
}
80% {
margin-left: calc(-728px * 3);
}
}
</style>
</head>
<body>
<!-- Define the slideshow container -->
<div id="slideshow">
<div id="slide-wrapper" class="slide-wrapper">
<!-- Define each of the slides
and write the content -->
<div class="slide">
<h1 class="slide-number">
1
</h1>
</div>
<div class="slide">
<h1 class="slide-number">
2
</h1>
</div>
<div class="slide">
<h1 class="slide-number">
3
</h1>
</div>
<div class="slide">
<h1 class="slide-number">
4
</h1>
</div>
</div>
</div>
</body>
</html>

If I understood your question properly, I think you would have to remove the transition property before changing the value and then apply it again once the transition is done.
const item = selectedItem.querySelector(config.carouselHolderId)
item.style.cssText = `transform: translateX(${newDelta}px); transition: none`;
// Restore the transition
item.style.transition = '';

You could temporarily disable the transition:
const config = {
individualItem: '.slide', // class of individual item
carouselWidth: 400, // in px
carouselId: '#slideshow', // carousel selector
carouselHolderId: '#slide-wrapper', // carousel should be <div id="carouselId"><div id="carouselHolderId">{items}</div></div>
}
document.addEventListener("DOMContentLoaded", function(e) {
// Get items
const el = document.querySelector(config.individualItem);
const elWidth = parseFloat(window.getComputedStyle(el).width) + parseFloat(window.getComputedStyle(el).marginLeft) + parseFloat(window.getComputedStyle(el).marginRight);
// Track carousel
let mousedown = false;
let movement = false;
let initialPosition = 0;
let selectedItem;
let currentDelta = 0;
document.querySelectorAll(config.carouselId).forEach(function(item) {
item.style.width = `${config.carouselWidth}px`;
});
document.querySelectorAll(config.carouselId).forEach(function(item) {
item.addEventListener('pointerdown', function(e) {
mousedown = true;
selectedItem = item;
initialPosition = e.pageX;
currentDelta = parseFloat(item.querySelector(config.carouselHolderId).style.transform.split('translateX(')[1]) || 0;
});
});
const scrollCarousel = function(change, currentDelta, selectedItem) {
let numberThatFit = Math.floor(config.carouselWidth / elWidth);
let newDelta = currentDelta + change;
let elLength = selectedItem.querySelectorAll(config.individualItem).length - numberThatFit;
if(newDelta <= 0 && newDelta >= -elWidth * elLength) {
selectedItem.querySelector(config.carouselHolderId).style.transform = `translateX(${newDelta}px)`;
// IMPORTANT LINE
if(newDelta <= 0 && newDelta <= -150) {
const el = selectedItem.querySelector(config.carouselHolderId);
el.classList.add("jump");
el.style.transform = `translateX(-1000px)`;
setTimeout(() => el.classList.remove("jump"), 10);
}
}
}
document.body.addEventListener('pointermove', function(e) {
if(mousedown == true && typeof selectedItem !== "undefined") {
let change = -(initialPosition - e.pageX);
scrollCarousel(change, currentDelta, document.body);
movement = true;
}
});
['pointerup', 'mouseleave'].forEach(function(item) {
document.body.addEventListener(item, function(e) {
selectedItem = undefined;
movement = false;
});
});
});
.slide-wrapper {
transform: translateX(0px);
width: 400px;
height: 400px;
transition: 400ms ease;
user-select: none;
}
.slide-number {
pointer-events: none;
}
.slide-wrapper.jump
{
transition-duration: 10ms;
}
<!DOCTYPE html>
<html>
<head>
<title>HTML and CSS Slideshow</title>
<style>
body {
font-family: Helvetica, sans-serif;
padding: 5%;
text-align: center;
font-size: 50;
overflow-x: hidden;
}
/* Styling the area of the slides */
#slideshow {
overflow: hidden;
height: 400px;
width: 400px;
margin: 0 auto;
}
/* Style each of the sides
with a fixed width and height */
.slide {
float: left;
height: 400px;
width: 400px;
}
/* Add animation to the slides */
.slide-wrapper {
/* Calculate the total width on the
basis of number of slides */
width: calc(728px * 4);
/* Specify the animation with the
duration and speed */
/* animation: slide 10s ease infinite; */
}
/* Set the background color
of each of the slides */
.slide:nth-child(1) {
background: green;
}
.slide:nth-child(2) {
background: pink;
}
.slide:nth-child(3) {
background: red;
}
.slide:nth-child(4) {
background: yellow;
}
/* Define the animation
for the slideshow */
#keyframes slide {
/* Calculate the margin-left for
each of the slides */
20% {
margin-left: 0px;
}
40% {
margin-left: calc(-728px * 1);
}
60% {
margin-left: calc(-728px * 2);
}
80% {
margin-left: calc(-728px * 3);
}
}
</style>
</head>
<body>
<!-- Define the slideshow container -->
<div id="slideshow">
<div id="slide-wrapper" class="slide-wrapper">
<!-- Define each of the slides
and write the content -->
<div class="slide">
<h1 class="slide-number">
1
</h1>
</div>
<div class="slide">
<h1 class="slide-number">
2
</h1>
</div>
<div class="slide">
<h1 class="slide-number">
3
</h1>
</div>
<div class="slide">
<h1 class="slide-number">
4
</h1>
</div>
</div>
</div>
</body>
</html>

Related

I've got a js appear effect issue

This is js and there is 4 articles should appear one at a time when I scroll down, but it doesn't work after aticle no.2. what did I wrong?
function scrollAppear(){
var main = document.querySelector("main");
var art = main.querySelectorAll("article");
var artPos1 = art[0].getBoundingClientRect().top;
var artPos2 = art[1].getBoundingClientRect().top;
var artPos3 = art[2].getBoundingClientRect().top;
var artPos4 = art[3].getBoundingClientRect().top;
var artPos5 = art[4].getBoundingClientRect().top;
var screenPos = window.innerHeight /1.3;
if (artPos1>600 && artPos1<700) {
art[0].classList.add('appear');
}
else if (artPos2<500) {
art[1].classList.add('appear');
}
else if (artPos3<800) {
art[2].classList.add('appear');
}
else if (artPos4<600) {
art[3].classList.add('appear');
}
else if (artPos5<600) {
art[4].classList.add('appear');
}
}
window.addEventListener('scroll',scrollAppear);
If they all need to appear at the same spot, shouldn't the same condition work for each?
if (artPos1>600 && artPos1<700) {
art[0].classList.add('appear');
}
else if (artPos2>600 && artPos2<700) {
art[1].classList.add('appear');
}
else if (artPos3>600 && artPos3<700) {
art[2].classList.add('appear');
}
else if (artPos4>600 && artPos4<700) {
art[3].classList.add('appear');
}
else if (artPos5>600 && artPos5<700) {
art[4].classList.add('appear');
}
Consider the following jQuery example.
function scrollAppear() {
var main = $("#main");
var art = $("article");
var screenPos = $(window).scrollTop();
art.each(function(i, el) {
if (screenPos >= $(el).css("top").slice(0, -2) - 120) {
$(el).fadeIn(100).addClass("appear");
}
});
}
window.addEventListener('scroll', scrollAppear);
#main {
position: relative;
height: 2000px;
}
article {
width: 100%;
height: 100px;
position: absolute;
display: none;
}
.red {
background: #F00;
top: 600px;
}
.orange {
background: #F60;
top: 700px;
}
.yellow {
background: #FF0;
top: 800px;
}
.green {
background: #0F0;
top: 900px;
}
.blue {
background: #00F;
top: 1000px;
}
.purple {
background: #F0F;
top: 1100px;
}
.appear {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="main">
<article class="red">
</article>
<article class="orange">
</article>
<article class="yellow">
</article>
<article class="green">
</article>
<article class="blue">
</article>
<article class="purple">
</article>
</div>
You can use .scrollTop():
Get the current vertical position of the scroll bar for the first element in the set of matched elements or set the vertical position of the scroll bar for every matched element.
https://api.jquery.com/scrolltop/
Use .each() to iterate over each element and make it appear if scrolling has crossed the proper threshold on the screen.

Javascript - how to trigger a "if" condition by a change through CSS

I'm being tormented in the past 4 hours to find out how to do this, I don't know what I'm doing wrong, I have a page with multiple layers, I wish to trigger some transition when the needed page has opacity 1, it should be simple when u think of it, here is my code, please help ;)
slide1 = document.querySelector('.slide1');
function videoPlay() {
var videoOne = document.getElementById('myVideo');
if ((slide1.style.opacity) > 0 ) {
videoOne.play();
}
}
videoPlay();
.slide {
width: 100%;
background-size: cover;
background-position: center;
position: absolute;
}
.slide1 {
width: 100%;
background: none;
opacity: 0;
}
<div class="slide slide1">
<div class="slide-content">
<div class="secondColumn">
<video muted id="myVideo">
<source src="Media/Acqua.mp4" type="video/mp4">
</video>
<div class="lowerTab"></div>
</div>
</div>
here is the code which i use to change the opacity using the wheel :
//wheel event
document.addEventListener('wheel',
function scrollWheel(event) {
var fig =event.deltaY;
if (fig > 0) {
slideMove();
}
else if (fig<0) {
slideMovReverse();
}
})
//basic movement
function slideMove() {
if (current === sliderImages.length-1 ) {
current = -1
}
reset();
sliderImages[current+1].style.transition = "opacity 1s ease-in 0s";
sliderImages[current+1].style.opacity= "1.0";
current++;
}
You can use the transitionend event, but you'd have to set up the transition first. As it sits now, there's not much information in your question about the different slides, how the transitions are set up, etc. Here's a baseline to give you an idea:
const slide1 = document.querySelector('.slide1');
const videoEl = document.querySelector('.slide1__video');
const button = document.querySelector('button');
let inView = false;
slide1.addEventListener('transitionend', () => {
let content = 'Playing';
if (inView) {
content = ''
}
videoEl.textContent = content;
inView = !inView;
})
button.addEventListener('click', () => {
slide1.classList.toggle('active')
})
.slide1 {
transition: opacity 500ms linear;
opacity: 0;
border: 1px solid green;
padding: 10px;
margin-bottom: 24px
}
.slide1.active {
opacity: 1
}
<div class="slide1">
Slide 1
<div class="slide1__video"></div>
</div>
<button>Next</button>
Edit
It'll need some love but I think it's in the right direction to what you're after.
const slides = Array.from(document.querySelectorAll('.slide'));
document.addEventListener('wheel', onScroll);
const SCROLL_TOLERANCE = 100;
let currentIndex = 0;
let currentScroll = 0;
function onScroll(e) {
if (e.deltaY > 0) {
currentScroll += 1;
} else {
currentScroll -= 1;
}
if (currentScroll >= (currentIndex * SCROLL_TOLERANCE) + 15) {
showNext();
} else if (currentScroll <= (currentIndex * SCROLL_TOLERANCE) - 15) {
showPrevious();
}
}
function showNext() {
if (currentIndex === slides.length - 1) {
return console.warn('At the end.');
}
currentIndex += 1;
setSlide();
}
function showPrevious() {
if (currentIndex === 0) {
return console.warn('At the beginning.');
}
currentIndex -= 1;
setSlide();
}
function setSlide() {
let newOpacity = 0;
slides.forEach(slide => {
if (+slide.dataset.index === currentIndex) {
newOpacity = 1
} else {
newOpacity = 0;
}
slide.style.opacity = newOpacity;
slide.addEventListener('transitionend', () => {
console.log('Done transitioning!');
// Do things here when the transition is over.
})
});
}
html,
body {
padding: 0;
margin: 0;
font-family: sans-serif;
font-size: 18px
}
.slide {
border: 3px solid #efefef;
position: absolute;
display: flex;
align-items: center;
justify-content: center;
width: 100%;
height: 100%;
transition: all 500ms linear;
opacity: 0;
transition-delay: 250ms;
}
.slide.active {
opacity: 1;
}
<div class="slide active" data-index="0">
Slide 1
</div>
<div class="slide" data-index="1">
Slide 2
</div>
<div class="slide" data-index="2">
Slide 3
</div>
<div class="slide" data-index="3">
Slide 4
</div>

How can we show one division on top of other while both are visible by some opacity in html?

I am not good at designing web pages. I have this page which I am making on codepen.io from one of the code at https://codepen.io/KARANVERMA5/pen/oqKJma .
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.modal {
width: 600px;
max-width: 100%;
height: 400px;
max-height: 100%;
}
#word-cloud {
height: 100vh;
width: 100vw;
margin: 0 auto;
}
body,
html {
margin: 0;
padding: 0;
}
.bar {
border: 1px solid #666;
height: 5px;
width: 100px;
}
.bar .in {
-webkit-animation: fill 10s linear 1;
animation: fill 10s linear 1;
height: 100%;
background-color: green;
}
#-webkit-keyframes fill {
0% {
width: 0%;
}
100% {
width: 100%;
}
}
#keyframes fill {
0% {
width: 0%;
}
100% {
width: 100%;
}
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script type="text/javascript">
$(window).on('load', function() {
$('#myModal').modal('show');
});
</script>
</head>
<div class="modal hide fade" id="myModal" role="dialog">
<div class="modal-header">
<img class="right" src="http://i.imgur.com/jfDhpP5.png" />
</div>
<div class="modal-body">
<h3>
<div id="word-cloud">
</div>
</h3>
</div>
<div class="modal-footer">
<div class="bar">
<div class="in"></div>
</div>
<div class="container center">
<button type="button" class="btn btn-default" data-dismiss="modal">Enter</button>
<div>
<span class="copyrights">Copyrights©
<script language="JavaScript" type="text/javascript">
now = new Date
theYear=now.getYear()
if (theYear < 1900)
theYear=theYear+1900
document.write(theYear)
</script>
your company
</span>
</div>
</div>
</div>
</div>
<script>
/* ======================= SETUP ======================= */
var config = {
trace: true,
spiralResolution: 1, //Lower = better resolution
spiralLimit: 360 * 5,
lineHeight: 0.8,
xWordPadding: 0,
yWordPadding: 3,
font: "sans-serif"
}
var words = ["words", "are", "cool", "and", "so", "are", "you", "Great", "funhouse!", "apart", "from", "Ravi", "fish"].map(function(word) {
return {
word: word,
freq: Math.floor(Math.random() * 50) + 10
}
})
words.sort(function(a, b) {
return -1 * (a.freq - b.freq);
});
var cloud = document.getElementById("word-cloud");
cloud.style.position = "relative";
cloud.style.fontFamily = config.font;
var traceCanvas = document.createElement("canvas");
traceCanvas.width = cloud.offsetWidth;
traceCanvas.height = cloud.offsetHeight;
var traceCanvasCtx = traceCanvas.getContext("2d");
cloud.appendChild(traceCanvas);
var startPoint = {
x: cloud.offsetWidth / 2,
y: cloud.offsetHeight / 2
};
var wordsDown = [];
/* ======================= END SETUP ======================= */
/* ======================= PLACEMENT FUNCTIONS ======================= */
function createWordObject(word, freq) {
var wordContainer = document.createElement("div");
wordContainer.style.position = "absolute";
wordContainer.style.fontSize = freq + "px";
wordContainer.style.lineHeight = config.lineHeight;
/* wordContainer.style.transform = "translateX(-50%) translateY(-50%)";*/
wordContainer.appendChild(document.createTextNode(word));
return wordContainer;
}
function placeWord(word, x, y) {
cloud.appendChild(word);
word.style.left = x - word.offsetWidth / 2 + "px";
word.style.top = y - word.offsetHeight / 2 + "px";
wordsDown.push(word.getBoundingClientRect());
}
function trace(x, y) {
// traceCanvasCtx.lineTo(x, y);
// traceCanvasCtx.stroke();
traceCanvasCtx.fillRect(x, y, 1, 1);
}
function spiral(i, callback) {
angle = config.spiralResolution * i;
x = (1 + angle) * Math.cos(angle);
y = (1 + angle) * Math.sin(angle);
return callback ? callback() : null;
}
function intersect(word, x, y) {
cloud.appendChild(word);
word.style.left = x - word.offsetWidth / 2 + "px";
word.style.top = y - word.offsetHeight / 2 + "px";
var currentWord = word.getBoundingClientRect();
cloud.removeChild(word);
for (var i = 0; i < wordsDown.length; i += 1) {
var comparisonWord = wordsDown[i];
if (!(currentWord.right + config.xWordPadding < comparisonWord.left - config.xWordPadding ||
currentWord.left - config.xWordPadding > comparisonWord.right + config.wXordPadding ||
currentWord.bottom + config.yWordPadding < comparisonWord.top - config.yWordPadding ||
currentWord.top - config.yWordPadding > comparisonWord.bottom + config.yWordPadding)) {
return true;
}
}
return false;
}
/* ======================= END PLACEMENT FUNCTIONS ======================= */
/* ======================= LETS GO! ======================= */
(function placeWords() {
for (var i = 0; i < words.length; i += 1) {
var word = createWordObject(words[i].word, words[i].freq);
for (var j = 0; j < config.spiralLimit; j++) {
//If the spiral function returns true, we've placed the word down and can break from the j loop
if (spiral(j, function() {
if (!intersect(word, startPoint.x + x, startPoint.y + y)) {
placeWord(word, startPoint.x + x, startPoint.y + y);
return true;
}
})) {
break;
}
}
}
})();
/* ======================= WHEW. THAT WAS FUN. We should do that again sometime ... ======================= */
/* ======================= Draw the placement spiral if trace lines is on ======================= */
(function traceSpiral() {
traceCanvasCtx.beginPath();
if (config.trace) {
var frame = 1;
function animate() {
spiral(frame, function() {
trace(startPoint.x + x, startPoint.y + y);
});
frame += 1;
if (frame < config.spiralLimit) {
window.requestAnimationFrame(animate);
}
}
animate();
}
})();
</script>
</html>
The page right now looks like this:-
While the footer right now has something like this:
There is a progress-bar on the top of enter button. I want to show the enter button and progress-bar behind the word-cloud and enter button only shows after progress-bar is complete. Please point me in right direction. Why the complete design is going to the left? And how can we display other divs behind the word cloud?
As Pete said we just have to add z-index and positioning to it. My CSS look something like it. After all we just have to tweak with the css that is all. It solved the issue.
#word-cloud {
position:fixed;
height: 100vh;
max-height: 100%;
width: 100vw;
max-width: 100%;
margin:-300px auto auto -250px;
top:20%;
left:22%;
text-align:center;
z-index:2;
}
img{
position:relative;
left:40%;
margin-left:0px;
}
body,
html {
margin: 0;
padding: 0;
}
.bar .in {
-webkit-animation: fill 10s linear 1;
animation: fill 10s linear 1;
height: 100%;
background-color: red;
}
#-webkit-keyframes fill {
0% {
width: 0%;
}
100% {
width: 100%;
}
}
#keyframes fill {
0% {
width: 0%;
}
100% {
width: 100%;
}
}

animate opacity in and out on scroll

So I have a set of elements called .project-slide, one after the other. Some of these will have the .colour-change class, IF they do have this class they will change the background colour of the .background element when they come into view. This is what I've got so far: https://codepen.io/neal_fletcher/pen/eGmmvJ
But I'm looking to achieve something like this: http://studio.institute/clients/nike/
Scroll through the page to see the background change. So in my case what I'd want is that when a .colour-change was coming into view it would slowly animate the opacity in of the .background element, then slowly animate the opacity out as I scroll past it (animating on scroll that is).
Any suggestions on how I could achieve that would be greatly appreciated!
HTML:
<div class="project-slide fullscreen">
SLIDE ONE
</div>
<div class="project-slide fullscreen">
SLIDE TWO
</div>
<div class="project-slide fullscreen colour-change" data-bg="#EA8D02">
SLIDE THREE
</div>
<div class="project-slide fullscreen">
SLIDE TWO
</div>
<div class="project-slide fullscreen colour-change" data-bg="#cccccc">
SLIDE THREE
</div>
</div>
jQuery:
$(window).on('scroll', function () {
$('.project-slide').each(function() {
if ($(window).scrollTop() >= $(this).offset().top - ($(window).height() / 2)) {
if($(this).hasClass('colour-change')) {
var bgCol = $(this).attr('data-bg');
$('.background').css('background-color', bgCol);
} else {
}
} else {
}
});
});
Set some data-gb-color with RGB values like 255,0,0…
Calculate the currently tracked element in-viewport-height.
than get the 0..1 value of the inViewport element height and use it as the Alpha channel for the RGB color:
/**
* inViewport jQuery plugin by Roko C.B.
* http://stackoverflow.com/a/26831113/383904
* Returns a callback function with an argument holding
* the current amount of px an element is visible in viewport
* (The min returned value is 0 (element outside of viewport)
*/
;
(function($, win) {
$.fn.inViewport = function(cb) {
return this.each(function(i, el) {
function visPx() {
var elH = $(el).outerHeight(),
H = $(win).height(),
r = el.getBoundingClientRect(),
t = r.top,
b = r.bottom;
return cb.call(el, Math.max(0, t > 0 ? Math.min(elH, H - t) : (b < H ? b : H)), H);
}
visPx();
$(win).on("resize scroll", visPx);
});
};
}(jQuery, window));
// OK. Let's do it
var $wrap = $(".background");
$("[data-bg-color]").inViewport(function(px, winH) {
var opacity = (px - winH) / winH + 1;
if (opacity <= 0) return; // Ignore if value is 0
$wrap.css({background: "rgba(" + this.dataset.bgColor + ", " + opacity + ")"});
});
/*QuickReset*/*{margin:0;box-sizing:border-box;}html,body{height:100%;font:14px/1.4 sans-serif;}
.project-slide {
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
}
.project-slide h2 {
font-weight: 100;
font-size: 10vw;
}
<div class="project-slides-wrap background">
<div class="project-slide">
<h2>when in trouble...</h2>
</div>
<div class="project-slide" data-bg-color="0,200,255">
<h2>real trouble...</h2>
</div>
<div class="project-slide">
<h2>ask...</h2>
</div>
<div class="project-slide" data-bg-color="244,128,36">
<h2>stack<b>overflow</b></h2>
</div>
</div>
<script src="//code.jquery.com/jquery-3.1.0.js"></script>
Looks like that effect is using two fixed divs so if you need something simple like that you can do it like this:
But if you need something more complicated use #Roko's answer.
var fixed = $(".fixed");
var fixed2 = $(".fixed2");
$( window ).scroll(function() {
var top = $( window ).scrollTop();
var opacity = (top)/300;
if( opacity > 1 )
opacity = 1;
fixed.css("opacity",opacity);
if( fixed.css('opacity') == 1 ) {
top = 0;
opacity = (top += $( window ).scrollTop()-400)/300;
if( opacity > 1 )
opacity = 1;
fixed2.css("opacity",opacity);
}
});
.fixed{
display: block;
width: 100%;
height: 200px;
background: blue;
position: fixed;
top: 0px;
left: 0px;
color: #FFF;
padding: 0px;
margin: 0px;
opacity: 0;
}
.fixed2{
display: block;
width: 100%;
height: 200px;
background: red;
position: fixed;
top: 0px;
left: 0px;
color: #FFF;
padding: 0px;
margin: 0px;
opacity: 0;
}
.container{
display: inline-block;
width: 100%;
height: 2000px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
Scroll me!!
</div>
<div class="fixed">
</div>
<div class="fixed2">
</div>

How to build simple jQuery image slider with sliding or opacity effect?

Some of us might not want to use ready plugins because of their high sizes and possibilty of creating conflicts with current javascript.
I was using light slider plugins before but when customer gives modular revise, it became really hard to manipulate. Then I aim to build mine for customising it easily. I believe sliders shouldn't be that complex to build from beginning.
What is a simple and clean way to build jQuery image slider?
Before inspecting examples, you should know two jQuery functions which i used most.
index() returns value is an integer indicating the position of the first element within the jQuery object relative to its sibling elements.
eq() selects of an element based on its position (index value).
Basicly i take selected trigger element's index value and match this value on images with eq method.
- FadeIn / FadeOut effect.
- Sliding effect.
- alternate Mousewheel response.
​html sample:
<ul class="images">
<li>
<img src="images/1.jpg" alt="1" />
</li>
<li>
<img src="images/2.jpg" alt="2" />
</li>
...
</ul>
<ul class="triggers">
<li>1</li>
<li>2</li>
...
</ul>
<span class="control prev">Prev</span>
<span class="control next">Next</span>
OPACITY EFFECT: jsFiddle.
css trick: overlapping images with position:absolute
ul.images { position:relative; }
ul.images li { position:absolute; }
jQuery:
var target;
var triggers = $('ul.triggers li');
var images = $('ul.images li');
var lastElem = triggers.length-1;
triggers.first().addClass('active');
images.hide().first().show();
function sliderResponse(target) {
images.fadeOut(300).eq(target).fadeIn(300);
triggers.removeClass('active').eq(target).addClass('active');
}
SLIDING EFFECT: jsFiddle.
css trick: with double wrapper and use child as mask
.mask { float:left; margin:40px; width:270px; height:266px; overflow:hidden; }
ul.images { position:relative; top:0px;left:0px; }
/* this width must be total of the images, it comes from jquery */
ul.images li { float:left; }
jQuery:
var target;
var triggers = $('ul.triggers li');
var images = $('ul.images li');
var lastElem = triggers.length-1;
var mask = $('.mask ul.images');
var imgWidth = images.width();
triggers.first().addClass('active');
mask.css('width', imgWidth*(lastElem+1) +'px');
function sliderResponse(target) {
mask.stop(true,false).animate({'left':'-'+ imgWidth*target +'px'},300);
triggers.removeClass('active').eq(target).addClass('active');
}
Common jQuery response for both slider:
( triggers + next/prev click and timing )
triggers.click(function() {
if ( !$(this).hasClass('active') ) {
target = $(this).index();
sliderResponse(target);
resetTiming();
}
});
$('.next').click(function() {
target = $('ul.triggers li.active').index();
target === lastElem ? target = 0 : target = target+1;
sliderResponse(target);
resetTiming();
});
$('.prev').click(function() {
target = $('ul.triggers li.active').index();
lastElem = triggers.length-1;
target === 0 ? target = lastElem : target = target-1;
sliderResponse(target);
resetTiming();
});
function sliderTiming() {
target = $('ul.triggers li.active').index();
target === lastElem ? target = 0 : target = target+1;
sliderResponse(target);
}
var timingRun = setInterval(function() { sliderTiming(); },5000);
function resetTiming() {
clearInterval(timingRun);
timingRun = setInterval(function() { sliderTiming(); },5000);
}
Here is a simple and easy to understand code for Creating image slideshow using JavaScript without using Jquery.
<script language="JavaScript">
var i = 0; var path = new Array();
// LIST OF IMAGES
path[0] = "image_1.gif";
path[1] = "image_2.gif";
path[2] = "image_3.gif";
function swapImage() { document.slide.src = path[i];
if(i < path.length - 1) i++;
else i = 0; setTimeout("swapImage()",3000);
} window.onload=swapImage;
</script>
<img height="200" name="slide" src="image_1.gif" width="400" />
I have recently created a solution with a gallery of images and a slider that apears when an image is clicked.
Take a look at the code here: GitHub Code
And a live example here: Code Example
var CreateGallery = function(parameters) {
var self = this;
this.galleryImages = [];
this.galleryImagesSrcs = [];
this.galleryImagesNum = 0;
this.counter;
this.galleryTitle = parameters.galleryTitle != undefined ? parameters.galleryTitle : 'Gallery image';
this.maxMobileWidth = parameters.maxMobileWidth != undefined ? parameters.maxMobileWidth : 768;
this.numMobileImg = parameters.numMobileImg != undefined ? parameters.numMobileImg : 2;
this.maxTabletWidth = parameters.maxTabletWidth != undefined ? parameters.maxTabletWidth : 1024;
this.numTabletImg = parameters.numTabletImg != undefined ? parameters.numTabletImg : 3;
this.addModalGallery = function(gallerySelf = self){
var $div = $(document.createElement('div')).attr({
'id': 'modal-gallery'
}).append($(document.createElement('div')).attr({
'class': 'header'
}).append($(document.createElement('button')).attr({
'class': 'close-button',
'type': 'button'
}).html('×')
).append($(document.createElement('h2')).text(gallerySelf.galleryTitle))
).append($(document.createElement('div')).attr({
'class': 'text-center'
}).append($(document.createElement('img')).attr({
'id': 'gallery-img'
})
).append($(document.createElement('button')).attr({
'class': 'prev-button',
'type': 'button'
}).html('◄')
).append($(document.createElement('button')).attr({
'class': 'next-button',
'type': 'button'
}).html('►')
)
);
parameters.element.after($div);
};
$(document).on('click', 'button.prev-button', {self: self}, function() {
var $currImg = self.counter >= 1 ? self.galleryImages[--self.counter] : self.galleryImages[self.counter];
var $currHash = self.galleryImagesSrcs[self.counter];
var $src = $currImg.src;
window.location.hash = $currHash;
$('img#gallery-img').attr('src', $src);
$('div#modal-gallery h2').text(self.galleryTitle + ' ' + (self.counter + 1));
});
$(document).on('click', 'button.next-button', {self: self}, function() {
var $currImg = self.counter < (self.galleryImagesNum - 1) ? self.galleryImages[++self.counter] : self.galleryImages[self.counter];
var $currHash = self.galleryImagesSrcs[self.counter];
var $src = $currImg.src;
window.location.hash = $currHash;
$('img#gallery-img').attr('src', $src);
$('div#modal-gallery h2').text(self.galleryTitle + ' ' + (self.counter + 1));
});
$(document).on('click', 'div#modal-gallery button.close-button', function() {
$('#modal-gallery').css('position', 'relative');
$('#modal-gallery').hide();
$('body').css('overflow', 'visible');
});
parameters.element.find('a').on('click', {self: self}, function(event) {
event.preventDefault();
$('#modal-gallery').css('position', 'fixed');
$('#modal-gallery').show();
$('body').css('overflow', 'hidden');
var $currHash = this.hash.substr(1);
self.counter = self.galleryImagesSrcs.indexOf($currHash);
var $src = $currHash;
window.location.hash = $currHash;
$('img#gallery-img').attr('src', $src);
$('div#modal-gallery h2').text(self.galleryTitle + ' ' + (self.counter + 1));
});
this.sizeGallery = function(gallerySelf = self) {
var $modalGallery = $(document).find("div#modal-gallery");
if($modalGallery.length <= 0) {
this.addModalGallery();
}
var $windowWidth = $(window).width();
var $parentWidth = parameters.element.width();
var $thumbnailHref = parameters.element.find('img:first').attr('src');
if($windowWidth < gallerySelf.maxMobileWidth) {
var percentMobile = Math.floor(100 / gallerySelf.numMobileImg);
var emMobile = 0;
var pxMobile = 2;
// var emMobile = gallerySelf.numMobileImg * 0.4;
// var pxMobile = gallerySelf.numMobileImg * 2;
parameters.element.find('img').css('width', 'calc('+percentMobile+'% - '+emMobile+'em - '+pxMobile+'px)');
} else if($windowWidth < gallerySelf.maxTabletWidth) {
var percentTablet = Math.floor(100 / gallerySelf.numTabletImg);
var emTablet = 0;
var pxTablet = 2;
// var emTablet = gallerySelf.numMobileImg * 0.4;
// var pxTablet = gallerySelf.numMobileImg * 2;
parameters.element.find('img').css('width', 'calc('+percentTablet+'% - '+emTablet+'em - '+pxTablet+'px)');
} else {
var $thumbImg = new Image();
$thumbImg.src = $thumbnailHref;
$thumbImg.onload = function() {
var $thumbnailWidth = this.width;
if($parentWidth > 0 && $thumbnailWidth > 0) {
parameters.element.find('img').css('width', (Math.ceil($thumbnailWidth * 100 / $parentWidth))+'%');
}
};
}
};
this.startGallery = function(gallerySelf = self) {
parameters.element.find('a').each(function(index, el) {
var $currHash = el.hash.substr(1);
var $img = new Image();
$img.src = $currHash;
gallerySelf.galleryImages.push($img);
gallerySelf.galleryImagesSrcs.push($currHash);
});
this.galleryImagesNum = this.galleryImages.length;
};
this.sizeGallery();
this.startGallery();
};
var myGallery;
$(window).on('load', function() {
myGallery = new CreateGallery({
element: $('#div-gallery'),
maxMobileWidth: 768,
numMobileImg: 2,
maxTabletWidth: 1024,
numTabletImg: 3
});
});
$(window).on('resize', function() {
myGallery.sizeGallery();
});
#div-gallery {
text-align: center;
}
#div-gallery img {
margin-right: auto;
margin-left: auto;
}
div#modal-gallery {
top: 0;
left: 0;
width: 100%;
max-width: none;
height: 100vh;
min-height: 100vh;
margin-left: 0;
border: 0;
border-radius: 0;
z-index: 1006;
-webkit-backface-visibility: hidden;
backface-visibility: hidden;
display: none;
background-color: #fefefe;
position: relative;
margin-right: auto;
overflow-y: auto;
padding: 0;
}
div#modal-gallery div.header {
position: relative;
}
div#modal-gallery div.header h2 {
margin-left: 1rem;
}
div#modal-gallery div.header button.close-button {
position: absolute;
top: calc(50% - 1em);
right: 1rem;
}
div#modal-gallery img {
display: block;
max-width: 98%;
max-height: calc(100vh - 5em);
margin-right: auto;
margin-left: auto;
}
div#modal-gallery div.text-center {
position: relative;
}
button.close-button {
display: inline-block;
padding: 6px 12px;
margin-bottom: 0;
font-size: 20px;
font-weight: 400;
line-height: 1.42857143;
text-align: center;
white-space: nowrap;
vertical-align: middle;
-ms-touch-action: manipulation;
touch-action: manipulation;
cursor: pointer;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
background-image: none;
border: 1px solid transparent;
border-radius: 4px;
color: #333;
background-color: #fff;
border-color: #ccc;
}
button.close-button:hover, button.close-button:focus {
background-color: #ddd;
}
button.next-button:hover, button.prev-button:hover, button.next-button:focus, button.prev-button:focus {
color: #fff;
text-decoration: none;
filter: alpha(opacity=90);
outline: 0;
opacity: .9;
}
button.next-button, button.prev-button {
position: absolute;
top: 0;
bottom: 0;
left: 0;
width: 15%;
font-size: 20px;
color: #fff;
text-align: center;
text-shadow: 0 1px 2px rgba(0,0,0,.6);
background-color: rgba(0,0,0,0);
filter: alpha(opacity=50);
opacity: .5;
border: none;
}
button.next-button {
right: 0;
left: auto;
background-image: -webkit-linear-gradient(left,rgba(0,0,0,.0001) 0,rgba(0,0,0,.5) 100%);
background-image: -o-linear-gradient(left,rgba(0,0,0,.0001) 0,rgba(0,0,0,.5) 100%);
background-image: -webkit-gradient(linear,left top,right top,from(rgba(0,0,0,.0001)),to(rgba(0,0,0,.5)));
background-image: linear-gradient(to right,rgba(0,0,0,.0001) 0,rgba(0,0,0,.5) 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#00000000', endColorstr='#80000000', GradientType=1);
background-repeat: repeat-x;
}
button.prev-button {
background-image: -webkit-linear-gradient(left,rgba(0,0,0,.5) 0,rgba(0,0,0,.0001) 100%);
background-image: -o-linear-gradient(left,rgba(0,0,0,.5) 0,rgba(0,0,0,.0001) 100%);
background-image: -webkit-gradient(linear,left top,right top,from(rgba(0,0,0,.5)),to(rgba(0,0,0,.0001)));
background-image: linear-gradient(to right,rgba(0,0,0,.5) 0,rgba(0,0,0,.0001) 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#80000000', endColorstr='#00000000', GradientType=1);
background-repeat: repeat-x;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="div-gallery">
<img src="http://placehold.it/300x300/ff0000/000000?text=Gallery+image+1" alt="">
<img src="http://placehold.it/300x300/ff4000/000000?text=Gallery+image+2" alt="">
<img src="http://placehold.it/300x300/ff8000/000000?text=Gallery+image+3" alt="">
<img src="http://placehold.it/300x300/ffbf00/000000?text=Gallery+image+4" alt="">
<img src="http://placehold.it/300x300/ffff00/000000?text=Gallery+image+5" alt="">
<img src="http://placehold.it/300x300/bfff00/000000?text=Gallery+image+6" alt="">
<img src="http://placehold.it/300x300/80ff00/000000?text=Gallery+image+7" alt="">
<img src="http://placehold.it/300x300/40ff00/000000?text=Gallery+image+8" alt="">
<img src="http://placehold.it/300x300/00ff00/000000?text=Gallery+image+9" alt="">
<img src="http://placehold.it/300x300/00ff40/000000?text=Gallery+image+10" alt="">
<img src="http://placehold.it/300x300/00ff80/000000?text=Gallery+image+11" alt="">
<img src="http://placehold.it/300x300/00ffbf/000000?text=Gallery+image+12" alt="">
<img src="http://placehold.it/300x300/00ffff/000000?text=Gallery+image+13" alt="">
<img src="http://placehold.it/300x300/00bfff/000000?text=Gallery+image+14" alt="">
<img src="http://placehold.it/300x300/0080ff/000000?text=Gallery+image+15" alt="">
<img src="http://placehold.it/300x300/0040ff/000000?text=Gallery+image+16" alt="">
</div>
Checkout this whole bunch of code to build simple jquery image slider. Copy and save this file to local machine and test it. You can modify it according to your requirement.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>
var current_img = 1;
var i;
$(document).ready(function(){
var imgs = $("#image").find("img");
function show_img(){
for (i = 1; i < imgs.length+1; i++) {
if(i == current_img){
$(imgs[i-1]).show();
}else{
$(imgs[i-1]).hide()
}
}
}
$("#prev").click(function(){
if(current_img == 1){
current_img = imgs.length;
}else{
current_img = current_img - 1
}
show_img();
});
$("#next").click(function(){
if(current_img == imgs.length){
current_img = 1;
}else{
current_img = current_img + 1
}
show_img();
});
});
</script>
</head>
<body>
<div style="margin-top: 100px;"></div>
<div class="container">
<div class="col-sm-3">
<button type="button" id="prev" class="btn">Previous</button>
</div>
<div class="col-sm-6">
<div id="image">
<img src="https://www.w3schools.com/html/pulpitrock.jpg" alt="image1">
<img src="https://www.w3schools.com/cSS/img_forest.jpg" alt="image2" hidden="true" style="max-width: 500px;">
<img src="https://www.w3schools.com/html/img_chania.jpg" alt="image3" hidden="true">
</div>
</div>
<div class="col-sm-3">
<button type="button" id="next" class="btn">Next</button>
</div>
</div>
</body>
</html>
I have written a tutorial on creating a slideshow, The tutorial page
In case the link becomes invalid I have included the code in my answer below.
the html:
<div id="slideShow">
<div id="slideShowWindow">
<div class="slide">
<img src="”img1.png”/">
<div class="slideText">
<h2>The Slide Title</h2>
<p>This is the slide text</p>
</div> <!-- </slideText> -->
</div> <!-- </slide> repeat as many times as needed -->
</div> <!-- </slideShowWindow> -->
</div> <!-- </slideshow> -->
css:
img {
display: block;
width: 100%;
height: auto;
}
p{
background:none;
color:#ffffff;
}
#slideShow #slideShowWindow {
width: 650px;
height: 450px;
margin: 0;
padding: 0;
position: relative;
overflow:hidden;
margin-left: auto;
margin-right:auto;
}
#slideShow #slideShowWindow .slide {
margin: 0;
padding: 0;
width: 650px;
height: 450px;
float: left;
position: relative;
margin-left:auto;
margin-right: auto;
}
#slideshow #slideshowWindow .slide, .slideText {
position:absolute;
bottom:18px;
left:0;
width:100%;
height:auto;
margin:0;
padding:0;
color:#ffffff;
font-family:Myriad Pro, Arial, Helvetica, sans-serif;
}
.slideText {
background: rgba(128, 128, 128, 0.49);
}
#slideshow #slideshowWindow .slide .slideText h2,
#slideshow #slideshowWindow .slide .slideText p {
margin:10px;
padding:15px;
}
.slideNav {
display: block;
text-indent: -10000px;
position: absolute;
cursor: pointer;
}
#leftNav {
left: 0;
bottom: 0;
width: 48px;
height: 48px;
background-image: url("../Images/plus_add_minus.png");
background-repeat: no-repeat;
z-index: 10;
}
#rightNav {
right: 0;
bottom: 0;
width: 48px;
height: 48px;
background-image: url("../Images/plus_add_green.png");
background-repeat: no-repeat;
z-index: 10; }
jQuery:
$(document).ready(function () {
var currentPosition = 0;
var slideWidth = 650;
var slides = $('.slide');
var numberOfSlides = slides.length;
var slideShowInterval;
var speed = 3000;
//Assign a timer, so it will run periodically
slideShowInterval = setInterval(changePosition, speed);
slides.wrapAll('<div id="slidesHolder"></div>');
slides.css({ 'float': 'left' });
//set #slidesHolder width equal to the total width of all the slides
$('#slidesHolder').css('width', slideWidth * numberOfSlides);
$('#slideShowWindow')
.prepend('<span class="slideNav" id="leftNav">Move Left</span>')
.append('<span class="slideNav" id="rightNav">Move Right</span>');
manageNav(currentPosition);
//tell the buttons what to do when clicked
$('.slideNav').bind('click', function () {
//determine new position
currentPosition = ($(this).attr('id') === 'rightNav')
? currentPosition + 1 : currentPosition - 1;
//hide/show controls
manageNav(currentPosition);
clearInterval(slideShowInterval);
slideShowInterval = setInterval(changePosition, speed);
moveSlide();
});
function manageNav(position) {
//hide left arrow if position is first slide
if (position === 0) {
$('#leftNav').hide();
}
else {
$('#leftNav').show();
}
//hide right arrow is slide position is last slide
if (position === numberOfSlides - 1) {
$('#rightNav').hide();
}
else {
$('#rightNav').show();
}
}
//changePosition: this is called when the slide is moved by the timer and NOT when the next or previous buttons are clicked
function changePosition() {
if (currentPosition === numberOfSlides - 1) {
currentPosition = 0;
manageNav(currentPosition);
} else {
currentPosition++;
manageNav(currentPosition);
}
moveSlide();
}
//moveSlide: this function moves the slide
function moveSlide() {
$('#slidesHolder').animate({ 'marginLeft': slideWidth * (-currentPosition) });
}
});

Categories

Resources