I'm using jQuery TouchSwipe to make some horizontal, scrollable divs on a mobile site. I've got it set up so that the div scrolls left or right, depending on how you swipe. My problem lies within after you stop swiping and go to swipe again. When you go to swipe, the div goes back to the beginning. Obviously I want the div to stay where it's at and scroll from that position. Here is what I have so far.
$('#table_set').swipe({
swipeStatus:swipe1, allowPageScroll:'horizontal'
});
function swipe1(event, phase, direction, distance, duration){
if(direction == 'left'{
$(this).scrollLeft(distance);
}else{
$(this).scrollLeft('-' + distance);
}
}
I understand why it's going to the beginning of the div. Every time that you touch, duration equals 0. I just don't know what the next steps are. Any help would be amazing. Thanks!
I've created a demo of the swiping. I think the issue with going to the beginning of the div was because direction returns null if there was just a click and no swiping.
I've avoided this by exiting the callback if direction is null.
I'm not sure why you need the swiping at all because the scrolling works with-out touchSwipe.
Please finde the demo below and here at jsFiddle.
var IMAGECOUNT = 10;
var url = 'http://lorempixel.com/400/200';
var imgArr = [];
var loadCounter = 10;
var decCounter = function(){
loadCounter--;
if (!loadCounter) $("#table_set").trigger('allImgLoaded');
};
$(function() {
var $table = $('#table_set');
var img;
//init table set with dummy images
for(var i=0; i< IMAGECOUNT; i++){
imgArr[i] = new Image();
imgArr[i].src = url + '?' + (new Date()).getTime(); // add time to avoid caching
imgArr[i].onload = decCounter;
}
$("#table_set").on('allImgLoaded', function() {
//console.log(imgArr);
$table.append(imgArr);
});
});
$('#table_set').swipe({
swipeStatus:swipe1, allowPageScroll:'horizontal'
});
function swipe1(event, phase, direction, distance, duration){
console.log('swiped!', direction, distance, duration);
if ( direction === null ) return; // no swipe
var curPos = $(this).scrollLeft();
var newPos = curPos;
if(direction == 'left'){
newPos += distance;
$(this).scrollLeft(newPos);
}else{
newPos -= distance;
$(this).scrollLeft(newPos);
}
}
#table_set {
height: 210px;
width: 100%;
overflow-x: scroll;
overflow-y: hidden;
white-space: nowrap;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.touchswipe/1.6.4/jquery.touchSwipe.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="table_set">
</div>
Related
I have this code:
function scroll() {
shouldScroll = chat.clientHeight === chat.scrollHeight;
if (!shouldScroll) {
scrollToBottom();
}
}
function scrollToBottom() {
chat.scrollTop = chat.scrollHeight;
}
scrollToBottom();
setInterval(scroll, 100);
In this code I have an automatically scroll but, When I want to see the whole conversation, he does not let me go up so I can read the conversations. It just keeps me down.
How can i fix this?
Thanks
Check if user has scrolled to another position using scrollTop or is near to the bottom by comparing to an offset:
var offset = 50; // if user is 50px far from bottom
var shouldScroll = false;
if (chat.scrollHeight - chat.scrollTop) < offset){
shouldScroll = true;
}
I'm trying to make one vertical line what goes from start point (defined by
CSS) to end point (which I didn't define yet).
The idea is; the user scrolls and the line keeps like sticky and/or grows its height until the end point.
But I don't know which logic I should apply.
(Not-working) example: https://jsfiddle.net/uzegqn7f/
That line should go, for example, to the second image's top following the user's scroll position.
<div class="vertical-line line-1"></div>
<img src="https://dummyimage.com/900x300/000000/fff.jpg" alt="" class="line-1-start">
<div class="content"></div>
<img src="https://dummyimage.com/900x300/000000/fff.jpg" alt="" class="line-1-end">
.content {
height:1000px;
}
img {
max-width:100%;
height:auto;
}
.vertical-line {
display: block;
position: absolute;
background: #ee403d;
width: 4px;
height: 10px;
z-index: 999;
}
.line-1 {
margin-left:10%;
margin-top:100px;
}
var distance = $('.line-1-end').offset().top - $('.line-1-start').offset().top;
function line_animation(element,distance) {
$(window).scroll(function(){
element.css("height", distance+"px");
});
}
$(document).on('load resize', function() {
var line1 = $(".line-1");
line_animation(line1,distance);
});
NOTE:
The distance between the elements is not always the same, may vary in responsive.
Try this (comments in code):
var start = $('.line-1-start').offset().top, // get where line starts
end = $('.line-1-end').offset().top, // get where line ends
line = $('#line');
drawLine($(window).scrollTop()); // draw initial line
$(window).scroll(function(){
drawLine($(this).scrollTop()); // draw line on scroll
});
$(document).on('resize', function() { // reset top and bottom and redraw line on window resize
start = $('.line-1-start').offset().top;
end = $('.line-1-end').offset().top;
drawLine($(window).scrollTop());
});
function drawLine(currentPosition) {
if (currentPosition >= start && currentPosition <= end) {
var distance = currentPosition - start;
line.css("height", distance+"px");
} else {
line.css("height", 0);
}
}
Updated fiddle
i didn't get to finish it but it's nearly there if it helps. It dynamically will figure out the height and start/end positions, you might be able to finish it off, it's not calculating the end position quite right, bit of tweaking and it'll be ok though. Checkout the JSfiddle;
https://jsfiddle.net/x4jhLohs/2/
$(document).on('ready', function() {
$(window).scroll(function(){
handleVerticalLine();
});
function handleVerticalLine() {
// Loop through and grab all our Vertical Line Containers, each one will have a Start and an End selector.
$('.vertical-line-container').each(function() {
// Grab our start and end elements.
var $startElement = $( $( this ).data( 'line-start-selector' ) );
var $endElement = $( $( this ).data( 'line-end-selector' ) );
var $verticalLine = $( this ).find( $( '.vertical-line' ) );
if( $startElement.length && $endElement.length && $verticalLine.length ) {
var startElementTopOffsfet = $startElement.offset().top;
var endElementTopOffsfet = $endElement.offset().top + $endElement.height();
var startElementVerticalLineBegin = startElementTopOffsfet;
var endElementVerticalLineBegin = endElementTopOffsfet;
$verticalLine.css( 'top', startElementTopOffsfet + $startElement.height() );
var verticalLinePercentage = startElementVerticalLineBegin / endElementVerticalLineBegin * 100;
verticalLinePercentage += $(window).scrollTop();
$verticalLine.css('height', verticalLinePercentage )
}
});
}
});
I have an absolutely positioned div that uses the jQuery .animate function to move horizontally from the right to left of the screen.
My problem is that once the div reaches the far left side, it continues and eventually disappears from the screen. How do you make it so that once the div reaches the left side, it will reverse and start going to the right? (and then vice versa so that the right side won't continue going right, but goes left again once it reaches the end)
HTML:
<div class="container">
<div class="block"></div>
</div>
CSS:
.block {
float:right;
position:absolute;
right:100px;
width:100px;
height:100px;
background:red;
}
jQuery:
$('.block').click(function() {
$(this).animate(
{"right": "+=100px"},"slow");
});
Here is my JSFiddle: https://jsfiddle.net/ebkc9dzL/
Thank you I really appreciate the help!
may be you should try like this:
$('.block').click(function() {
var leftPosition = $(this).position();
if (leftPosition.left > 100) {
$(this).animate({"right": "+=100px"},"slow");
} else {
$(this).animate({"right": "-=100px"},"slow");
}
});
when the element is close to the border the if..else part of the code will reverse the direction.
Here is a fiddle, try to click on the red box to get an idea on how it works:
https://jsfiddle.net/dimitrioglo/ebkc9dzL/14/
Working fiddle: https://jsfiddle.net/ebkc9dzL/19/
You need to have a variable outside the click function that will tell you the direction of the animation, so that once inside the click function you can calculate the location of the animated object using getBoundingClientRect() (mdn reference).
Then, if object is moving left and its left distance is less than its own width, you need to move it only enough so that it comes to the edge. If it's AT the edge (left is zero), you need to change the direction.
If it's moving right and its right distance is less than its own width, you need to move it only enough (calculated by window.innerWidth - 100, since 100 is width of your object) so that it comes to the edge. If it's AT the right edge, you need to change direction.
Changing direction in object you pass to jQuery's animate function is a simple matter of adding or subtracting from its "right" attribute.
var direction = "+";
$('.block').click(function() {
var obj = {},
distance = 100,
rect = this.getBoundingClientRect();
if(direction=="+"){
if(rect.left>0 && rect.left < 100)
distance = rect.left;
else if(rect.left<=0)
direction = "-";
}
else {
if(rect.right >(window.innerWidth-100) && rect.right+1<window.innerWidth)
distance = (window.innerWidth-rect.right);
else if(rect.right+1 >=window.innerWidth){
direction = "+";
}
}
obj = {"right": direction+"="+distance.toString()+"px"}
$(this).animate(obj,"slow");
});
Here you go: jsFiddle.
The new javascript is as follows:
var goLeft = true;
$('.block').click(function() {
var animateDist = 100;
var distLeft = $(this).position().left;
var distRight = window.innerWidth - distLeft;
if (goLeft) {
if (distLeft < 100) {
animateDist = "+="+distLeft+"px";
$(this).animate(
{"right": animateDist},"slow"
);
goLeft = false;
} else {
$(this).animate(
{"right": "+=100px"},"slow"
);
}
} else {
if (distRight < 100) {
animateDist = "-="+distRight+"px";
$(this).animate(
{"right": animateDist},"slow"
);
goLeft = true;
} else {
$(this).animate(
{"right": "-=100px"},"slow"
);
}
}
});
This isn't perfect, you need to adjust your internal window width to match the parent container, but this is enough to get you in the right direction.
Good luck!
Try this code:
var sign = [ "+" , "-" ];
var signPosition = 0;
var maxOffset = $(".block").offset().left;
$('.block').click(function() {
if ($(this).offset().left < 100) {
signPosition = 1;
} else if ($(this).offset().left == maxOffset) {
signPosition = 0;
}
$(this).animate(
{"right": sign[signPosition] + "=100px"},"slow");
});
The variable sign is the array that contains the directions in which the element might move, the variable signPosition contains the position of the direction currently in use, the variable maxOffset contains the starting position.
Hope this will help you.
I have created a parallax scroll, which seem to be working fine in firefox however in the chrome browser there's a slight jump on the body text when scrolling. click here scroll to the about section. I am not sure if t this is a css or JS issue.. below is a snippet i have incorporated into my parallax function
Does anyone know how i an fix this issue?
$(document).ready(function(){
// Cache the Window object
$window = $(window);
// Cache the Y offset and the speed of each sprite
$('[data-type]').each(function() {
$(this).data('offsetY', parseInt($(this).attr('data-offsetY')));
$(this).data('Xposition', $(this).attr('data-Xposition'));
$(this).data('speed', $(this).attr('data-speed'));
});
// For each element that has a data-type attribute
$('[data-type="background"]').each(function(){
// Store some variables based on where we are
var $self = $(this),
offsetCoords = $self.offset(),
topOffset = offsetCoords.top;
// When the window is scrolled...
$(window).scroll(function() {
// If this section is in view
if ( ($window.scrollTop() + $window.height()) > (topOffset) &&
( (topOffset + $self.height()) > $window.scrollTop() ) ) {
// Scroll the background at var speed
// the yPos is a negative value because we're scrolling it UP!
var yPos = -($window.scrollTop() / $self.data('speed'));
// If this element has a Y offset then add it on
if ($self.data('offsetY')) {
yPos += $self.data('offsetY');
}
// Put together our final background position
var coords = '50% '+ yPos + 'px';
// Move the background
$self.css({ backgroundPosition: coords });
$('[data-type="scroll-text"]', $self).each(function() {
var $text= $(this);
var pos = ($window.scrollTop()/10) * $text.data('speed');
var curP = $text.css('margin-top');
var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
if(is_chrome) {
$text.animate({
paddingTop: pos,
}, 200, 'linear', function() {
// Animation complete.
});
} else {
$text.css('padding-top', pos);
}
});
}; // in view
}); // window scroll
}); // each data-type
}); // document ready
Some suggestions:
1.) Use position: fixed to avoid any jitter, as you'll be taking the element out of the document flow. You can then position it using z-index.
2.) Cache as much as you can to ease processing time.
3.) Math.round may not be necessary, but try adding this CSS to your moving areas: -webkit-transform: translate3d(0,0,0); This will force hardware acceleration in Chrome, which may ease some of the jittering. (It looked smoother on my screen when I added this with Inspector, but it didn't get rid of the jumpiness with the scroll wheel.) Note: Don't do this on your entire document (e.g. body tag), as it might cause some issues with your current layout. (Your navigation bar didn't stick to the top of the window, for instance.)
4.) If you have any animations running as part of your parallax logic (tweening the margin into place or something along those lines), remove it - that would probably cause the jump you see.
Hope this helps. Best of luck.
I see the same jittering in FireFox and Chrome (Mac). Looking at your containers, one thing that's glaring at me is the pixel position that's being calculated/used.
Chrome: <div id="about-title" style="margin-top: 1562.3999999999999px;">
FireFox: <div id="about-title" style="margin-top: 1562.4px;">
Browsers aren't going to allow content to sit at 1/2 pixel, let alone 0.3999999 of a pixel. I think it's moving it, and trying to calculate whether to round up or round down. It jitters because it's calculating with every click of your mouse wheel.
Thus, I'd try adding Math.round() to your positions so that the containers are never being left in limbo.
Take a look at the code here: http://webdesigntutsplus.s3.amazonaws.com/tuts/338_parallax/src/index.html
Firebug some of the elements, and you'll see that their only fraction of a pixel is '0.5'. Most of them (the bulk) go to round number values.
You are going to have to change the way that the scrolling works (i.e. change how the spacing is computed), but this can be fixed by adding the position:fixed CSS element to the page elements that are scrolling. The problem is coming from the time that it takes for the JavaScript to process and then render.
For example, on your page you would set each of the <div> tags containing text to have a fixed position and then use the JavaScript/JQuery function to update the top: CSS element. This should make the page scroll smoothly.
Have you tried adding the preventdefault inside the scroll function?
$(window).scroll(function(e) {
e.preventDefault();
// rest of your code
}
In a previous question I created a fairly good parallax scrolling implementation. Jquery Parallax Scrolling effect - Multi directional You might find it useful.
Here's the JSFiddle http://jsfiddle.net/9R4hZ/40/ use the up/down arrows or scroll wheel.
Using padding and margin for the positioning are probably why you're experiencing rendering issues. While my code uses scroll or keyboard input for the effect you can loop the relavent portion and check the $moving variable until you reach the desired element on screen.
function parallaxScroll(scroll) {
// current moving object
var ml = $moving.position().left;
var mt = $moving.position().top;
var mw = $moving.width();
var mh = $moving.height();
// calc velocity
var fromTop = false;
var fromBottom = false;
var fromLeft = false;
var fromRight = false;
var vLeft = 0;
var vTop = 0;
if($moving.hasClass('from-top')) {
vTop = scroll;
fromTop = true;
} else if($moving.hasClass('from-bottom')) {
vTop = -scroll;
fromBottom = true;
} else if($moving.hasClass('from-left')) {
vLeft = scroll;
fromLeft = true;
} else if($moving.hasClass('from-right')) {
vLeft = -scroll;
fromRight = true;
}
// calc new position
var newLeft = ml + vLeft;
var newTop = mt + vTop;
// check bounds
var finished = false;
if(fromTop && (newTop > t || newTop + mh < t)) {
finished = true;
newTop = (scroll > 0 ? t : t - mh);
} else if(fromBottom && (newTop < t || newTop > h)) {
finished = true;
newTop = (scroll > 0 ? t : t + h);
} else if(fromLeft && (newLeft > l || newLeft + mw < l)) {
finished = true;
newLeft = (scroll > 0 ? l : l - mw);
} else if(fromRight && (newLeft < l || newLeft > w)) {
finished = true;
newLeft = (scroll > 0 ? l : l + w);
}
// set new position
$moving.css('left', newLeft);
$moving.css('top', newTop);
// if finished change moving object
if(finished) {
// get the next moving
if(scroll > 0) {
$moving = $moving.next('.parallax');
if($moving.length == 0)
$moving = $view.find('.parallax:last');
} else {
$moving = $moving.prev('.parallax');
if($moving.length == 0)
$moving = $view.find('.parallax:first');
}
}
// for debug
$('#direction').text(scroll + " " + l + "/" + t + " " + ml + "/" + mt + " " + finished + " " + $moving.text());
}
May not be related to your specifics, but I had a jumpy parallax scrolling problem, I was able to solve it adding the following CSS for the fixed portions of the page:
#supports (background-attachment: fixed)
{
.fixed-background
{
background-attachment: fixed;
}
}
Not sure of all the specifics, but found at Alternate Fixed & Scroll Backgrounds
I'm wondering if there is a simple way to make use of JavaScript (probably jQuery too?) in order to make the contents of a fixed-height div element scroll infinitely up and down (top, bottom, top, bottom, etc) when the page loads and without any user input or manipulation?
Thanks ahead of time, any input is greatly appreciated as I am hardly mediocre with JavaScript.
With pure js you can do something like this:
var scroller = document.getElementById('scroller');
var delta = 15;
var lastSc;
//console.log(scroller.scrollTop, scrollHeight);
setInterval(function(){
var sc = scroller.scrollTop + delta;
scroller.scrollTop = sc;
if (scroller.scrollTop === lastSc){
delta = delta*(-1);
}
lastSc = scroller.scrollTop;
}, 10);
Here is demo
Edit: updated demo
Here is something I've just written, using jQuery:
var speed = 100; //smaller means faster
var offset = 5; //bigger means more text will be "scrolled" every time
function ScrollMyDiv() {
var myDiv = $("#MyDiv");
var direction = myDiv.attr("scroll_dir") || "";
var lastScrollTop = parseInt(myDiv.attr("last_scroll_top") || "0", 10);
if (direction.length === 0) {
myDiv.attr("scroll_dir", "down");
direction = "down";
}
var top = myDiv.scrollTop();
myDiv.attr("last_scroll_top", top + "")
if (direction === "down") {
if (top > 0 && lastScrollTop === top)
myDiv.attr("scroll_dir", "up");
top += offset;
} else {
if (top <= 0)
myDiv.attr("scroll_dir", "down");
top -= offset;
}
myDiv.scrollTop(top);
window.setTimeout(ScrollMyDiv, speed);
}
$(document).ready(function() {
ScrollMyDiv();
});
Live test case: http://jsfiddle.net/HmfNJ/1/
Basically, it will start by scrolling down (adding to the scrollTop) then when it identify it reached the bottom by seeing the scrollTop remains the same, it will change direction and start scroll up.
Thanks for the replies but I found my answer elsewhere. Here's what I ended up using: http://jsbin.com/onohan/3/edit#preview
It had a couple of small problems but I at least knew enough about basic JavaScript to fix them. Hopefully this will benefit someone in the future. :)
To get a smooth transition for scroll to bottom this is VanillaJS code that works well with me
var delta = 0.6, interval;
interval = setInterval(function(){
window.scrollBy(0, delta);
}, 20);
To clear the Interval you can run
clearInterval(interval);