I have problem when writing around 60 lines here in fiddle
then it start to scroll up !.
what im doing wrong there ? thanks.
I want to always stay scrolled down at bottom.
$chat = $('#chatarea');
$submit = $('#submit');
$input = $('#text')
ENTER = 13;
var addMessage = function(message) {
// create message element
$msg = $('<div>', {class: 'message hidden-message', text: message})
if($input.val().length > 0){
// append element
$chat.append($msg) ;
}
else
{
return false;}
$msg.hide().removeClass('hidden-message') ;
$msg.slideDown(function(){
// animate scroll to bottom
$chat.animate({ scrollTop: $chat.height() })
});
};
$input.on('keydown', function(e){
if(e.keyCode === 13 && $input.val().length < 1 ){
return false;
}
});
$input.on('keyup', function(e){
if(e.keyCode == 13 && $input.val().length > 1 ) {addMessage($input.val());
$input.val('');
}
else if(e.keyCode == 13 && $input.val().length == 1){
$input.val('');
e.preventDefault();
return false;}else{}
});
$submit.on('click', function(){
if($input.val().length > 1) {
addMessage($input[0].value);
$input.val('');
}
});
The Problem:
.holder has a height of 1000px and .chatarea inside it has a height of 90%, so in your script $chat.height() always returns 900, so after 60 lines or so, whenever there's an input it scrolls to 900px and stays there.
Solution:
Use this:
$chat.animate({ scrollTop: $chat.prop("scrollHeight") - $chat.height() })
Or a faster animation:
$chat.animate({ scrollTop: $chat.prop("scrollHeight") - $chat.height() }, 25)
Instead of this:
$chat.animate({ scrollTop: $chat.height() })
Demo http://jsfiddle.net/MYPgE/8/
Problem is within $msg.slideDown function, just comment out $chat.animate({ scrollTop: $chat.height() }) and put this code into the $submit.on click function
$(function () {
$("#chatarea").animate({
scrollTop: $('#chatarea').get(0).scrollHeight}, 1000);});
}
fiddle: http://jsfiddle.net/MYPgE/6/
Related
I have a script which has a button to scroll the site but I need it to scroll automatically on page load. I need the script to scroll exactly like shown below, except the button. Could anyone change it for me? I'm new to javascript, thanks..
function scroll(element, speed) {
var distance = element.height();
var duration = distance / speed;
element.animate({scrollTop: distance}, duration, 'linear');
}
$(document).ready(function() {
$("button").click(function() {
scroll($("html, body"), 0.015); // Set as required
});
});
Call the scroll function in on window load, this will scroll the page on load finished.
$(window).on('load', function(){
scroll($("html, body"), 0.015); // Set as required
})
You can try the below JavaScript code
var div = $('.autoscroller');
$('.autoscroller').bind('scroll mousedown wheel DOMMouseScroll mousewheel keyup', function(evt) {
if (evt.type === 'DOMMouseScroll' || evt.type === 'keyup' || evt.type === 'mousewheel') {
}
if (evt.originalEvent.detail < 0 || (evt.originalEvent.wheelDelta && evt.originalEvent.wheelDelta > 0)) {
clearInterval(autoscroller);
}
if (evt.originalEvent.detail > 0 || (evt.originalEvent.wheelDelta && evt.originalEvent.wheelDelta < 0)) {
clearInterval(autoscroller);
}
});
var autoscroller = setInterval(function(){
var pos = div.scrollTop();
if ((div.scrollTop() + div.innerHeight()) >= div[0].scrollHeight) {
clearInterval(autoscroller);
}
div.scrollTop(pos + 1);
}, 50);
here on the load of the page. The text are auto-scrolled upto the end of the page.
This is my code: Fiddle
countEach()
$(window).on('scroll', function(e) {
countEach()
})
function countEach() {
$('.count').each(function() {
if (showOnScreen(this) && $(this).attr('show') != 'false') {
console.log($(this).text())
console.log($(this).attr('show'))
$(this).attr('show', 'false')
numberAnimate(this)
} else if (!showOnScreen(this)) {
$(this).attr('show', 'true')
}
})
}
function showOnScreen(target) {
if ($(window).scrollTop() + $(window).height() >= $(target).offset().top)
return true;
else
return false;
}
function numberAnimate(target) {
var $this = $(target);
jQuery({
Counter: 0
}).animate({
Counter: $this.text()
}, {
duration: 1000,
easing: 'swing',
step: function() {
$this.text(this.Counter.toFixed(1));
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="count">5.6</span>
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
<p>Scroll up and then scroll down again</p>
<span class="count">5.6</span>
The problem is, the increasing number animation will run again, if i scroll up and scroll down again. What is the thing that i need to change to stop it? I tried a lot of things, but i am not good at Javascript.
You need to declare a global var as stopNow = 2 so your animation can only run twice and decrement it when animation runs.
var stopNow = 2;
Update the countEach function as follows
function countEach() {
$('.count').each(function() {
//also check stopNow != 0
if (showOnScreen(this) && $(this).attr('show') != 'false' && stopNow != 0) {
console.log($(this).text())
console.log($(this).attr('show'))
$(this).attr('show', 'false')
numberAnimate(this)
stopNow = stopNow - 1; //decrement stopNow
} else if (!showOnScreen(this)) {
$(this).attr('show', 'true')
}
})
}
Here's your updated working fiddle - https://jsfiddle.net/6w8ubh5y/7/
Use a global variable. Set it to false at the beginning. In the scroll event, check it and if it is still false, run the countEach() function then change the variable to true. Like this:
var stop = false;
countEach();
$(window).on('scroll', function(e) {
if(!stop){
countEach();
stop = true;
}
})
Change the event binding code from:
$(window).on('scroll', function(e) {
countEach()
})
to
$(window).on('scroll', countEach);
and change countEach function like this...
function countEach() {
$('.count').each(function() {
...
});
$(window).off('scroll', countEach); // add this line
}
hello i have a little Problem with Jquery toggeling.
when I scroll to the div toggling don't wanna stop and play in a while.
I don't no how I can trigger only one time the toggling on the div entrance and to set it back on the div exit ( from the top).
there is my code
$(document).ready(function(){
$(".fa-home-mini").css("display", "none");
$('.fa-home-mini').click(function () {
if($('.navi').is(':visible')){
$('.navi').toggle('slide', {
direction: 'left'
}, 1000);
}
else{
$('.navi').toggle('slide', {
direction: 'left'
}, 1000);
}
});
$(window).scroll( function() {
var value = $(this).scrollTop();
if ( value > 480 ){
$(".fa-home-mini").css("display", "block");
$('.fa-home-mini').trigger('click');
}
else
{
$(".fa-home-mini").css("display", "none");
$(".navi").css("display", "block");
}
});
});
You can use off method inside the if block like below:
if ( value > 480 ){
$(".fa-home-mini").css("display", "block");
$('.fa-home-mini').trigger('click');
$(window).off('scroll')
}
Another approach will be:
var flag = false;
$(window).scroll( function() {
var value = $(this).scrollTop();
if ( value > 480 ){
if(!flag) {
$(".fa-home-mini").css("display", "block");
$('.fa-home-mini').trigger('click');
flag = true;
}
}
else
{
$(".fa-home-mini").css("display", "none");
$(".navi").css("display", "block");
}
});
I'm using a smooth scroll script for a site I'm currently working on, and I've got a really annoying problem what I've experienced before with the same script. It works nice and smoothly but when I click on one of the navigation points what should lead me to the div(or a) I'm trying to target, it shows me the targeting area for like 0.1 seconds, and then it starts to scroll. It doesn't happen everytime, but often enough to be annoying. How could I prevent this? Here is the script I'm talking about:
$(window).load(function(){
$(".contactLink").click(function(){
if ($("#contactForm").is(":hidden")){
$("#contactForm").slideDown("slow");
}
else{
$("#contactForm").slideUp("slow");
}
});
});
function closeForm(){
$("#messageSent").show("slow");
setTimeout('$("#messageSent").hide();$("#contactForm").slideUp("slow")', 2000);
}
$(window).load(function() {
function filterPath(string) {
return string
.replace(/^\//,'')
.replace(/(index|default).[a-zA-Z]{3,4}$/,'')
.replace(/\/$/,'');
}
$('a[href*=#]').each(function() {
if ( filterPath(location.pathname) == filterPath(this.pathname)
&& location.hostname == this.hostname
&& this.hash.replace(/#/,'') ) {
var $targetId = $(this.hash), $targetAnchor = $('[name=' + this.hash.slice(1) +']');
var $target = $targetId.length ? $targetId : $targetAnchor.length ? $targetAnchor : true;
if ($target) {
var targetOffset = $target.offset().top - 110;
$(this).click(function() {
$('html, body').animate({scrollTop: targetOffset}, 1400);
var d = document.createElement("div");
d.style.height = "101%";
d.style.overflow = "hidden";
document.body.appendChild(d);
window.scrollTo(0,scrollToM);
setTimeout(function() {
d.parentNode.removeChild(d);
}, 10);
return false;
});
}
}
});
});
setTimeout(function() {
d.parentNode.removeChild(d);
}, 10);
return false;
});
move the return false out of the setTimeOut
Found the solution:
$(this).click(function(e) {
e.preventDefault();
Now it rolls fine.
I have a page that I'm building and I would like to make it that when I scroll (up or down) the page scrolls to the next div (each div is 100% the height of the window). And gets "fixed" there until you scroll again. An example of what I'm trying to accomplish can be seen here:
http://testdays.hondamoto.ch/
You will notice that when you scroll down, it automatically moves you to the next "div".
What I've tried:
Using the jQuery .scroll event combined with:
function updatePosition() {
if(canScroll) {
var pageName;
canScroll = false;
var st = $(window).scrollTop();
if (st > lastScrollTop){
// downscroll code
if(pageNumber < 7) {
pageNumber++;
}
pageName = '#' + getPageToScrollTo().id;
$('body').animate({ scrollTop: $(pageName).offset().top }, 2000, function() {
canScroll = true;
});
} else {
// upscroll code
if(pageNumber > 0) {
pageNumber--;
}
pageName = '#' + getPageToScrollTo().id;
$('body').animate({ scrollTop: $(pageName).offset().top }, 2000, function() {
canScroll = true;
});
}
lastScrollTop = st;
}
}
But the scroll event was getting called when the page was scrolling (animating), AND when the user scrolled. I only need it to be called when the user scrolls.
Then I added:
var throttled = _.throttle(updatePosition, 3000);
$(document).scroll(throttled);
From the Underscore.js library - but it still did the same.
Finally, I browsed here a bit and found:
Call Scroll only when user scrolls, not when animate()
But I was unable to implement that solution. Is there anyone that knows of any libraries or methods to get this working?
EDIT:
Solution based on Basic's answer:
function nextPage() {
canScroll = false;
if(pageNumber < 7) {
pageNumber++;
}
pageName = getPageToScrollTo();
$('html, body').stop().animate({ scrollTop: $(pageName).offset().top }, 1000, function() {
canScroll = true;
});
}
function prevPage() {
canScroll = false;
if(pageNumber > 0) {
pageNumber--;
}
pageName = getPageToScrollTo();
$('html, body').stop().animate({ scrollTop: $(pageName).offset().top }, 1000, function() {
canScroll = true;
});
}
//--Bind mouseWheel
$(window).on(mousewheelevt, function(event) {
event.preventDefault();
if(canScroll){
if(mousewheelevt == "mousewheel") {
if (event.originalEvent.wheelDelta >= 0) {
prevPage();
} else {
nextPage();
}
} else if(mousewheelevt == "DOMMouseScroll") {
if (event.originalEvent.detail >= 0) {
nextPage();
} else {
prevPage();
}
}
}
});
Ok...
The relevant code for the Honda site can be found in http://testdays.hondamoto.ch/js/script_2.js. It seems to be doing some calculations to locate the top of the div then scroll to it. There are handlers for different types of scrolling.
Specifically, the movement is handled by function navigation(target)
the key bits is here...
$('html,body').stop().animate({
scrollTop: $(target).offset().top + newMargin
}, 1000,'easeInOutExpo',function(){
//Lots of "page"-specific stuff
}
});
There are handlers for the scroll types...
$('body').bind('touchstart', function(event) {
//if(currentNav!=3){
// jQuery clones events, but only with a limited number of properties for perf reasons. Need the original event to get 'touches'
var e = event.originalEvent;
scrollStartPos = e.touches[0].pageY;
//}
});
//--Bind mouseWheel
$('*').bind('mousewheel', function(event, delta) {
event.preventDefault();
//trace('class : '+$(this).attr('class') + ' id : '+$(this).attr('id'));
if(!busy && !lockScrollModel && !lockScrollMap){
if(delta<0){
nextPage();
}else{
prevPage();
}
}
});
You'll note that the navigate() function sets a busy flag which is unset when scrolling completes - which is how it suppresses all new scroll events during a scroll. Try changing the direction of scroll while the page is already scrolling and you'll notice user input is being ignored too.