jQuery: scroll left / right to next div - javascript

I have a parent .slider-wrap div at 100% width, with 3 .slider-slide-wrap child divs inside, each at 680px width. You can scroll horizontally inside the .slider-wrap div.
I've also created 2 .slider-nav divs, #slider-left sitting on the left, and #slider-right sitting on the right, the idea being, you can scroll as you wish using the scrollbar, but if you clicked the #slider-right div at any time, it would slide you across to the next instance of .slider-slide-wrap divs. Thus, the 2 .slider-nav divs will take you left and right to the next / previous instance of .slider-slide-wrap div.
jsFiddle demo: http://jsfiddle.net/neal_fletcher/rAb3V/
HTML:
<div class="slider-wrap">
<div class="slide-wrap">
<div class="slider-slide-wrap"></div>
<div class="slider-slide-wrap"></div>
<div class="slider-slide-wrap"></div>
</div>
</div>
<div id="slider-left" class="slider-nav"></div>
<div id="slider-right" class="slider-nav"></div>
jQuery:
$(document).ready(function () {
var n = $(".slider-slide-wrap").length,
width = 680,
newwidth = width * n;
$('.slide-wrap').css({
'width': newwidth
});
});
$(document).ready(function () {
$(".slider-slide-wrap").each(function (i) {
var thiswid = 680;
$(this).css({
'left': thiswid * i
});
});
});
If this is at all possible? Any suggestions would be greatly appreciated!

First of I think you need to have an indicator to identify which slide the user has scrolled to, or which slide is currently on the viewport in order for this scroll left & right to work properly.
/*on scroll move the indicator 'shown' class to the
most visible slide on viewport
*/
$('.slider-wrap').scroll(function () {
var scrollLeft = $(this).scrollLeft();
$(".slider-slide-wrap").each(function (i) {
var posLeft = $(this).position().left
var w = $(this).width();
if (scrollLeft >= posLeft && scrollLeft < posLeft + w) {
$(this).addClass('shown').siblings().removeClass('shown');
}
});
});
/* on left button click scroll to
the previous sibling of the current visible slide */
$('#slider-left').click(function () {
var $prev = $('.slide-wrap .shown').prev();
if ($prev.length) {
$('.slider-wrap').animate({
scrollLeft: $prev.position().left
}, 'slow');
}
});
/* on right button click scroll to
the next sibling of the current visible slide */
$('#slider-right').click(function () {
var $next = $('.slide-wrap .shown').next();
if ($next.length) {
$('.slider-wrap').animate({
scrollLeft: $next.position().left
}, 'slow');
}
});
See it working of this jsfiddle.
PS. You also don't need a lot of $(document).ready(), one will do just fine and a best practice to do.

Related

Animate div detect top or bottom of it

I want my div to animate when that div is almost half while scrolling.
How can I do it? It's not on a fixed div but its like sticky sidebar
Just like on this website sample
this is my code
$(function(){ // document ready
if ($('.filter-container').length) { // make sure ".filter-container" element exists
var el = $('.filter-container');
var stickyTop = $('.filter-container').offset().top; // returns number
var stickyHeight = $('.filter-container').height();
$(window).scroll(function(){ // scroll event
var limit = $('#footer').offset().top - stickyHeight - 100;
var windowTop = $(window).scrollTop(); // returns number
if (stickyTop < windowTop){
el.css({ position: 'fixed', top: 0, width: 280 });
}
else {
el.css({ position: 'static', width: 280 });
}
if (limit < windowTop) {
var diff = limit - windowTop;
el.css({top: diff});
}
});
}
});
You could write a jQuery function using Waypoints.
Or more easily (in my opinion) but with higher payload cost use Bootstrap affix. In this case you keep your current css but then add some Bootstrap properties to the div, in your case:
<div class="filter-container" data-spy="affix" data-offset-top="60" data-offset-bottom="200">
This will add the classes .affix-top to the div UNTIL the user scrolls past 60px. Then if will change to .affix when the user gets 200px from the bottom it will change to .affix-bottom to the class.
This jsfiddle shows it quite well:
http://jsfiddle.net/skelly/df8tb/
This shows the appropriate css to get the sticky effect.

Sticky div at bottom of viewport after scroll

