jQuery - scrollTop command not scrolling - javascript

I'm displaying some images on a webpage and I want it to be scrolled all the way to the bottom as soon as the page loads, then fade the image in. This is what my code looks like thus far:
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function(){
// fade in initial image
$("#lower").fadeIn(3000);
$("#lower").css("display", "block;");
// show only initial image at mid-page
var margin = ( $(window).height() - $("#lower").height() ) * (0.5);
$("#lower").css("margin-top", margin);
// set scroll position to bottom of page
$(document).scrollTop( $(document).height() );
});
</script>
and my html looks like this:
<body>
<div id="view">
<img id="upper" src="pages/2.gif">
<img id="lower" src="pages/1.gif">
</div>
</body>
(#upper has opacity 0 and I plan to fade it in later, when the user scrolls up to the image)
the problem I'm having is that the page doesn't scroll all the way to the bottom on load. Ive tried a number of things including changing the selector for the .scrollTop function to body and/ or html tag as well as document or window. I even tried overshooting the scrollTop value excessively but to no avail.
Can anyone tell me me why The page is not scrolling all the way to the bottom upon load?
[EDIT]
Sorry sorry, sloppy code. Finals week and little sleep. Heres a no-typo version of the same thing with the same problem. I even overshot the scrollTop parameter here, but the result is the same.
An observation: scroll location persists after refresh. Could this have anything to do with the obstinate scroll position here?

You have a typo here:
var margin = ($(window).hieght() - $("#lower").height())/2;
//----------------------^^^^^^^---a spelling typo
which should be:
var margin = ($(window).height() - $("#lower").height())/2;
Because of this the script execution stops and it never goes to the line where you have done the scrollTop. so all in all it gets stopped at an error and does not go further for execution.
Also i want to add that this is not a correct way of doing:
$("#lower").attr("style", "display: block;")
instead you can use .css() method:
$("#lower").css("display", "block");
or with simple .show(), fadeIn(), .toggle('show') etc. too.

Related

Keep scroll position inside div after reload php file with ajax

I have a div with it's own scroll bar which is being reloaded by AJAX (php file). When I scroll inside this div and reload it, the inner scrollbar gets sent back to the top. I would like for the scroll bar to remain at the position where I originally scrolled to.
<style>
#div2 {
height: 400px;
width: 100%;
overflow-y:scroll;
}
</style>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
setInterval(function () {
$('#div1').load('shownic8.php');
},7000);
</script>
<div id="div1">
</div>
Here is the code from "shownic8.php" file
<div id="div2">
...
</div>
Can you help me keep the position of my scroll bar? Thank you very much.
Check https://api.jquery.com/scrolltop/
Before .load() store current scroll position:
var pos = $('#your-container').scrollTop();
Use .load() callback (http://api.jquery.com/load/) to restore scroll position:
$('#your-container').scrollTop(pos);
Using your code:
setInterval(function () {
var scrollTarget = $('#div1');
var pos = scrollTarget.scrollTop();
scrollTarget.load('shownic8.php', function() {
$('#div1').scrollTop(pos);
});
},7000);
You can either use DOM element's scrollTop property or jQuery function of the same name.
But I don't advice you to do so because saving and restoring scroll position you couldn't avoid a slight blinking effect every time you reload contents.
So, instead, I would recommend to update items that actually change instead of reloading the whole contents, so the scrollTop property gets never changed.
Of course, (to do it the right way) it implies modifying your shownic8.php page (or implementing another different route instead) to return some structured data and use them to fill or update your div contents.
On the other hand, you can try another, slightly dirty, approach to hide that blinking efect (replacing it by a less obvious side effect). That is:
Instead of loading your contents directly into #div1 element, create a new div inside it (appending through .append() or .appendTo()) and load into it.
After that (at least in reloading operations), remove previous contents so that new content climbs up to the top position (and not altering scroll position).
Example: (untested)
setInterval(function () {
var prevContents = $("#div1>*");
$('<div></div>')
.load('shownic8.php')
.appendTo('#div1')
;
prevContents.remove();
},7000);

How to disable jQuery plugin on window resize

I'm trying to implement the window resize event listener so that the jScroll jQuery plugin I'm using doesn't fire on smaller screens where the scrolling of certain items is causing problems.
By putting together a mix of stuff i've read here this is what i've come up with:
<script>
$(window).resize(function() {
windowWidth = $(this).width();
if (.windowWidth() > 602) {
$(".sectionTitle").jScroll({speed : "slow",top : 50});
});
</script>
How to disable JavaScript in media query was my main source of help but still haven't got it to work. Any help would be greatly appreciated.
RE the comments:
this is what I get in the console:
Uncaught SyntaxError: Unexpected token . (index):113
2
Uncaught SyntaxError: Unexpected end of input (index):1
GET http://ghost-mirror.org/notify_act.php net::ERR_NAME_NOT_RESOLVED jquery.js:5
When i dont wrap the jscroll code in the resize function, .sectionTitle follows the users scrolling in the window like a fixed element until it reaches the end of its container.
I updated the code like entiendo stated:
<script>
$(window).resize(function() {
var windowWidth = $(this).width();
if(windowWidth > 602) {
$(".sectionTitle").jScroll({speed : "slow",top : 50});
}
});
</script>
If I could just get the plugin to run by default on window widths more than 602px and disabled by default on windows less than 602 i would be super grateful. (At the moment it only runs when I resize the window, so If I load up the page but dont change the size then the script doesnt run).
So, here's a suggestion:
HTML:
<div id="container">
<div class="scroll">
<h3>Page 1</h3>
<p>Page 1 of jScroll Example - jQuery Infinite Scrolling Plugin
This is the content of page 1 in the jScroll example. Scroll to the bottom of this box to load the next set of content.
This is example text for the jScroll demonstration. jScroll is a jQuery plugin for infinite scrolling, endless scrolling, lazy loading, auto-paging, or whatever you may call it.
With jScroll, you can initialize the scroller on an element with a fixed height and overflow setting of "auto" or "scroll," or it can be set on a standard block-level element within the document and the scrolling will be initialized based on the brower window's scroll position.
jScroll is open-source and can be downloaded from my GitHub repository at github.com/pklauzinski/jscroll. </p>
next page
</div>
</div>
jQuery:
$(document).ready(function(){
var origElement = $('.scroll').clone(); //we're cloning the original element and will use that to replace the content of the div "container" whenever the window size is less than 602px
if($(window).width() > 602){
$('.scroll').jscroll();
}
$(window).resize(function(){
if($(window).width() < 602){
alert($(window).width());
$('.scroll').remove();
$('#container').html(origElement);
}
else{
$('.scroll').jscroll();
}
});
});
Here's a fiddle: http://jsfiddle.net/6YXFu/3/

Using javascript to pause background scroll to allow for fixed elements to have slide show

Ok so the effect I am trying to emulate can be found on the nexus 5 site - http://www.google.com/nexus/5/ - when you scroll to the phone section. I've viewed source and looked through the code but there is over 13k lines of js so it was a waste.
Anyways what I did was add a class to fix the position of the images and created a background div that was like 5000px so it would appear to be fixed. The js fixed the position after the screen reached a certain point and then removed the fixed class after the end of the div.
My question is that i know this can be done better than my janky 'hack'. I'd love to hear your thoughts on better implementation.
This is part of the code that adds the fixed class
<script type="text/javascript">
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 500) {
$(".container").addClass("fixed");
}
if (scroll >= 8000) {
$(".container").removeClass("fixed");
}
});
Try this guide:
http://blog.teamtreehouse.com/multiplane-design-with-svgs-and-css-3d-transforms
Demo: http://codepen.io/nickpettit/full/eBCrK
Haven't done something like this before myself however. Also just a note that fixed position elements from my experience act up when viewed on tablet/smartphone.

