Adding a dragging animation using hammer.js - javascript
I've just finished building my slider with touch events using hammer.js. Right now I'm trying to figure out how can I add a dragging effect on my slider. Basically the concept is once I swipe left or right before releasing my finger from the element or screen, it will drag the slider 30px to the left or right before sliding to the next slide
$(document).ready(function() {
$('.prev').on('click', function(e) {
event.stopPropagation();
// store variable relevent to clicked slider
var sliderWrapper = $(this).closest('.slider-wrapper'),
slideItems = sliderWrapper.find('.slide-items'),
slider = sliderWrapper.find('.slider'),
currentSlide = sliderWrapper.attr('data-slide');
// Check if data-slide attribute is greater than 0
if( currentSlide > 0 ) {
// Decremement current slide
currentSlide--;
// Assign CSS position to clicked slider
slider.css({'right' : currentSlide*slideItems.outerWidth() });
// Update data-slide attribute
sliderWrapper.attr('data-slide', currentSlide);
}
});
$('.next').on('click', function(e) {
event.stopPropagation();
// store variable relevent to clicked slider
var sliderWrapper = $(this).closest('.slider-wrapper'),
slideItems = sliderWrapper.find('.slide-items'),
slider = sliderWrapper.find('.slider'),
totalSlides = slideItems.length,
currentSlide = sliderWrapper.attr('data-slide');
// Check if dataslide is less than the total slides
if( currentSlide < totalSlides - 1 ) {
// Increment current slide
currentSlide++;
// Assign CSS position to clicked slider
slider.css({'right' : currentSlide*slideItems.outerWidth() });
// Update data-slide attribute
sliderWrapper.attr('data-slide', currentSlide);
}
})
$('.slider-wrapper').each(function(){
// create a simple instance
// by default, it only adds horizontal recognizers
var direction;
var mc = new Hammer(this),
itemLength = $(this).find('.slide-items').length,
count = 0,
slide = $(this);
var sliderWrapper = slide,
slideItems = sliderWrapper.find('.slide-items'),
slider = sliderWrapper.find('.slider'),
totalSlides = slideItems.length,
currentSlide = sliderWrapper.attr('data-slide');
mc.on("panleft panright", function(ev) {
direction = ev.type;
});
mc.on("panend", function(ev) {
if(direction === "panleft") {
console.log('panleft');
// Check if dataslide is less than the total slides
if( currentSlide < totalSlides - 1 ) {
// Increment current slide
currentSlide++;
// Assign CSS position to clicked slider
slider.css({'right' : currentSlide*slideItems.outerWidth() });
// Update data-slide attribute
sliderWrapper.attr('data-slide', currentSlide);
}
}
if(direction === "panright") {
console.log('right');
// Check if data-slide attribute is greater than 0
if( currentSlide > 0 ) {
// Decremement current slide
currentSlide--;
// Assign CSS position to clicked slider
slider.css({'right' : currentSlide*slideItems.outerWidth() });
// Update data-slide attribute
sliderWrapper.attr('data-slide', currentSlide);
}
}
});
});
});
$(window).on('load', function() {
$('.slider-wrapper').each(function() {
var slideItems = $(this).find('.slide-items'),
items = slideItems.length,
sliderBox = $(this).find('.slider'),
sliderWrapperWidth = $(this).width();
slideItems.outerWidth( sliderWrapperWidth / 2 );
sliderBox.width( slideItems.outerWidth() * items );
});
});
/* http://meyerweb.com/eric/tools/css/reset/
v2.0 | 20110126
License: none (public domain)
*/
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline; }
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
display: block; }
body {
line-height: 1; }
ol, ul {
list-style: none; }
blockquote, q {
quotes: none; }
blockquote:before, blockquote:after,
q:before, q:after {
content: '';
content: none; }
table {
border-collapse: collapse;
border-spacing: 0; }
* {
box-sizing: border-box; }
.container {
max-width: 1280px;
margin: 0 auto; }
.container .slider-wrapper {
margin-bottom: 40px;
background-color: grey;
overflow: hidden; }
.container .slider-wrapper .slider {
position: relative;
right: 0;
display: flex;
flex-wrap: wrap;
overflow: hidden; }
.container .slider-wrapper .slider > div {
padding: 10px;
background-color: #e5d0d0; }
.container .slider-wrapper .slider > div p {
color: purple; }
.container .slider-wrapper .buttons {
display: flex;
justify-content: space-between;
background: beige;
padding: 10px 0; }
.container .slider-wrapper .buttons div {
background-color: cyan; }
/*# sourceMappingURL=style.css.map */
<script src="https://cdnjs.cloudflare.com/ajax/libs/hammer.js/2.0.8/hammer.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="slider-wrapper" data-slide="0">
<div class="slider">
<div class="slide-items">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus tempus diam nec mauris vehicula, eget euismod lorem ultrices. Fusce suscipit nisi nisi, nec fermentum ligula finibus non. Cras scelerisque risus libero, quis faucibus enim elementum non. Ut vitae purus in enim aliquam sollicitudin non et dui. Duis nec varius lectus.</p>
</div>
<div class="slide-items">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam eget ex mi. Etiam a vestibulum ligula, id porta dui. Duis in iaculis quam. Integer aliquam justo nec nibh consequat vulputate.</p>
</div>
<div class="slide-items">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus tempus diam nec mauris vehicula, eget euismod lorem ultrices. Fusce suscipit nisi nisi, nec fermentum ligula finibus non. Cras scelerisque risus libero, quis faucibus enim elementum non. Ut vitae purus in enim aliquam sollicitudin non et dui. Duis nec varius lectus.</p>
</div>
</div>
<div class="buttons">
<div class="prev">prev</div>
<div class="next">next</div>
</div>
</div>
<div class="slider-wrapper" data-slide="0">
<div class="slider">
<div class="slide-items">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus tempus diam nec mauris vehicula, eget euismod lorem ultrices. Fusce suscipit nisi nisi, nec fermentum ligula finibus non. Cras scelerisque risus libero, quis faucibus enim elementum non. Ut vitae purus in enim aliquam sollicitudin non et dui. Duis nec varius lectus.</p>
</div>
</div>
<div class="buttons">
<div class="prev">prev</div>
<div class="next">next</div>
</div>
</div>
<div class="slider-wrapper" data-slide="0">
<div class="slider">
<div class="slide-items">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus tempus diam nec mauris vehicula, eget euismod lorem ultrices. Fusce suscipit nisi nisi, nec fermentum ligula finibus non. Cras scelerisque risus libero, quis faucibus enim elementum non. Ut vitae purus in enim aliquam sollicitudin non et dui. Duis nec varius lectus.</p>
</div>
<div class="slide-items">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam eget ex mi. Etiam a vestibulum ligula, id porta dui. Duis in iaculis quam. Integer aliquam justo nec nibh consequat vulputate.</p>
</div>
</div>
<div class="buttons">
<div class="prev">prev</div>
<div class="next">next</div>
</div>
</div>
<div class="slider-wrapper" data-slide="0">
<div class="slider">
<div class="slide-items">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus tempus diam nec mauris vehicula, eget euismod lorem ultrices. Fusce suscipit nisi nisi, nec fermentum ligula finibus non. Cras scelerisque risus libero, quis faucibus enim elementum non. Ut vitae purus in enim aliquam sollicitudin non et dui. Duis nec varius lectus.</p>
</div>
</div>
<div class="buttons">
<div class="prev">prev</div>
<div class="next">next</div>
</div>
</div>
<div class="slider-wrapper" data-slide="0">
<div class="slider">
<div class="slide-items">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus tempus diam nec mauris vehicula, eget euismod lorem ultrices. Fusce suscipit nisi nisi, nec fermentum ligula finibus non. Cras scelerisque risus libero, quis faucibus enim elementum non. Ut vitae purus in enim aliquam sollicitudin non et dui. Duis nec varius lectus.</p>
</div>
<div class="slide-items">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus tempus diam nec mauris vehicula, eget euismod lorem ultrices. Fusce suscipit nisi nisi, nec fermentum ligula finibus non. Cras scelerisque risus libero, quis faucibus enim elementum non. Ut vitae purus in enim aliquam sollicitudin non et dui. Duis nec varius lectus.</p>
</div>
</div>
<div class="buttons">
<div class="prev">prev</div>
<div class="next">next</div>
</div>
</div>
</div>
I modified something from your code. Is this similar what you are trying to do??
$(document).ready(function() {
$('.prev').on('click', function(e) {
e.stopPropagation();
// store variable relevent to clicked slider
var sliderWrapper = $(this).closest('.slider-wrapper'),
slideItems = sliderWrapper.find('.slide-items'),
slider = sliderWrapper.find('.slider'),
currentSlide = sliderWrapper.attr('data-slide');
// Check if data-slide attribute is greater than 0
if( currentSlide > 0 ) {
// Decremement current slide
currentSlide--;
// Assign CSS position to clicked slider
slider.css({'right' : currentSlide*slideItems.outerWidth() });
// Update data-slide attribute
sliderWrapper.attr('data-slide', currentSlide);
}
});
$('.next').on('click', function(e) {
e.stopPropagation();
// store variable relevent to clicked slider
var sliderWrapper = $(this).closest('.slider-wrapper'),
slideItems = sliderWrapper.find('.slide-items'),
slider = sliderWrapper.find('.slider'),
totalSlides = slideItems.length,
currentSlide = sliderWrapper.attr('data-slide');
// Check if dataslide is less than the total slides
if( currentSlide < totalSlides - 1 ) {
// Increment current slide
currentSlide++;
// Assign CSS position to clicked slider
slider.css({'right' : currentSlide*slideItems.outerWidth() });
// Update data-slide attribute
sliderWrapper.attr('data-slide', currentSlide);
}
})
$('.slider-wrapper').each(function(){
// create a simple instance
// by default, it only adds horizontal recognizers
var direction;
var mc = new Hammer(this),
itemLength = $(this).find('.slide-items').length,
count = 0,
slide = $(this);
var sliderWrapper = slide,
slideItems = sliderWrapper.find('.slide-items'),
slider = sliderWrapper.find('.slider'),
totalSlides = slideItems.length,
currentSlide = sliderWrapper.attr('data-slide');
var dragDist = 40;
var dist = 0;
var curPosition = 0;
var toPosition = 0;
mc.on("panleft panright", function(ev) {
direction = ev.type;
// modified
dist = ev.deltaX;
var maxDist = Math.min(dragDist, dist);
curPosition = currentSlide*slideItems.outerWidth();
toPosition = curPosition + maxDist*-1;
slider.css({'right': toPosition + 'px'});
});
mc.on("panend", function(ev) {
slider.css({'right': curPosition + 'px'});
if( Math.abs(dist) <= dragDist ){
return;
}
if(direction === "panleft") {
console.log('pan left');
// Check if dataslide is less than the total slides
if( currentSlide < totalSlides - 1 ) {
// Increment current slide
currentSlide++;
// Assign CSS position to clicked slider
slider.css({'right' : currentSlide*slideItems.outerWidth() });
// Update data-slide attribute
sliderWrapper.attr('data-slide', currentSlide);
}
}
if(direction === "panright") {
console.log('pan right');
// Check if data-slide attribute is greater than 0
if( currentSlide > 0 ) {
// Decremement current slide
currentSlide--;
// Assign CSS position to clicked slider
slider.css({'right' : currentSlide*slideItems.outerWidth() });
// Update data-slide attribute
sliderWrapper.attr('data-slide', currentSlide);
}
}
});
});
});
$(window).on('load', function() {
$('.slider-wrapper').each(function() {
var slideItems = $(this).find('.slide-items'),
items = slideItems.length,
sliderBox = $(this).find('.slider'),
sliderWrapperWidth = $(this).width();
slideItems.outerWidth( sliderWrapperWidth / 2 );
sliderBox.width( slideItems.outerWidth() * items );
});
});
/* http://meyerweb.com/eric/tools/css/reset/
v2.0 | 20110126
License: none (public domain)
*/
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline; }
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
display: block; }
body {
line-height: 1; }
ol, ul {
list-style: none; }
blockquote, q {
quotes: none; }
blockquote:before, blockquote:after,
q:before, q:after {
content: '';
content: none; }
table {
border-collapse: collapse;
border-spacing: 0; }
* {
box-sizing: border-box; }
.container {
max-width: 1280px;
margin: 0 auto; }
.container .slider-wrapper {
margin-bottom: 40px;
background-color: grey;
overflow: hidden; }
.container .slider-wrapper .slider {
position: relative;
right: 0;
display: flex;
flex-wrap: wrap;
overflow: hidden; }
.container .slider-wrapper .slider > div {
padding: 10px;
background-color: #e5d0d0; }
.container .slider-wrapper .slider > div p {
color: purple; }
.container .slider-wrapper .buttons {
display: flex;
justify-content: space-between;
background: beige;
padding: 10px 0; }
.container .slider-wrapper .buttons div {
background-color: cyan; }
/*# sourceMappingURL=style.css.map */
<script src="https://cdnjs.cloudflare.com/ajax/libs/hammer.js/2.0.8/hammer.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="slider-wrapper" data-slide="0">
<div class="slider">
<div class="slide-items">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus tempus diam nec mauris vehicula, eget euismod lorem ultrices. Fusce suscipit nisi nisi, nec fermentum ligula finibus non. Cras scelerisque risus libero, quis faucibus enim elementum non. Ut vitae purus in enim aliquam sollicitudin non et dui. Duis nec varius lectus.</p>
</div>
<div class="slide-items">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam eget ex mi. Etiam a vestibulum ligula, id porta dui. Duis in iaculis quam. Integer aliquam justo nec nibh consequat vulputate.</p>
</div>
<div class="slide-items">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus tempus diam nec mauris vehicula, eget euismod lorem ultrices. Fusce suscipit nisi nisi, nec fermentum ligula finibus non. Cras scelerisque risus libero, quis faucibus enim elementum non. Ut vitae purus in enim aliquam sollicitudin non et dui. Duis nec varius lectus.</p>
</div>
</div>
<div class="buttons">
<div class="prev">prev</div>
<div class="next">next</div>
</div>
</div>
<div class="slider-wrapper" data-slide="0">
<div class="slider">
<div class="slide-items">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus tempus diam nec mauris vehicula, eget euismod lorem ultrices. Fusce suscipit nisi nisi, nec fermentum ligula finibus non. Cras scelerisque risus libero, quis faucibus enim elementum non. Ut vitae purus in enim aliquam sollicitudin non et dui. Duis nec varius lectus.</p>
</div>
</div>
<div class="buttons">
<div class="prev">prev</div>
<div class="next">next</div>
</div>
</div>
<div class="slider-wrapper" data-slide="0">
<div class="slider">
<div class="slide-items">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus tempus diam nec mauris vehicula, eget euismod lorem ultrices. Fusce suscipit nisi nisi, nec fermentum ligula finibus non. Cras scelerisque risus libero, quis faucibus enim elementum non. Ut vitae purus in enim aliquam sollicitudin non et dui. Duis nec varius lectus.</p>
</div>
<div class="slide-items">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam eget ex mi. Etiam a vestibulum ligula, id porta dui. Duis in iaculis quam. Integer aliquam justo nec nibh consequat vulputate.</p>
</div>
</div>
<div class="buttons">
<div class="prev">prev</div>
<div class="next">next</div>
</div>
</div>
<div class="slider-wrapper" data-slide="0">
<div class="slider">
<div class="slide-items">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus tempus diam nec mauris vehicula, eget euismod lorem ultrices. Fusce suscipit nisi nisi, nec fermentum ligula finibus non. Cras scelerisque risus libero, quis faucibus enim elementum non. Ut vitae purus in enim aliquam sollicitudin non et dui. Duis nec varius lectus.</p>
</div>
</div>
<div class="buttons">
<div class="prev">prev</div>
<div class="next">next</div>
</div>
</div>
<div class="slider-wrapper" data-slide="0">
<div class="slider">
<div class="slide-items">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus tempus diam nec mauris vehicula, eget euismod lorem ultrices. Fusce suscipit nisi nisi, nec fermentum ligula finibus non. Cras scelerisque risus libero, quis faucibus enim elementum non. Ut vitae purus in enim aliquam sollicitudin non et dui. Duis nec varius lectus.</p>
</div>
<div class="slide-items">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus tempus diam nec mauris vehicula, eget euismod lorem ultrices. Fusce suscipit nisi nisi, nec fermentum ligula finibus non. Cras scelerisque risus libero, quis faucibus enim elementum non. Ut vitae purus in enim aliquam sollicitudin non et dui. Duis nec varius lectus.</p>
</div>
</div>
<div class="buttons">
<div class="prev">prev</div>
<div class="next">next</div>
</div>
</div>
</div>
Related
Rewrite jQuery easing easeInExpo function into plain javascript & css
So I have this great little nugget of code that I am trying to rewrite into plain JavaScript and CSS without jQuery. jQuery.extend(jQuery.easing,{ easeInExpo: function (x, t, b, c, d) { return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b; } }); var nset = false; $('button#hmenu').click(function(){ if(!nset){ $('ul#nav').delay(35).slideDown(300,'easeInExpo'); $('button#hmenu').addClass('active'); nset = true; } else { $('ul#nav').slideUp(550); nset = false; $('button#hmenu').removeClass('active'); } }) I'm looking at some CSS transitions that use easing but just wondering what the options are? In my code I have a slideDown and up easing functions. This is used in production for a mobile menu nav.
Update: This github repo (You don't need jQuery) has a really comprehensive list of common jQuery functions, all rewritten in vanilla Javascript. It includes animations, query selectors, ajax, events and other advanced jQuery features. The slightly older youmightnotneedjquery.com is also very good, particularly if you need to support older IE versions. You can achieve an easeInExpo style animation by using the following CSS, as provided by this website: transition: all 500ms cubic-bezier(0.950, 0.050, 0.795, 0.035); The below example illustrates this easing property on the height of a div. I've updated it to match the delay you've added in jQuery when clicked (35ms), the timings (300ms and 550ms respectively), and jQuery's default easing ('swing') – as provided by this answer – when it's closed: let expandable = document.getElementById('expandable'); let expandButton = document.getElementById('expand-button'); expandButton.addEventListener('click', () => { expandable.classList.toggle('expanded'); }); #expandable { background: red; transition: all 550ms cubic-bezier(.02, .01, .47, 1); height: 0px; width: 100px; transition-delay: 0ms; } #expandable.expanded { height: 100px; transition-delay: 35ms; transition: all 300ms cubic-bezier(0.950, 0.050, 0.795, 0.035); } <div id="expandable"></div> <br /> <button id="expand-button">Toggle expand</button>
There's a little bit of magic needed here in order to get your collapsible component to expand to a variable height. If you are just expanding to the same height each time, say 100px, that's a simple as creating a single class such as "expanded" and then adding and removing that class as a boolean switch. We'll still be using a boolean switch for variable heights, but we'll also need to get the heights of each expandable element using JavaScript, and then refresh those height values if the size of the user's window changes to account for text-wrapping, image resizing, etc. We can achieve rather simply using custom CSS properties (variables), with a fallback value to unset, meaning that when to variable height is present, the box will expand to show all contents without an animation as a last resort, but in most if not all cases (and for all modern browsers) the custom CSS variable should be the ideal solution for unique values per section. Here it is in action (below), with both a toggle and accordion example, with a cubic bezier easing function used to closely match the easeInExpo function you supplied in your original question. I pulled this easing function cubic-bezier(0.95, 0.05, 0.795, 0.035) from easings.net/en#easeInExpo where they have a pure CSS easing for easeInExpo and many others. Simple Example const expandables = document.querySelectorAll('.expandable'); const setInnerHeights = () => { for (const expandable of expandables) { expandable.style.setProperty('--inner-height', Array.from(expandable.children).map(child => child.offsetHeight).reduce((a, c) => a + c, 0) + 'px'); } }; setInnerHeights(); document.addEventListener('click', e => { if (e.target?.matches('.expand-trigger')) { const expandable = e.target.nextElementSibling; expandable.classList[expandable.classList.contains('expanded') ? 'remove' : 'add']('expanded'); } }); window.addEventListener('resize', setInnerHeights); html { height: 100%; box-sizing: border-box; } *, *::before, *::after { box-sizing: inherit; } body { display: flex; flex-direction: column; align-items: stretch; justify-content: flex-start; min-height: 100%; padding: 20px; } .expandable { max-height: 0; overflow: hidden; transition: max-height 0.25s cubic-bezier(0.95, 0.05, 0.795, 0.035); text-align: left; } .expandable > p { margin: 0; padding: 10px 0; } .expandable.expanded { --content-height: calc(var(--inner-height) + 20px); max-height: var(--content-height, unset); } <button class="expand-trigger">Expand #1</button> <div class="expandable"> <p>Lorem ipsum dolor sit amet.</p> </div> <button class="expand-trigger">Expand #2</button> <div class="expandable"> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam mi purus, interdum id mattis et, posuere nec urna. Mauris in ornare sem. Phasellus non eros augue. Fusce tempus bibendum mauris, vel luctus est viverra eget. Cras vitae lectus magna. Integer vulputate est ut felis dictum consectetur. Nunc vitae enim at sem rhoncus aliquet et id risus. Etiam faucibus quis turpis eu pellentesque. Aliquam dictum lorem nec orci finibus commodo. Etiam tincidunt lacinia consectetur. Praesent tortor lorem, imperdiet sed varius vel, varius ac quam. Vestibulum aliquam lorem sem, sit amet imperdiet purus commodo eu. Integer a iaculis tortor.</p> </div> <button class="expand-trigger">Expand #3</button> <div class="expandable"> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam mi purus, interdum id mattis et, posuere nec urna. Mauris in ornare sem. Phasellus non eros augue. Fusce tempus bibendum mauris, vel luctus est viverra eget. Cras vitae lectus magna. Integer vulputate est ut felis dictum consectetur. Nunc vitae enim at sem rhoncus aliquet et id risus. Etiam faucibus quis turpis eu pellentesque. Aliquam dictum lorem nec orci finibus commodo. Etiam tincidunt lacinia consectetur. Praesent tortor lorem, imperdiet sed varius vel, varius ac quam. Vestibulum aliquam lorem sem, sit amet imperdiet purus commodo eu. Integer a iaculis tortor.</p> <p>Integer convallis lectus eu felis bibendum, vel lacinia metus imperdiet. Maecenas vulputate, quam vitae tempus pretium, erat felis euismod risus, nec blandit leo mi eget purus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer at neque laoreet, egestas dui ut, bibendum lorem. Maecenas elementum odio a congue facilisis. Vivamus risus urna, vestibulum egestas sem nec, lacinia volutpat metus. Suspendisse potenti. Suspendisse ullamcorper commodo libero, sed rhoncus nibh porta in. Donec mi felis, posuere luctus varius ac, faucibus vitae erat.</p> </div> Complex Example const initAccordions = () => { const getNode = selector => document.querySelector(selector), getNodes = selector => Array.from(document.querySelectorAll(selector)), findChildren = (node, selector) => Array.from(node.children).filter(e => e.matches?.(selector)), findChild = (node, selector) => Array.from(node.children).find(e => e.matches?.(selector)), _addInput = (node, position, id, checked) => node.insertAdjacentHTML(position, `<input type="radio" name="accordion-${id}"${checked ? ' checked="checked"' : ''}>`), setInnerHeight = node => { const height = Array.from(node.children).map(child => child.offsetHeight).reduce((a, c) => a + c, 0) + 'px'; node.style.setProperty('--inner-height', height); }, accordions = Array.from(document.querySelectorAll('.accordion')); let accordionIndex = 0; for (const accordion of accordions) { const isToggle = accordion.dataset?.type === 'toggle', panels = findChildren(accordion, '.accordion--panel'); let panelIndex = 0; for (const panel of panels) { const title = findChild(panel, '.accordion--panel--title'), content = findChild(panel, '.accordion--panel--content'), addInput = (node, position, checked) => _addInput(node, position, accordionIndex + (isToggle ? '-' + panelIndex : ''), checked); setInnerHeight(content); addInput(title, 'beforebegin'); addInput(title, 'afterbegin', true); panelIndex++; } accordionIndex++; } window.addEventListener('resize', () => { const panelContents = Array.from(document.querySelectorAll('.accordion > .accordion--panel > .accordion--panel--content')); for (const content of panelContents) setInnerHeight(content); }); }; initAccordions(); html { height: 100%; box-sizing: border-box; } *, *::before, *::after { box-sizing: inherit; } body { display: flex; flex-direction: column; align-items: center; justify-content: flex-start; min-height: 100%; padding: 20px; } .accordion--panel > [type=checkbox], .accordion--panel > [type=radio], .accordion--panel--title > [type=checkbox], .accordion--panel--title > [type=radio] { -webkit-appearance: none; -moz-appearance: none; appearance: none; display: block; position: absolute; left: 0; top: 0; width: 100%; height: 100%; cursor: pointer; } .accordion--panel > [type=checkbox]:checked, .accordion--panel > [type=radio]:checked, .accordion--panel--title > [type=checkbox]:checked, .accordion--panel--title > [type=radio]:checked { display: none; } .accordion--panel { border-radius: 7px; } .accordion--panel--title { background-color: #ccc; } .accordion--panel--content { box-shadow: inset 0 0 0 2px #ccc; border-radius: 0 0 7px 7px; } .accordion { display: flex; flex-direction: column; gap: 10px; width: 100%; max-width: 500px; } .accordion--panel { display: flex; flex-direction: column; position: relative; overflow: hidden; } .accordion--panel > [type=checkbox], .accordion--panel > [type=radio] { z-index: 1; } .accordion--panel--title, .accordion--panel--content { padding-inline: 15px; } .accordion--panel--title { position: relative; padding-block: 10px; } .accordion--panel--content { max-height: 0; overflow: hidden; transition: max-height 0.25s cubic-bezier(0.95, 0.05, 0.795, 0.035); } .accordion--panel--content--inner > p:first-child { margin-top: 10px; } .accordion--panel--content--inner > p:last-child { margin-bottom: 10px; } [type=checkbox]:checked ~ .accordion--panel--content, [type=radio]:checked ~ .accordion--panel--content { --content-height: calc(var(--inner-height) + 20px); max-height: var(--content-height, unset); } <h2>Accordion Demo</h2> <div class="accordion" data-type="accordion"> <div class="accordion--panel"> <div class="accordion--panel--title">Title #1</div> <div class="accordion--panel--content"> <div class="accordion--panel--content--inner"> <p>Lorem ipsum dolor sit amet.</p> </div> </div> </div> <div class="accordion--panel"> <div class="accordion--panel--title">Title #2</div> <div class="accordion--panel--content"> <div class="accordion--panel--content--inner"> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam mi purus, interdum id mattis et, posuere nec urna. Mauris in ornare sem. Phasellus non eros augue. Fusce tempus bibendum mauris, vel luctus est viverra eget. Cras vitae lectus magna. Integer vulputate est ut felis dictum consectetur. Nunc vitae enim at sem rhoncus aliquet et id risus. Etiam faucibus quis turpis eu pellentesque. Aliquam dictum lorem nec orci finibus commodo. Etiam tincidunt lacinia consectetur. Praesent tortor lorem, imperdiet sed varius vel, varius ac quam. Vestibulum aliquam lorem sem, sit amet imperdiet purus commodo eu. Integer a iaculis tortor.</p> </div> </div> </div> <div class="accordion--panel"> <div class="accordion--panel--title">Title #3</div> <div class="accordion--panel--content"> <div class="accordion--panel--content--inner"> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam mi purus, interdum id mattis et, posuere nec urna. Mauris in ornare sem. Phasellus non eros augue. Fusce tempus bibendum mauris, vel luctus est viverra eget. Cras vitae lectus magna. Integer vulputate est ut felis dictum consectetur. Nunc vitae enim at sem rhoncus aliquet et id risus. Etiam faucibus quis turpis eu pellentesque. Aliquam dictum lorem nec orci finibus commodo. Etiam tincidunt lacinia consectetur. Praesent tortor lorem, imperdiet sed varius vel, varius ac quam. Vestibulum aliquam lorem sem, sit amet imperdiet purus commodo eu. Integer a iaculis tortor.</p> <p>Integer convallis lectus eu felis bibendum, vel lacinia metus imperdiet. Maecenas vulputate, quam vitae tempus pretium, erat felis euismod risus, nec blandit leo mi eget purus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer at neque laoreet, egestas dui ut, bibendum lorem. Maecenas elementum odio a congue facilisis. Vivamus risus urna, vestibulum egestas sem nec, lacinia volutpat metus. Suspendisse potenti. Suspendisse ullamcorper commodo libero, sed rhoncus nibh porta in. Donec mi felis, posuere luctus varius ac, faucibus vitae erat.</p> </div> </div> </div> </div> <h2>Toggle Demo</h2> <div class="accordion" data-type="toggle"> <div class="accordion--panel"> <div class="accordion--panel--title">Title #1</div> <div class="accordion--panel--content"> <div class="accordion--panel--content--inner"> <p>Lorem ipsum dolor sit amet.</p> </div> </div> </div> <div class="accordion--panel"> <div class="accordion--panel--title">Title #2</div> <div class="accordion--panel--content"> <div class="accordion--panel--content--inner"> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam mi purus, interdum id mattis et, posuere nec urna. Mauris in ornare sem. Phasellus non eros augue. Fusce tempus bibendum mauris, vel luctus est viverra eget. Cras vitae lectus magna. Integer vulputate est ut felis dictum consectetur. Nunc vitae enim at sem rhoncus aliquet et id risus. Etiam faucibus quis turpis eu pellentesque. Aliquam dictum lorem nec orci finibus commodo. Etiam tincidunt lacinia consectetur. Praesent tortor lorem, imperdiet sed varius vel, varius ac quam. Vestibulum aliquam lorem sem, sit amet imperdiet purus commodo eu. Integer a iaculis tortor.</p> </div> </div> </div> <div class="accordion--panel"> <div class="accordion--panel--title">Title #3</div> <div class="accordion--panel--content"> <div class="accordion--panel--content--inner"> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam mi purus, interdum id mattis et, posuere nec urna. Mauris in ornare sem. Phasellus non eros augue. Fusce tempus bibendum mauris, vel luctus est viverra eget. Cras vitae lectus magna. Integer vulputate est ut felis dictum consectetur. Nunc vitae enim at sem rhoncus aliquet et id risus. Etiam faucibus quis turpis eu pellentesque. Aliquam dictum lorem nec orci finibus commodo. Etiam tincidunt lacinia consectetur. Praesent tortor lorem, imperdiet sed varius vel, varius ac quam. Vestibulum aliquam lorem sem, sit amet imperdiet purus commodo eu. Integer a iaculis tortor.</p> <p>Integer convallis lectus eu felis bibendum, vel lacinia metus imperdiet. Maecenas vulputate, quam vitae tempus pretium, erat felis euismod risus, nec blandit leo mi eget purus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer at neque laoreet, egestas dui ut, bibendum lorem. Maecenas elementum odio a congue facilisis. Vivamus risus urna, vestibulum egestas sem nec, lacinia volutpat metus. Suspendisse potenti. Suspendisse ullamcorper commodo libero, sed rhoncus nibh porta in. Donec mi felis, posuere luctus varius ac, faucibus vitae erat.</p> </div> </div> </div> </div> Other CSS easing functions are available at easings.net. You can also customize your easing function visually using Chrome's DevTools by adding either the transition or transition-timing-function properties to any element with the value of ease, then clicking the square curve icon next to the word ease and dragging either of the circular handles.
jQuery, move ALL elements lower
I have a serious issue: with jQuery, I have to move ALL elements toward down, because an advertisement banner must be put up there so that it wont cover anything. Its like havin a frameset at the top. I was trying this: jQuery('*').each(function() { var $this = jQuery(this); if ($this.css('position') === 'fixed' || $this.css('position') === 'absolute') { $this.css('margin-top', 80); } }); but not all element are actually pushed.
Using a combination of your jQuery to add margin to fixed and absolute positioned elements, and padding-top to the body to cover static positioned elements I believe you can cover what you're after. Notice I changed your selector in the jQuery to look for elements that are not of the 'ad' class. This assuming your ad is absolutely positioned. $(':not(.ad)').each(function() { var $this = $(this); if ($this.css('position') === 'fixed' || $this.css('position') === 'absolute') { $this.css('margin-top', 80); } }); body { padding-top: 80px; } .content { position: static; padding: 0 110px; } .ad { position: fixed; top: 0; left: 0; width: 728px; height: 80px; background: red; } div.abs { width: 100px; height: auto; position: absolute; background: gray; top: 0; left: 0; } div.fxd { width: 100px; height: auto; position: fixed; background: gray; top: 0; right: 0; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="content"> <p>Content in a static positioned block level div. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam venenatis elit nunc, a bibendum nisi volutpat id. Morbi pretium ultrices tortor sed porta. Praesent ullamcorper tristique luctus. Suspendisse sodales, est gravida accumsan sodales, urna turpis congue tortor, in ullamcorper justo magna et ex. Aliquam commodo, mi eget euismod volutpat, lorem lectus ultricies est, at congue velit ipsum vitae neque. Aenean consectetur ante lacus, ac iaculis sapien pulvinar a. Aenean porta porttitor faucibus. Sed nec metus vel enim suscipit placerat. Phasellus cursus pretium ex at venenatis.</p> </div> <div class="content"> <p>Content in a static positioned block level div. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam venenatis elit nunc, a bibendum nisi volutpat id. Morbi pretium ultrices tortor sed porta. Praesent ullamcorper tristique luctus. Suspendisse sodales, est gravida accumsan sodales, urna turpis congue tortor, in ullamcorper justo magna et ex. Aliquam commodo, mi eget euismod volutpat, lorem lectus ultricies est, at congue velit ipsum vitae neque. Aenean consectetur ante lacus, ac iaculis sapien pulvinar a. Aenean porta porttitor faucibus. Sed nec metus vel enim suscipit placerat. Phasellus cursus pretium ex at venenatis.</p> </div> <div class="abs">This is a <strong>absolute</strong> positioned div at 0/0</div> <div class="fxd">This is a <strong>fixed</strong> positioned div at 0/0</div> <div class="ad"></div>
Try this. jQuery(document).ready(function() { /* // For Down all Element Viewport $('html').css('margin-top', 80); // or // For Down all Element Body $('body').css('margin-top', 80); */ // For all fixed or absolute element var elems = document.body.getElementsByTagName("*"); var len = elems.length for (var i=0;i<len;i++) { if (window.getComputedStyle(elems[i],null).getPropertyValue('position') == 'fixed' || window.getComputedStyle(elems[i],null).getPropertyValue('position') == 'absolute') { elems[i].style.marginTop ='80px'; } } }); // If that content has a specific selector like ID or class, then use $( your selector ).css("margin-top","80px");
Copying jQuery offset from one element to another puts them in different places
My goal is given 2 divs, one with tagged content, generate new content in the other div that is vertically aligned with the first. A minimal example of what I've got so far is below in the snippet. I've tried doing adjustments like subtracting $('sidebar').offset().top and/or the height of the header from the new element's top-side offset (thinking that maybe the new element was offsetting from the top of the sidebar instead of the document for some reason), but that still doesn't put it in the right place. I think the hurdle here is figuring out why tag_offset.top and test_tip.offset().top aren't equal at the end, even though that's explicitly being assigned when test_tip is instantiated. var tag_offset = $('.jt-tooltip-tag').offset(); tag_offset['left'] = 0; var tag_text = $('.jt-tooltip-text').text(); var test_tip = $('<div class="jt-sidebar-tip">').text(tag_text).offset(tag_offset).appendTo('#jt-tooltip-sidebar'); .middlebar { width: 49%; float: left; } .sidebar { height: 500px; width: 49%; float: right; border: 1px solid purple; } .jt-tooltip-tag { font-weight: bold; background-color: #14c9c9; } .jt-tooltip-text { display: none; } .jt-sidebar-tip { position: relative; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="page"> <h1 class="header"> Omigosh a header! </h1> <div class="content"> <div class="middlebar"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin nec tortor justo. Donec magna neque, interdum eu diam ut, efficitur pharetra ligula. Aenean libero justo, feugiat a est a, hendrerit cursus justo. Donec vehicula ligula ut diam bibendum, vel convallis purus blandit. Nulla <span class="jt-tooltip"><span class="jt-tooltip-tag">facilisi.</span><span class="jt-tooltip-text">This should be vertically-aligned with facilisi.</span></span> Donec pretium, leo at commodo dignissim, eros ligula vulputate sem, quis iaculis turpis est ac erat. Ut ultrices mauris efficitur tellus gravida convallis vitae ac magna. Nullam vel enim ut eros tempor dictum et quis risus. Aliquam finibus sed justo eu porttitor. </div> <div class="sidebar" id="jt-tooltip-sidebar"> </div> </div> </div>
In order to position an element relative to the document, you need to set its CSS to position: absolute;. But then you also need to set its left offset to a position that puts it into its container. I've done this by copying $("#jt-tooltip-sidebar").offset().left. var tag_offset = $('.jt-tooltip-tag').offset(); tag_offset.left = $("#jt-tooltip-sidebar").offset().left; var tag_text = $('.jt-tooltip-text').text(); var test_tip = $('<div class="jt-sidebar-tip">').text(tag_text).offset(tag_offset).appendTo('#jt-tooltip-sidebar'); .middlebar { width: 49%; float: left; } .sidebar { height: 500px; width: 49%; float: right; border: 1px solid purple; } .jt-tooltip-tag { font-weight: bold; background-color: #14c9c9; } .jt-tooltip-text { display: none; } .jt-sidebar-tip { position: absolute; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="page"> <h1 class="header"> Omigosh a header! </h1> <div class="content"> <div class="middlebar"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin nec tortor justo. Donec magna neque, interdum eu diam ut, efficitur pharetra ligula. Aenean libero justo, feugiat a est a, hendrerit cursus justo. Donec vehicula ligula ut diam bibendum, vel convallis purus blandit. Nulla <span class="jt-tooltip"><span class="jt-tooltip-tag">facilisi.</span><span class="jt-tooltip-text">This should be vertically-aligned with facilisi.</span></span> Donec pretium, leo at commodo dignissim, eros ligula vulputate sem, quis iaculis turpis est ac erat. Ut ultrices mauris efficitur tellus gravida convallis vitae ac magna. Nullam vel enim ut eros tempor dictum et quis risus. Aliquam finibus sed justo eu porttitor. </div> <div class="sidebar" id="jt-tooltip-sidebar"> </div> </div> </div>
How to create a random changing paragraph with fade effects?
For a horror themed website I'm supposed to create a div that houses reviews. I want the reviews to stay on screen for a couple of seconds before fading out and being replaced with another review. I kind of have an idea about how to get the desired effect using Jquery and absolute css placement, but I'm having trouble getting the code to do exactly what I want. Some examples on google and this website have pushed me to the right direction I think, but none work very well for multiple paragraphs + random placement. (In case a visitor returns to the site, he's faced with different reviews the the last time) I'm guessing I'll need an array.. $('#leftReview').fadeIn('fast').delay(1000).fadeOut('fast'); #ReviewContainer{ width: 400px; height: 400px; margin: 0 auto; border: 2px solid white; color: white; background-color: #000; position: relative; } .leftReview{ position:absolute; top:0; left:0; width:400px; height:400px; } <div id="ReviewContainer"> <div class="leftReview"> <h3>Review #1</h3> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce id sem libero. Duis sit amet pretium sapien.</p> </div> <div class="leftReview"> <h3>Review #2</h3> <p>Nam ut nunc id turpis consequat vestibulum eget sit amet arcu. Nullam nec pellentesque leo, eu pulvinar velit.</p> </div> <div class="leftReview"> <h3>Review #3</h3> <p>Pellentesque sagittis justo sit amet odio commodo, in malesuada nulla elementum. Integer pretium, sem nec vehicula dapibus.</p> </div> <div class="leftReview"> <h3>Review #4</h3> <p>Arcu elit scelerisque enim, vel tincidunt velit ex non dolor. Proin nec fringilla mi. Nunc commodo nulla vitae ipsum eleifend fermentum.</p> </div> </div>
To randomize the divs you need to use Math.random function to get a random number. $(document).ready(function() { setInterval(rotate,1200); }) var panels = $('.leftReview'); var arr = []; var rand = getRandom(panels.length); panels.eq(rand).fadeIn(); function rotate() { var visible = panels.filter(':visible').fadeOut(function() { panels.eq(getRandom(panels.length)).fadeIn(); }); } function getRandom(length) { if (arr.length == length) { arr = []; } var rand = Math.floor(Math.random() * length); if (arr.indexOf(rand) > -1) { return getRandom(length) } arr.push(rand) return rand; } #ReviewContainer{ width: 400px; height: 400px; margin: 0 auto; border: 2px solid white; color: white; background-color: #000; position: relative; } .leftReview { position:absolute; top:0; left:0; width:400px; height:400px; display:none } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="ReviewContainer"> <div class="leftReview"> <h3>Review #1</h3> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce id sem libero. Duis sit amet pretium sapien.</p> </div> <div class="leftReview"> <h3>Review #2</h3> <p>Nam ut nunc id turpis consequat vestibulum eget sit amet arcu. Nullam nec pellentesque leo, eu pulvinar velit.</p> </div> <div class="leftReview"> <h3>Review #3</h3> <p>Pellentesque sagittis justo sit amet odio commodo, in malesuada nulla elementum. Integer pretium, sem nec vehicula dapibus.</p> </div> <div class="leftReview"> <h3>Review #4</h3> <p>Arcu elit scelerisque enim, vel tincidunt velit ex non dolor. Proin nec fringilla mi. Nunc commodo nulla vitae ipsum eleifend fermentum.</p> </div> </div> http://jsbin.com/pojoke/edit?html,css,js
For make this, use setInterval event and make your div on display:none first Please try $(document).ready(function() { var id = 0; var carrousel = setInterval(rotate,1200); function rotate(){ if(id != $('.leftReview').length){ $('.leftReview').eq(id).fadeIn(100).delay(1000).fadeOut(100) id++; } } }) #ReviewContainer{ width: 400px; height: 400px; margin: 0 auto; border: 2px solid white; color: white; background-color: #000; position: relative; } .leftReview{ position:absolute; top:0; left:0; width:400px; height:400px; display:none } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="ReviewContainer"> <div class="leftReview"> <h3>Review #1</h3> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce id sem libero. Duis sit amet pretium sapien.</p> </div> <div class="leftReview"> <h3>Review #2</h3> <p>Nam ut nunc id turpis consequat vestibulum eget sit amet arcu. Nullam nec pellentesque leo, eu pulvinar velit.</p> </div> <div class="leftReview"> <h3>Review #3</h3> <p>Pellentesque sagittis justo sit amet odio commodo, in malesuada nulla elementum. Integer pretium, sem nec vehicula dapibus.</p> </div> <div class="leftReview"> <h3>Review #4</h3> <p>Arcu elit scelerisque enim, vel tincidunt velit ex non dolor. Proin nec fringilla mi. Nunc commodo nulla vitae ipsum eleifend fermentum.</p> </div> </div> Update with random view $(document).ready(function() { var carrousel = setInterval(rotate,1200); function rotate(){ id = Math.floor((Math.random() * $(".leftReview").length)); $('.leftReview').eq(id).fadeIn(100).delay(1000).fadeOut(100) } }) #ReviewContainer{ width: 400px; height: 400px; margin: 0 auto; border: 2px solid white; color: white; background-color: #000; position: relative; } .leftReview{ position:absolute; top:0; left:0; width:400px; height:400px; display:none } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="ReviewContainer"> <div class="leftReview"> <h3>Review #1</h3> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce id sem libero. Duis sit amet pretium sapien.</p> </div> <div class="leftReview"> <h3>Review #2</h3> <p>Nam ut nunc id turpis consequat vestibulum eget sit amet arcu. Nullam nec pellentesque leo, eu pulvinar velit.</p> </div> <div class="leftReview"> <h3>Review #3</h3> <p>Pellentesque sagittis justo sit amet odio commodo, in malesuada nulla elementum. Integer pretium, sem nec vehicula dapibus.</p> </div> <div class="leftReview"> <h3>Review #4</h3> <p>Arcu elit scelerisque enim, vel tincidunt velit ex non dolor. Proin nec fringilla mi. Nunc commodo nulla vitae ipsum eleifend fermentum.</p> </div> </div>
anchor link to multiple classes instead of id's with jquery
I have a page with up and down arrows that are links that float on the left. I want them to navigate between div's on the page as a scrolling anchor links. Here is what I have so far.....I know the jquery is far from complete but I think im going in the right direction. Any help would be great. JSFIDDLE: http://jsfiddle.net/t8uaQ/ HTML: <ul id="et-float-menu"> <li class="et-float-menu-item1"> <span><img></span> </li> <li class="et-float-menu-item2"> <span><img></span> </li> </ul> <div class="jumptosection" id="section1"> <h2>Section 1</h2> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam dapibus luctus ligula sit amet tincidunt. Aliquam dapibus ipsum ac metus interdum congue. In sed arcu et quam semper tincidunt vel non enim. Ut sit amet volutpat neque. Suspendisse potenti. Vestibulum cursus erat vitae posuere mattis. Integer eleifend eleifend fermentum.</p> <p>Curabitur arcu tortor, tincidunt in ante ornare, aliquam pulvinar nunc. Quisque elit erat, suscipit non odio a, fringilla fermentum dui. Aenean ultricies nisi vitae massa fermentum facilisis. Donec dignissim iaculis tortor ultrices dapibus.</p> </div> <div class="jumptosection" id="section2"> <h2>Section 2</h2> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam dapibus luctus ligula sit amet tincidunt. Aliquam dapibus ipsum ac metus interdum congue. In sed arcu et quam semper tincidunt vel non enim. Ut sit amet volutpat neque. Suspendisse potenti. Vestibulum cursus erat vitae posuere mattis. Integer eleifend eleifend fermentum.</p> <p>Curabitur arcu tortor, tincidunt in ante ornare, aliquam pulvinar nunc. Quisque elit erat, suscipit non odio a, fringilla fermentum dui. Aenean ultricies nisi vitae massa fermentum facilisis. Donec dignissim iaculis tortor ultrices dapibus.</p> </div> <div class="jumptosection" id="section3"> <h2>Section 3</h2> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam dapibus luctus ligula sit amet tincidunt. Aliquam dapibus ipsum ac metus interdum congue. In sed arcu et quam semper tincidunt vel non enim. Ut sit amet volutpat neque. Suspendisse potenti. Vestibulum cursus erat vitae posuere mattis. Integer eleifend eleifend fermentum.</p> <p>Curabitur arcu tortor, tincidunt in ante ornare, aliquam pulvinar nunc. Quisque elit erat, suscipit non odio a, fringilla fermentum dui. Aenean ultricies nisi vitae massa fermentum facilisis. Donec dignissim iaculis tortor ultrices dapibus.</p> </div> <div class="jumptosection" id="section4"> <h2>Section 4</h2> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam dapibus luctus ligula sit amet tincidunt. Aliquam dapibus ipsum ac metus interdum congue. In sed arcu et quam semper tincidunt vel non enim. Ut sit amet volutpat neque. Suspendisse potenti. Vestibulum cursus erat vitae posuere mattis. Integer eleifend eleifend fermentum.</p> <p>Curabitur arcu tortor, tincidunt in ante ornare, aliquam pulvinar nunc. Quisque elit erat, suscipit non odio a, fringilla fermentum dui. Aenean ultricies nisi vitae massa fermentum facilisis. Donec dignissim iaculis tortor ultrices dapibus.</p> </div> MY CSS: #section1 { padding:20px; margin:10px; background-color:#f8f8f8; } #section2 { padding:20px; margin:10px; background-color:#e8e8e8; } #section3 { padding:20px; margin:10px; background-color:#f8f8f8; } #section4 { padding:20px; margin:10px; background-color:#e8e8e8; } #et-float-menu { position: fixed; z-index: 11; left: 0; top: 45%; background-color: #000; padding: 20px 10px 10px 15px; margin: 0; -webkit-border-top-right-radius: 8px; -webkit-border-bottom-right-radius: 8px; -moz-border-radius-topright: 8px; -moz-border-radius-bottomright: 8px; border-top-right-radius: 8px; border-bottom-right-radius: 8px; } #et-float-menu a { padding: 0; clear: both; float: left; margin-bottom: 10px; color: #fff; } #et-float-menu a:hover { color: #b2b2b2; transition: color 300ms ease 0s; } #et-float-menu li { display: block; margin-left: 0; } .et-float-menu-item a { display: inline-block; font-size: 24px; position: relative; text-align: center; transition: color 300ms ease 0s; color: #fff; text-decoration: none; } .et-float-menu-item a:hover { color: #a0a0a0; } .et-social-icon span { display: none; } .et-float-menu-item1 a:before { content: '↑';font-size:22px; } .et-float-menu-item2 a:before { content: '↓';font-size:22px; } JQUERY: jQuery(document).ready(function(){ var jumptosectionTopPosition = jQuery('.jumptosection').offset().top; jQuery('#scroll').click(function(){ jQuery('html, body').animate({scrollTop:jumptosectionTopPosition}, 'slow'); return false; }); });
Change hrefs of your <a> to scrollUp and scrollDown correspondingly. Stick to some .selected class, which will be used for identifying current selected section. Add this class to the first section in html. Add a function that will perform selection: by adding .selected class and scrolling to newly selected div. function changeSelection(sectionFrom, sectionTo) { if(sectionTo.length > 0) { sectionFrom.removeClass("selected"); sectionTo.addClass("selected"); $("body").animate({scrollTop: sectionTo.offset().top}); } } Attach click listeners to your anchors. Inside each of them find current selected div and div you want to be selected and call changeSelection() using these divs. For scrollDown we want to select the next div: $(document).on("click", "[href='#scrollDown']", function(){ var currentSection = $(".selected"); var nextSection = currentSection.next(".jumptosection"); changeSelection(currentSection, nextSection); return false; }); For scrollUp we want to select the previous div: $(document).on("click", "[href='#scrollUp']", function(){ var currentSection = $(".selected"); var prevSection = currentSection.prev(".jumptosection"); changeSelection(currentSection, prevSection); return false; }); In case you reach the end (the first or the last .jumptosection div), nothing will be changed (it is controlled by the changeSelection function - it checks do we have sectionWeWantScrollTo) Here is the Demo Edited (for http://94co.com/client3/about/) See this answer about WordPress and jQuery. Use jQuery instead of $ in your script It is better to use id instead of href on anchor Make sure you wrap JavaScript of click listeners in jQuery(document).ready(function(){ /*scrollUp and scrollDown click listeners should be here*/ }); (JSFiddle makes this wrap automatically). changeSelection function doesn't need to be wrapped Here is the updated Demo
You can set some initial var that let you know the start point like this: var pre = $('.et-float-menu-item1'), nex = $('.et-float-menu-item2'), act = $('#section1'); Where act is the start And then evaluate prev and next elements: nex.click(function(){ pre.slideDown(); var gt = act.next('div').offset().top; $('body').animate({scrollTop : gt},'slow'); act = act.next('div'); }) pre.click(function(){ var gt = act.prev('div').offset().top; $('body').animate({scrollTop : gt},'slow'); act = act.prev('div'); }) This code can be improved but is the first aproach I can give. Check the Demo Fiddle