I'm trying to create a sticky footer element in a left hand column of a webpage. The right hand column will have dynamic content so I can't put an exact height to any element(except for viewport height). What I'd like to happen is the footer is placed below the viewport until a user starts scrolling and then the footer element is fixed at the bottom of the viewport.
I have a forked Fiddle that works but breaks the content if it is taller than navigation. I've also tried using Sticky Footer, but I can't wrap everything together because of the same issue.
What I've found so far.
var $buzz = $('#buzz'),
viewportHeight = $(window).height(),
buzzHeight = 182,
buzzTop = $buzz.offset().top + buzzHeight,
buzzPosition = buzzTop - viewportHeight;
$(window).bind("resize.browsersize", function () {
var viewportHeight = $(window).height(),
buzzHeight = 182,
buzzTop = $buzz.offset().top + buzzHeight,
buzzPosition = buzzTop - viewportHeight;
}).trigger("resize.browsersize");
$(window).scroll(function () {
if ($(window).scrollTop() >= buzzPosition) {
$buzz.css({
position: 'fixed',
bottom: 0
});
} else {
$buzz.removeAttr("style");
}
});
In the events that cause the divs on the left to resize, call $(window).scroll(); and it will reposition the sticky footer.
$('.change').on('click', function () {
$(this).css("height", "+=50px");
$(window).scroll();
return false;
});

stick div to screen if bottom of div and screen matches

Hello all I am working on a project where in a page I have to stick the div to screen (disable scrolling) when its bottom is at the bottom of screen. I have two divs in the page and both the divs are of variable height. I want to stick the div2 and scroll the div1.
<script>
var divheight
var scrolltop
var screenheight
if(divheight-scrolltop <= screenheight){
/* now stick the div wherever it is i can not
use fixed position as both the divs are floating and
fixing the position will make it to change the position*/ }
else { /*un stick the div*/ }
</script>
i dont know what to put in if and else please help me
Make a function which fire on scroll. The main aim of the function would be to see the difference between screen height and bottom of the div. Once the difference is less than or equal to zero modify the css position to fixed. This will help you
(function ($) {
$('.DIV1').scroll(function () {
var $this = $(this),
win_ht = $(window).height(),
div_ht = $this.height(),
div_bot = $this.offset().top + div_ht;
if (win_ht - div_bot <= 0) {
$this.css({
'position': 'fixed',
'bottom': '0'
})
}
});
})(jQuery);

CSS: Making Horizontal scrollable Menu

I want to add a menu to my application screens. The menu will have the menu icons which are horizontal scroll-able one menu at a time when left or right arrow pressed. Based on the menu screen the menu should be scrolled to that menu icon for that menu screen.
Ex.:
< menu1 | menu2 | menu3 >
Say there are 6 menu icons and 3 are visible at a time. on press of right arrow, it should scroll one item at a time.
and if my screen is related to menu 4, the menu4 has to be positioned.
< menu4 | menu5 | menu6 >
And also each menu item should be clickable.
Please let me know, How I can achieve this.
Update
Have js for MouseOver
<script type="text/javascript">
$(function () {
var div = $('div.sc_menu'),
ul = $('ul.sc_menu'),
ulPadding = 15;
var divWidth = div.width();
div.css({ overflow: 'hidden' });
var lastLi = ul.find('li:last-child');
div.mousemove(function (e) {
var ulWidth = lastLi[0].offsetLeft + lastLi.outerWidth() + ulPadding;
var left = (e.pageX - div.offset().left) * (ulWidth - divWidth) / divWidth;
div.scrollLeft(left);
});
});
</script>
JSFiddle
Check here
Update3
Update 4
This is dynamic menu retreived from db build with ul & li's. If there is more Li than screen width, I simply want an arrow to left & right side to scroll extra li's, if any.
See this fiddle:
http://jsfiddle.net/kzQFQ/49/
$(document).ready(function () {
$('.right').click(function () {
var position = $('.container').position();
var r=position.left-$(window).width()
$('.container').animate({
'left': ''+r+'px'
});
});
$('.left').click(function () {
var position = $('.container').position();
var l=position.left+$(window).width()
if(l<=0)
{
$('.container').animate({
'left': ''+l+'px'
});
}
});
});
Good article about horizontal scrollable menu here
And DEMO (Note: Reduce the size of the browser)
hop this should be help you see link
http://jquery.malsup.com/cycle/int2.html
see Non-Image Content at the last of page
see this fiddle: http://fiddle.jshell.net/vac9x/1/

Scrollpane on the bottom, css is hacky, javascript is hard

