Can't get scrollTop() to work in both Chrome & Firefox - javascript

I am having trouble getting the scrollTop() method to work in both Firefox and Chrome. I used $('body, html').scrollTop(); however, it doesn't work in Chrome. Only $('body').scrollTop(); works in Chrome. Any thoughts would be greatly appreciated. Below is my code.
<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
<style type="text/css">
body {
height: 2000px;
}
#light {
display: block;
position: fixed;
top: 50%;
left: 50%;
margin-left: -400px;
margin-top: -200px;
width: 800px;
height: 400px;
background-color: blue;
z-index:1002;
overflow: auto;
}
</style>
</head>
<body>
<div id="light">
</div>
<!-- Used the google jQuery link for ease of use in this example -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(window).scroll(function () {
var offset = $('body, html').scrollTop();
var view = $(window).height();
var total = $(document).height();
var percent = 1-(offset / (total - view));
var widthFactor = 800*percent;
var marginFactor = -(400*percent)
if(percent > 0.33){
$("#light").css({ "width" : widthFactor,
"margin-left" : marginFactor});
};
});
});
</script>
</body>
</html>

Use the document object instead
$(document).scrollTop();

I had this same issue. Best solution for me was to do it on window:
var offset = $(window).scrollTop();
In order for this to work though, your body and html elements can't have a height set to 100%. use min-height instead
EDIT: the HTML element can use height: 100%, however if you need the body to stretch to full height you have to use min-height: 100% instead. Otherwise the scrollTop always returns "0"

Try this, this is scroll on top with animation which is seen more effective
$("html, body").animate({ scrollTop: 0 }, 2000);
Demo Here

You use multiple selector and it will return an array of DOM elements. Calling getter function of this array seems undefined in Chrome (setter functions should work)?
Anyway you can use $('body').scrollTop() || $('html').scrollTop() in you case.
Or just $(document) as mentioned in Justin's answer.

Used this solution:
window.scrollY || window.pageYOffset || document.body.scrollTop + (document.documentElement && document.documentElement.scrollTop || 0)
Supplied in this answer in another thread:
https://stackoverflow.com/a/33462363
You don't need to involve jQuery and it works fine for me.

try this simple javascript code for scroll element using id
document.getElementById("id").scrollTop=0;

Remove height style from the body,html tags. Add an id to the main div under body e.g. #content then use following script. As previously quoted run $(document).scrollTop(); in the browser console and make sure it returns a value not 0.
$('body, html').animate({
scrollTop: $('#content ').offset().top
}, 1000);

Related

I have a Div Element acting as a button but it will only work once

I am 11 years old and I started learning Javascript a couple of months ago, So I am trying to make a page where if you scroll down too much it will take you back to the top so I made a Div element that fills up a large space and onmouseover it will take you back up to the top but if you try it a second time it won't do anything. Please help. Thanks in advance !
I hope my understanding of your problem is right. You have a div and you want to go up each time you scroll too much.
As an example of how to handle the scroll in vanilla JavaScript you can have a look at the document for the onscroll event: https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onscroll.
Here is an example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<style>
#container {
height: 500px;
width: 515px;
overflow: auto;
}
#foo {
height: 1000px;
width: 500px;
background-color: #777;
}
</style>
</head>
<body>
<div id="container">
<div id="foo"></div>
</div>
<script>
var container = document.getElementById('container');
container.addEventListener('scroll', function(event) {
// Get top and left value
var top = container.scrollTop
if (top > 400) {
// Go to the top
container.scrollTop = 0;
}
}, false);
</script>
</body>
</html>
In this example the contained element is bigger that the container so the container becomes scrollable with the overflow: auto; css property.
The scripts applies a onscroll event that checks the scroll value of the container and reset it to 0 when it exceed an arbitrary value (400 in the example).
I hope this has been useful to your work.

Converting Edge/IE JavaScript WheelEvent deltas to native scroll amounts?

