Change CSS class based on current ID - javascript

So I am using jQuery scrollTop() to change the CSS class of a specific element based on how far down the page you one (one page website). However, this requires me to adjust the jQuery when the sections of the page grow larger in height.
Is there any good way to change the CSS class based on the current ID you are at in the page? or does it need to be based on how far down you are in terms of pixels?
This is the code I am currently using:
<script>
$(window).bind('scroll', function() {
if($(this).scrollTop()>= 0 && $(this).scrollTop() < 550){
$('.homeLink').addClass('selected');
}
else {
$('.homeLink').removeClass('selected');
}
});
$(window).bind('scroll', function() {
if($(this).scrollTop()>= 575 && $(this).scrollTop() < 1900){
$('.photosLink').addClass('selected');
}
else {
$('.photosLink').removeClass('selected');
}
});
$(window).bind('scroll', function() {
if($(this).scrollTop()>= 1950 && $(this).scrollTop() < 3000){
$('.aboutLink').addClass('selected');
}
else {
$('.aboutLink').removeClass('selected');
}
});
</script>
It would be really cool to have it just change based on the ID it's at. Any ideas?

You could get the position of a target element with a certain ID, and change the behavior of the window scroll function based on whether you had reached that position yet.
// in window scroll function do this
var pos = $(window).scrollTop();
var elemTop = $('#someElement').position().top;
if (pos > elemTop) {
doSomething();
}
For example, see this fiddle

Related

Is there a way for changing different images at different scrolling point?

I'm trying to change one image at a time when I'm scrolling through the page.
This code actually changes all images classes when we get to that point of the scroll.
Is there any other way we can change images individually when scrolling?
Thank you.
jQuery(function($) {
var show = $(".show");
var hide = $(".hide");
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if($(window).scrollTop() >= 500){
show.removeClass('show').addClass("hide");
hide.removeClass('hide').addClass("show");
} else {
show.removeClass("hide").addClass('show');
hide.removeClass('show').addClass("hide");
}
});
});
Since you're checking the scroll position of window and hiding/showing, this will hide/show all elements with the specified class name.
To achieve your purpose, add css position: relative to all images (if no position is specified already),
Then, iterate through each image as follows...
jQuery(function($) {
//var show = $(".show");
//var hide = $(".hide");
$(window).scroll(function() {
/*var scroll = $(window).scrollTop();
if($(window).scrollTop() >= 500){
show.removeClass('show').addClass("hide");
hide.removeClass('hide').addClass("show");
} else {
show.removeClass("hide").addClass('show');
hide.removeClass('show').addClass("hide");
}*/
var images = $('img');//or any other selector
$.each(images, function () {
if($(this).offset().top <= -500) {
$(this).hide();
}
else {
$(this).show();
}
});
});
});

How to make an element become fixed when 50px from the top of the screen

I have a html div element that scrolls with the page but I would like it to become fixed once it reaches 50px from the top of the screen...
How is this done?
My div id is #box
Thanks!
-Ina
If you want it to be fixed at the top of the page at some distance from the top, you can check the top offset of the element and change the class when it reach the distance you want.
Here is the jquery code for your reference
jQuery(document).scroll(function() {
var documentTop = jQuery(document).scrollTop();
console.log('this is current top of your document' + documentTop );
//box top is 891
if (documentTop > 841) {
//change the value of the css at this point
jQuery("#box").addClass("stayfix");
}
else
{
jQuery("#box").removeClass("stayfix");
}
});
You need to be more specific about what have you done so far. For eg, how did you make the div element to scrolls inside the page. using css or js/jquery animation features?That will help us to give more specific answer.
**Edited According to your fiddle.
They are right, this question is duplicate. Here is a code I made with answers from the forum.
var box_top = $("#box").offset().top;
$(window).scroll(function (event) {
if ($(window).scrollTop() >= (box_top - 50)) {
$("#box").css({position:"fixed",top:"50px"});
} else {
$("#box").css({position:"relative"});
}
});
Hope it helps anyway.
https://jsfiddle.net/ay54msd5/1/
Try something like this. It's a solution using jquery (hopefully not a problem) that checks the scrollHeight of the page every time the page scrolls. If the scrollHeight is greater than a certain threshold, the element becomes fixed. If not, the element is positioned relatively (but you can do whatever you want in that case.
$(document).ready(function() {
var navFixed = false;
var $box = $("#box");
var topHeight = 50;
$(document).scroll(function() {
if ($(document).scrollTop() >= topHeight && !navFixed) {
$box.css("position", "fixed");
navFixed = true;
}
else if ($(document).scrollTop() < topHeight && navFixed) {
$box.css("position", "relative");
navFixed = false;
}
});
});
You would have to write some additional CSS targeting the #box element that tells it what coordinates you'd like it to be fixed to.

Remove class if other class present at scroll height