I want to put a bar on the bottom of my page containing a varying number of pictures, which (if wider than the page) can be scrolled left and right.
The page width is varying, and I want the pane to be 100% in width.
I was trying to do a trick by letting the middle div overflow and animate it's position with jquery.animate().
Like this:
Here is a fiddle without the js: http://jsfiddle.net/SoonDead/DdPtv/7/
The problems are:
without declaring a large width to the items holder it will not overflow horizontally but vertically. Is this a good hack? (see the width: 9000px in the fiddle)
I only want to scroll the middle pane if it makes sense. For this I need to calculate the width of the overflowing items box (which should be the sum of the items' width inside), and the container of it with the overflow: hidden attribute. (this should be the width of the browser window minus the left and right buttons).
Is there a way to calculate the length of something in js without counting all of it's childrens length manually and sum it up?
Is there a way to get the width of the browser window? Is there a way to get a callback when the window is resized? I need to correct the panes position if the window suddenly widens (and the items are in a position that should not be allowed)
Since the window's width can vary I need to calculate on the fly if I can scroll left or right.
Can you help me with the javascript?
UPDATE: I have a followup question for this one: Scroll a div vertically to a desired position using jQuery Please help me solve that one too.
Use white-space:nowrap on the item container and display:inline or display:inline-block to prevent the items from wrapping and to not need to calculate or set an explicit width.
Edit:: Here's a live working demo: http://jsfiddle.net/vhvzq/2/
HTML
<div class="hscroll">
<ol>
<li>...</li>
<li>...</li>
</ol>
<button class="left"><</button>
<button class="right">></button>
</div>
CSS
.hscroll { white-space:nowrap; position:relative }
.hscroll ol { overflow:hidden; margin:0; padding:0 }
.hscroll li { list-style-type:none; display:inline-block; vertical-align:middle }
.hscroll button { position:absolute; height:100%; top:0; width:2em }
.hscroll .left { left:0 }
.hscroll .right { right:0 }
JavaScript (using jQuery)
$('.hscroll').each(function(){
var $this = $(this);
var scroller = $this.find('ol')[0];
var timer,offset=15;
function scrollLeft(){ scroller.scrollLeft -= offset; }
function scrollRight(){ scroller.scrollLeft += offset; }
function clearTimer(){ clearInterval(timer); }
$this.find('.left').click(scrollLeft).mousedown(function(){
timer = setInterval(scrollLeft,20);
}).mouseup(clearTimer);
$this.find('.right').click(scrollRight).mousedown(function(){
timer = setInterval(scrollRight,20);
}).mouseup(clearTimer);
});
Thanks Phrogz for this part -- give the image container the white-space: nowrap; and display: inline-block;.
You can calculate the width without having to calculate the width of the children every time but you will need to calculate the width of the children once.
//global variables
var currentWidth = 0;
var slideDistance = 0;
var totalSize = 0;
var dispWidth = (winWidth / 2); //this should get you the middle of the page -- see below
var spacing = 6; //padding or margins around the image element
$(Document).Ready(function() {
$("#Gallery li").each(function () {
totalSize = totalSize + parseFloat($(this).children().attr("width"));// my images are wrapped in a list so I parse each li and get it's child
});
totalSpacing = (($("#Gallery li").siblings().length - 1) * spacing); //handles the margins between pictures
currentWidth = (parseFloat($("#Gallery li.pictureSelected").children().attr("width")) + spacing);
maxLeftScroll = (dispWidth - (totalSize + totalSpacing)); //determines how far left you can scroll
});
function NextImage() {
currentWidth = currentWidth + (parseFloat($("#Gallery li.pictureSelected").next().children().attr("width")) + spacing); //gets the current width plus the width of the next image plus spacing.
slideDistance = (dispWidth - currentWidth)
$("#Gallery").animate({ left: slideDistance }, 700);
}
There is a way to get the browser window with in javascript (jQuery example).
and there is a way to catch the resize event.
var winWidth = $(window).width()
if (winWidth == null) {
winWidth = 50;
}
$(window).resize(function () {
var winNewWidth = $(window).width();
if (winWidth != winNewWidth) {
window.clearTimeout(timerID);
timerID = window.setInterval(function () { resizeWindow(false); }, 100);
}
winWidth = winNewWidth;
});
On my gallery there's actually quite a bit more but this should get you pointed in the right direction.
You need to change your #items from
#items
{
float: left;
background: yellow;
width: 9000px;
}
to
#items {
background: yellow;
}
Then calculate the width very easily with jQuery
// #items width is calculated as the number of child .item elements multiplied by their outerWidth (width+padding+border)
$("#items").width(
$(".item").length * $(".item").outerWidth()
);
and simply declare click events for the #left and #right elements
$("#left").click(function() {
$("#middle").animate({
scrollLeft: "-=50px"
}, 'fast');
});
$("#right").click(function() {
$("#middle").animate({
scrollLeft: "+=50px"
}, 'fast');
});
jsFiddle link here
EDIT
I overlooked that detail about the varying image widths. Here is the correct way to calculate the total width
var totalWidth = 0;
$(".item").each(function(index, value) {
totalWidth += $(value).outerWidth();
});
$("#items").width(totalWidth);

Categories

Resources