In Edge and Internet Explorer, I'm noticing a strange issue with wheel events not equating to their expected scroll amounts. Even though the deltaMode values are reported as DOM_DELTA_PIXEL (0), the number of pixels found in deltaY is greater then the number of pixels actually being scrolled in a small scrollable div.
Take this code for example:
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<style>
#scroller {
width: 200px;
height: 200px;
overflow: scroll;
}
</style>
</head>
<body>
<div id="scroller">
<p>test</p><p>test</p><p>test</p><p>test</p>
<p>test</p><p>test</p><p>test</p><p>test</p>
<p>test</p><p>test</p><p>test</p><p>test</p>
</div>
<script>
(function() {'use strict';
var scroller = document.getElementById('scroller');
scroller.addEventListener('wheel', function(e) {
var scrollY = e.deltaY;
console.log('scrollY:', scrollY);
setTimeout(function() {
console.log('scroller.scrollTop:', scroller.scrollTop);
}, 250);
});
})();
</script>
</body>
</html>
In the console I'm seeing values like this:
scrollY: 101.8499984741211
scroller.scrollTop: 28
In other browsers like Chrome, these values match or are at-least very close.
So the amount actually being scrolled is not the same as what is reported. Why is this, and can we get the correct value?
The reason the values are different is because IE and Edge actually scale the DOM pixels down based on how much of the window the scrolling area being scrolled takes up.
This complicates computing the proper scaling for a browser, and since IE/Edge are the only ones doing it, you will have to use some form of user-agent sniffing.
To get the correct amount of scrolling, you need to multiply the deltaY by (scroller.clientHeight / window.innerHeight) (and likewise with deltaX).
Here is that same sample with these adjustments:
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<style>
#scroller {
width: 200px;
height: 200px;
overflow: scroll;
}
</style>
</head>
<body>
<div id="scroller">
<p>test</p><p>test</p><p>test</p><p>test</p>
<p>test</p><p>test</p><p>test</p><p>test</p>
<p>test</p><p>test</p><p>test</p><p>test</p>
</div>
<script>
(function() {
'use strict';
var scroller = document.getElementById('scroller');
scroller.addEventListener('wheel', function(e) {
var deltaY = e.deltaY;
var scaleY = scroller.clientHeight / window.innerHeight;
var scrollY = deltaY * scaleY;
console.log('scrollY:', scrollY);
setTimeout(function() {
console.log('scroller.scrollTop:', scroller.scrollTop);
}, 250);
});
})();
</script>
</body>
</html>
Which gives the following output in my console:
scrollY: 28.199999577518067
scroller.scrollTop: 28
Note that scrollTop values do not have floating points, so if you want the values to match exactly, you can Math.round them.

JQuery animate margin-top using var not working

I'm using JQuery to have my .wrapper div snap back to its original margin-top after being moved to margin-top. The original margin-top is dependent on browser height. I'm trying to do this by storing the original margin-top value into a variable, and using it for JQuery animate when I want to .wrapper div to snap back later on.
$(document).ready(function() {
//Adjust .wrapper Margin-top to adjust position to 1/4 of Window Broswer Height
var marginWindowSpace = ($(window).height()) / 4;
$(".wrapper").css("margin-top", marginWindowSpace);
var originalMargin = $(".wrapper").css("margin-top").toString();
});
$(".title").click(function() {
$("#results-container").empty();
$(".wrapper").animate({
'margin-top': originalMargin
}, 200);
$(".title-tag, .or, .random-article, .random-article-underline").fadeIn(500);
$("footer").addClass("footer-pos1");
});
QUESTION: Why wont my the animate margin-top accept my variable (where the original margin-top value is stored), even when converted to string? I don't want to use a static value as my margin-top.
If you want to see the app code, it's here. http://codepen.io/myleschuahiock/pen/zqvvNZ
Any help is appreciated! Thanks!
EDIT: I changed the click function to $('.go-back'), but the animate for magin-top should still be the same
Move the whole $(".title").click(function(){}) into the $(document).ready(function(){})
The problem exists because at the time of the initialisation of the $(".title").click(function(){}) originalMargin is not set yet because the document is not ready yet.
Do like this. there are some errors in your animate part.margin-top should be correct as marginTop and your string should convert as int and do like this.I implement as an example.hope this will help to you.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<style type="text/css">
body{
margin: 0;
padding: 0;
}
div.testing{
width: 100px;
height: 100px;
background-color: orange;
margin-top: 100px;
}
div.two{
width: 200px;
height: 200px;
background-color: green;
position:
}
</style>
<body>
<div class="testing"></div>
<br><br>
<h3 class="clk">Click me!</h3>
<div class="two"></div>
<script type="text/javascript">
$(document).ready(function(){
var one = $(".testing").css("margin-top").toString();
var vaL = parseInt(one,10);
$(".clk").click(function(){
$(".two").animate({'marginTop':vaL+'px'},1000);
});
});
</script>
</body>
</html>
note :
var one = $(".testing").css("margin-top").toString();
int this part get the margin-top value as a string.
var vaL = parseInt(one,10);
convert it to an integer.
then the animate part
$(".two").animate({'marginTop':vaL+'px'},1000);

