jQuery syntax added var - javascript

I needed a jQuery function to fix my div when the page is scrolled.
I found this:
var fixed = false;
var topTrigger = $('#sticker').offset().top;
$(document).scroll(function() {
if( $(this).scrollTop() >= topTrigger ) {
if( !fixed ) {
fixed = true;
$('#sticker').css({'position':'fixed', 'top':'0'});
}
} else {
if( fixed ) {
fixed = false;
$('#sticker').css({'position':'relative'});
}
}
});
Now, since I'm not a super beginner with jQuery, I tried to skim it and understand it. The only things I don't understand are the things related to the var:fixed. I tried to delete the var and the if statement related to that and the function works perfectly.
My question : why is that variable there, what does it mean, what feature does it add to the entire function?
Why should I keep it there instead of deleting everything related to that variable?

The scroll event will be fired multiple times as the user scrolls. If you keep on changing the DOM attributes, then the performance of the site may slow down.
To avoid applying the style multiple times, they are having a flag called fixed. So once the user has scrolled a particular height, they will trigger change the DOM to be fixed. Later they need not again change the CSS style.
Only if the user scrolls back less than the threshold they need to change the style again.

Related

Generic code to fade in divs with particular class, remove function after first run

I'm trying to create a generic function that can be placed just once in my site and work across multiple pages, nice and lightweight.
I want to be able to make certain divs on the site fade-in when you reach 10px above them on the scroll.
I want to do this by simply adding the following attributes to my divs:
.fade-in-block
#specific-block-name
The idea is that I could go through the site, add this class and an ID, and the animation would work.
I almost have it working except for one thing, the scroll listening constantly continues to console.log after the function has been called. I don't like this as it feels like it's going to be constantly trying to apply the animation, which won't really be seen from the front-end but I feel the constant maths behind the scenes could slow stuff down.
Here is my jQuery:
$('body .fade-in-block').each(function(){
var block = '#'+$(this).attr('id');
console.log('Block class is = '+block);
var offset = $(block).offset().top;
var $w = $(window).scroll(function () {
if ($w.scrollTop() > offset - 10) {
console.log('reached block turn-on point for '+block);
$(block).removeAttr('id'); // remove the ID from the element so the script doesn't continue to find the element
// fade and rise animation here
}
});
});
And here is a JSFiddle. It works just fine, but once you hit the block you'll see it logs constantly every pixel scrolled.
I tried to remedy this by removing the selecting id from the element once the event has occurred, but it continues to run.
Scroll and resize events both have this problem and the solution is said to be debouncing. However, I've never actually gotten debouncing to work properly. Instead I typically create a sort of switch that is turned off once the scroll condition has activated. In your case, since you have multiple elements, you would need to assign a switch to each element.
$(window).on('scroll', function(){
$('.fade-in-block').each(function(){
var appear = $(this).attr('data-appeared');
if(!appear){
$(this).attr('data-appeared', true);
//do something to $(this)
}
})
})
Here I'm adding a data attribute after it has appeared and checking for it again once it has.

How to dynamically change the height of an empty div using Javascript onclick and restore with onScroll

Context: I have a button on the top of the page in the header, and I want visitors to jump to the form section which is at a lower position on the same page. For some unchangeable factors, the form is partially hidden under the header after page jump, so I am thinking of creating a new div before the form and change the height of the div to push the form down after jumping. Then, when users scroll again on the page, the height should go back to 0.
Problem: When I click on the DemoButton for the first time, the div height doesn't change and the form goes under header, but the second time it works. I don't know how to fix that.
The basic html structure is shown as following:
<div>
<a href="#demoForm" id="DemoButton">
<button>request demo</button>
</a>
</div>
<div id="space"></div>
<from id="demoForm">...</form>
JavaScript:
window.onload = function comparison() {
window.addEventListener("scroll", reset, false);
var demo = document.getElementById('DemoButton');
demo.onclick = uniform;
}
function reset() {
document.getElementById('Space').style.height = '0';
}
function uniform() {
document.getElementById('Space').style.height = '160px';
};
I know a lot of people are using newer CSS for reactive headers these days. I believe it's done using media queries, and I might suggest researching it some more. (I have some experience, it was very easy and cool too.)
Ideally, you'd want something like this to happen in CSS without JavaScript at all. See if you can get it figured out that way.
Using very light Javascript, it seems the easiest thing to do would be to just offset the scroll by the height of the header once the button has been clicked. You can hard-code the header height or calculate it dynamically.
So...
;;;;;;;;;;;;;;
; $ = document ;
; id = 'getElementById' ;
;;;;;;;;;;;;;
onload = function (e)
{
$[id]('DemoButton')
. onclick = function offset(e)
{
document.body.scrollTop -= $[id]('Header').offsetHeight;
}
;
}
Notes
You may have to wrap it in a 5ms setTimeout. Easy enough.
I don't remember all the cross-browseryness. There might be a need to parseInt or use document.documentElement. But at least you don't have cross-browser scroll events to deal with now, so this should be nice.

how to make a div stay in the same position and then dissapear at a specific point