Jquery Sticky Nav Issue

I'm been trying to get my head around issue and seem to cant find some help.
http://fiddle.jshell.net/DQgkE/7/show/
The experience is a bit jumpy and buggy now- but what i will like is
1) When you scroll down the page. I want the Sticky Nav to be (disable,dropped off, stop) at a specific location(chapter-3) on the page and the user should have the ability to keep scrolling down.
2) When the user is scrolling back up, the code will stick the nav back and carry it up until the nav reaches the original position at the top.
Below is a starting point.
3) Currently is kinda of doing that but there's some huge jump going on when scrolling back up
http://imakewebthings.com/jquery-waypoints/#doc-disable
using disable, destroy, enable option will be nice.
This is a original experience cleaned: http://fiddle.jshell.net/DQgkE/1/show/
Thanks for the help in Advance.
I'm not sure how this plugin you used work, but I have a solution I wrote a while back that I wrote in jquery. It has few variables at the top, the item you wanted sticky, the item where you want it to stop, and the class to add when it becomes sticky and padding at the top and bottom. I only modified the javascript portion in this fork.
EDIT
I went ahead and fixed the original code. Solution without waypoint plugin is in comments.
Here is the result:
http://fiddle.jshell.net/Taks7/show/
I would recommend to use jQuery (that was a surprise, right?! :P)
$(document).ready(function() { //when document is ready
var topDist = $("nav").position(); //save the position of your navbar !Don't create that variable inside the scroll function!
$(document).scroll(function () { //every time users scrolls the page
var scroll = $(this).scrollTop(); //get the distance of the current scroll from the top of the window
if (scroll > topDist.top - *distance_nav_from_top*) { //user goes to the trigger position
$('nav').css({position:"fixed", width: "100%", top:"*distance_nav_from_top*"}); //set the effect
} else { //window is on top position, reaches trigger position from bottom-to-top scrolling
$('nav').css({position:"static", width:"initial", top:"initial"}); //set them with the values you used before scrolling
}
});
});
I really hope I helped!

How to prevent content jump after adding position:fixed to subhead?

I'm currently working on my new portfolio you can see here: http://katharinakoeth.de/neu/
And there's already my problem. As you can see, I added some jquery action to my subheads (i'm really a beginner when it comes to javascript) to change its position from inherit to fixed/sticky .. but when the change happens, my content jumps up because of the sudden space.
ยป it's most obvious with the "people I enjoy working with" ... the first person suddenly disappears as soon as the subhead becomes sticky.
Is there any way to either add extra space or prevent the jump in another way?
When you change those subheaders to position:fixed, they're removed from the flow of the document. They have a margin-bottom: 75px which is also removed from the flow when that happens.
Try changing that to a margin-top:75px to the start of the blocks below each subheader; that won't "disappear" when the subheads change position values, so your spacing should be preserved.
FYI, your fix.js file could probably be refactored down to something like this:
var $titles = $("header h2");
$(window).scroll(function(){
var win_top = $(this).scrollTop();
$titles.each(function(){
var div_top1 = $(this).offset().top;
if (win_top > div_top) $(this).addClass('stick')
else $(this).removeClass('stick');
});
});

Categories

Resources