How to start page at center of center or at specific height after load

I want to start page at the center horizontally and vertically when it had loaded (not at top), anyone any suggestions? Or at a specific height if that is possible. Thank you!
You can Do it like this:
$(document).ready(function() {
$(window).scrollTop($(window).height()/2);
$(window).scrollLeft($(window).width()/2);
});
You can change the position to what suit your needs.
Also you can use $(window).scrollTo($(window).width()/2, $(window).height()/2);
not sure what you are asking but have you tried relative coordinates ?
like >>
/*i put this all css selector for canceling all margins, paddings so i can remove default browser prefereces for the same*/
/*border box is just that any size od div is not changed after addinational padding*/
*{margin:0;padding:0;box-sizing:border-box;}
body{
position:absolute;
width:100%;height:100%;
background-color:red;
padding-top:10%;
padding-left:10%;
padding-right:10%;
padding-bottom:10%;
}
centerd{
/*relative dimensions wont work if not display:block;*/
display:block;
width:100%;height:100%;
background-color:blue;
}
<!doctype html>
<html>
<meta charset = "UTF-8" />
<title>Center Content</title>
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<body>
<centerd>
<!--html5 element, you can create your own -->
</centerd>
</body>
</html>
for more information visit : it is cool way to know enough about html, css, javascript etc.
Although not sure if this is what you are looking for:
To center a container (a DIV element say) horizontally, give it a fixed width and auto left and right margins in CSS:
div#container
{ width: 1024px; /* a fixed width container */
border: thin solid green; /* debug, to see */
margin-left: auto;
margin-right: auto;
}
then an anonymous JavaScript function to center a container vertically after load using its margin-top property:
function ()
{ var e = document.getElementById("container");
var eHeight = e.offsetHeight;
var clientHeight = document.documentElement.clientHeight;
var marginTop = 0;
if(clientHeight > eHeight)
{ marginTop = (clientHeight - eHeight) >> 1; // integer divide by 2
}
e.style.marginTop = marginTop + "px";
}
added to the page using jQuery's ready() function for the window, and HTML
<div id="container">
hello this is page content
</div>
centers a container element in the viewport where possible
Old question but I just use:
function Scrolldown() {
window.scroll(250, 400);
}
window.onload = Scrolldown;

javascript code to resize textarea with animation effect on focus gain

I am working with web application and I want to resize textarea with animation effect (smoothly resize) when the textarea gain focus.
I tried following code to resize textarea on focus gain but it does not smoothly resize.
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type='text/javascript'>
function abc()
{
$('#txt').attr('rows',15);
}
</script>
</head>
<body>
<textarea id='txt' rows="4" onfocus='abc();' cols="50">
this is testing of textrea
</textarea>
</body>
</html>
If you dont need support for IE9 and older versions, pure CSS can solve your issue.
#txt {
height:80px;
transition: all 2s;
-webkit-transition: all 2s; /* Safari */
}
#txt:focus {
height:300px;
}
http://jsfiddle.net/MHC8T/
try this:
function abc()
{
$('#txt').animate({'height':"+=100px"}, 400);
}
you can switch the height to whatever you want.. the +=100 is relative and will add 100px to the height of the textarea
also as an external event handler
$("#txt").bind("focusin",function abc(){
$('#txt').animate({'height':"+=100px"}, 400);
});
hope that helps
Try this...
$('#txt').focus(function() {
$('#txt').animate({
width: 500,
height: 200
}, 1000);
});
$('#txt').blur(function() {
$('#txt').animate({
width: 160,
height: 48
}, 1000);
});
Example: http://jsfiddle.net/FMp4a/
For more information about the $.animate() see this page in the jQuery API documentation...
http://api.jquery.com/animate/
Try this
$('textarea.expand').focus(function ()
{
$(this).animate({ height: "4em" }, 500);
});
for more information check
"http://jsfiddle.net/Y3rMM/"
I came up with a different answer, this way it auto adjusts to the size of the amount of content in the textarea instead of a fixed height
$('#txt').focus (function() {
$(this).animate({
height: $(this)[0].scrollHeight
}, 200);
});
$('#txt').blur(function() {
$('#txt').animate({
height: 40
}, 200);
});
Example: http://jsfiddle.net/FMp4a/10/

Categories

Resources