So i'm wondering how you can make a div apear at a certain point of the page and stay in the exact same spot untill you reach a specific point of the page
kinda like they have on http://www.squarespace.com where you see a imac screen which stays on the screen until you reach a specific point
can this be done without using js
either way can someone let me know how?
I'm going to assume you mean making a div show up when the user has scrolled to a certain point in the page and then disappear when they scroll to another point.
This isn't technically possible with CSS. There might be a way to make it look like this with other elements covering it up, but I'll focus on doing it with JS for now.
Essentially, you want to
// set up limits for show/hide
var SHOW_Y = 100,
HIDE_Y = 800;
// function to be called every time
// the page is scrolled
function scrolled() {
if(window.scrollTop < SHOW_Y) {
hide(this);
} else if(window.scrollTop < HIDE_Y) {
show(this);
} else {
hide(this);
}
}
// helper function which hides an element
function hide(element) {
element.style.display = 'none';
}
// helper function which shows an element
function show(element) {
element.style.display = 'block';
}
window.addEventListener('load', function() {
var element = document.getElementById('your-element');
window.addEventListener('scroll', scrolled.bind(element));
});
I would probably do this using CSS classes rather than display properties, in order to control the way that the element disappears and reappears, but this should give you some idea.
You could also use a script like Skrollr or ScrollMagic.

Determining when the user has scrolled to the end of a DIV

My page has a DIV, with overflow and I've placed two buttons on either side of the div to act as secondary scrolling methods.
When pressing the left button, the following script is run and seems to work perfectly:
function slideLeft() {
if ($("#divfieldWidgets").scrollLeft() == 0) {
$('#divScrollWidgetsLeft').animate({ opacity: 0.1 }, 250);
window.clearInterval(animationHandler);
}
$('#divfieldWidgets').animate({ scrollLeft: "-=100px" }, 250);
}
However I just can't seem to be able to find a method to determine when the DIV has hit it's limit when scrolling right.
I'm pretty sure I need some calculation based on $("#divfieldWidgets").scrollLeft() and $("#divfieldWidgets").width(), but all arithmetic calculations I've performed on those two values don't yield any results that show any relation to the width, it's maximum, etc, etc.
There is ONE final option I thought of, and that's storing the current scrollLeft value in a temporary variable and comparing the new value; if there's no change, then it's reached the end but I'm sure there must be a more cleaner way of achieving this.
Any thoughts?
You could use something like
$(function() {
$('#lorem').scroll( function() {
if ( $('#lorem').scrollLeft() == ($('#lorem p').width() - $('#lorem').width())) {
alert('end!');
}
});
});
As shown here
I'd suggest store width on ready in variables accessible inside the scroll event
a = $('#lorem p').width();
b = $('#lorem').width();
and use them in function
if ( $('#lorem').scrollLeft() == (a - b)) {
// rest of the code
}
This way, you'll save a couple of more function calls on scroll. As it is a very costly event that you should be using only if there is no other solution.
Ideally, you should use throttled function calls like this. Which will delay the function call and save a lot of resources.

Prevent/stop auto anchor link from occurring

I need to prevent the automatic scroll-to behavior in the browser when using link.html#idX and <div id="idX"/>.
The problem I am trying to solve is where I'm trying to do a custom scroll-to functionality on page load by detecting the anchor in the url, but so far have not been able to prevent the automatic scrolling functionality (specifically in Firefox).
Any ideas? I have tried preventDefault() on the $(window).load() handler, which did not seem to work.
Let me reiterate this is for links that are not clicked within the page that scrolls; it is for links that scroll on page load. Think of clicking on a link from another website with an #anchor in the link. What prevents that autoscroll to the id?
Everyone understand I'm not looking for a workaround; I need to know if (and how) it's possible to prevent autoscrolling to #anchors on page load.
NOTE
This isn't really an answer to the question, just a simple race-condition-style kluge.
Use jQuery's scrollTo plugin to scroll back to the top of the page, then reanimate the scroll using something custom. If the browser/computer is quick enough, there's no "flash" on the page.
I feel dirty just suggesting this...
$(document).ready(function(){
// fix the url#id scrollto "effect" (that can't be
// aborted apparently in FF), by scrolling back
// to the top of the page.
$.scrollTo('body',0);
otherAnimateStuffHappensNow();
});
Credit goes to wombleton for pointing it out. Thanks!
This seems the only option I can see with ids:
$(document).ready(function() {
$.scrollTo('0px');
});
It doesn't automatically scroll to classes.
So if you identify your divs with unique classes you will lose a bit of speed with looking up elements but gain the behaviour you're after.
(Thanks, by the way, for pointing out the scroll-to-id feature! Never knew it existed.)
EDIT:
I know this is an old thread but i found something without the need to scroll. Run this first before any other scripts. It puts an anchor before the first element on the page that prevents the scroll because it is on top of the page.
function getAnchor(sUrl)
{
if( typeof sUrl == 'string' )
{
var i = sUrl.indexOf( '#' );
if( i >= 0 )
{ return sUrl.substr( i+1 ).replace(/ /g, ''); }
}
return '';
};
var s = getAnchor(window.location.href);
if( s.length > 0 )
{ $('<a name="'+s+'"/>').insertBefore($('body').first()); }
Cheers!
Erwin Haantjes
Scroll first to top (fast, no effects pls), and then call your scroll function. (I know its not so pretty)
or just use a prefix
This worked well for me:
1- put this on your css file
a[name] { position: absolute; top: 0px }
2- put this on your document.ready bind right before you start animating (if you're animating at all)
$("a[name]").css("position","relative");
Might need tweaking depending on your stylesheet/code but you get the idea.
Credit to: http://cssbeauty.com/skillshare/discussion/1882/disable-anchor-jump/

Categories

Resources