I need to hide an element on scroll - but only if its not already hidden.
I've written the following jQuery but it's not working for some reason - any tips please?
The css class open-style-switcher and close-style-switcher determine a css scroll anim. I want to wait until the page has scrolled to a certain height, then auto hide the search box if it contains the open class.
Where am I going wrong!?
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 500) {
$('#search-box').hasClass('open-style-switcher').toggleClass("open-style-switcher", "close-style-switcher", 1000);
}
});
"toggleClass" can receive two classes separated by space
Also creating "$searchBox" variable to avoid double search in DOM.
And as was told before: hasClass() returns boolean
Here it is:
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 500) {
var $searchBox = $('#search-box');
if ($searchBox.hasClass('open-style-switcher'))
{
$searchBox.toggleClass("open-style-switcher close-style-switcher", 1000);
}
}
});
.hasClass() - Returns: Boolean determines whether any of the matched elements are assigned the given class.
In your scenario, addClass and removeClass is more suitable.
See below :
$(window).scroll(function() {
var scroll = $(window).scrollTop();
var searchbox = $('#search-box');
if (scroll >= 500 && searchbox.hasClass('open-style-switcher')) {
searchbox.removeClass("open-style-switcher");
searchbox.addClass("close-style-switcher", 1000);
}
});
toggleClass() does not work in the way you, or even the other answers, think it does. It only adds and removes classes, not exchange them for others. See toggleClass() documentation here.
if (scroll >= 500) {
if($('#search-box').hasClass('open-style-switcher'))
{
$('#search-box').removeClass("open-style-switcher");
$('#search-box').addClass("close-style-switcher");
}
}
I imagine you will also want an else block that does the inverse of this. Perhaps the below is a more straight forward way of doing what you want to achieve as there may not be any point in the check to see if the #search-box already has the open-style-switcher class.
if (scroll >= 500) {
$('#search-box').removeClass("open-style-switcher").addClass("close-style-switcher");
}
else
{
$('#search-box').removeClass("close-style-switcher").addClass("open-style-switcher");
}

add element offset to jQuery offset calculations

I am rather new to jquery and i'm trying to find the right offset for a div element inside the body. I want to make this div element sticky whenever I scroll down and pass the top offset of this element.
I followed this tutorial: https://www.youtube.com/watch?v=utonytGKodc and it works but I have a metaslider in my header and the width/height of this element is left out of the calculations to find the right offset....
the result is that my element becomes a sticky element way to soon, is there a way I can manualy add the sliders coordinates (offset) to the offset calculation of the element i want to make sticky?
var offerteOffset = jQuery(".agendawrap").offset().top //+ metaslider coordinates??;
alert(offerteOffset);
jQuery(window).scroll(function() {
var scrollPos = jQuery(window).scrollTop();
if (scrollPos >= offerteOffset) {
jQuery(".agendawrap").addClass("fixed");
} else {
jQuery(".agendawrap").removeClass("fixed");
}
});
I cant believe people make such bad tutorials.
First of all: dont write jQuery all the time. Have a look at this thread.
Basically it says: use an invoking function with an own scope:
(function($) { /* all your jQuery goes here */ })(jQuery);
So you can just type $ instead of jQuery.
To your original question:
(function($) {
$(function() { // document ready...
var scrollTolerance = 50,
agendawrap = $(".agendawrap"),
offerteOffset = agendawrap.offset().top;
$(window).on('scroll', function() {
var scrollPos = $(window).scrollTop();
// OR: if (scrollPos - scrollTolerance >= offerteOffset) {
if (scrollPos + scrollTolerance >= offerteOffset) {
agendawrap.addClass("fixed");
}
else {
agendawrap.removeClass("fixed");
}
});
});
})(jQuery);

Determine the id of the div that has been scrolled to bottom

simple question, easy points, cannot find the answer in SO. The javascript function below alerts when a user scrolls to the bottom of a div. I have many divs, but I only want the alert to run when a div id=imageloc is scrolled.
$(window).scroll( function() {
if ( document.documentElement.clientHeight + $( document ).scrollTop() >= document.body.offsetHeight ) {
if (this.id == "imageloc" ) {
alert("bottom of the page.");
}
}
});
The javascript function below alerts when a user scrolls to the
bottom of a div. I have many divs, but I only want the alert to run
when a div id=imageloc is scrolled.
Maybe I have misunderstood, but it's phrased like you have many scrollable divs and want to do something if one of them is scrolled to the bottom. Then you should listen to scroll event on this particular div:
$("#imageloc").scroll( function(e) {
if ( this.scrollTop >= this.scrollHeight - this.offsetHeight ) {
console.log( 'bottom' )
}
});
http://jsfiddle.net/aheh5/
If you want to do something when the document has been scrolled past the bottom of a particular div try this: http://jsfiddle.net/aheh5/1/ (it will, however, trigger every time the user scrolls the window and #imageloc is above the viewport).
Use like this
$(window).scroll(function() {
var winTop = $(this).scrollTop();
var $divs = $('div');
var top = $.grep($divs, function(item) {
return $(item).position().top <= winTop;
});
alert($(top).attr('id'));
});
You can try something like this,
var imgLocTop = $('#imageloc').offset().top ;
var $window = $(window);
var limit = Math.abs($window.height() - imgLocTop);
$window.scroll( function() {
if($window.scrollTop() >= limit) {
alert('Reached the required div');
}
});
Demo

Categories

Resources