in the fiddle you will see at the center of the page a DIV that contains text next to an img.
When I scroll down/up I need to effect with jquery/javascript only the div who's the closest to the navbar-below. all the divs as the same class so I effect them all-not what I need
For example:
what I am trying to achieve : when I scroll down,the closest div to the navbar(yellow bar) will be painted(the div) green,so if I scroll down and the navbar "collapse" with the div with will paint in green, and when he passes him and "disapper" it will go back to original color and the next div will paint in green. is it possible?
Here's the JS FIDDLE: http://jsfiddle.net/nnkekjsy/3/
When I referred to div I meant this section :
<div class="x" id="inside_center">
<div class="left_side" id="left_inside_center">sddsadasasdsadLorem </div>
<div class="right_side" id="right_inside_center"><img src="http://img-9gag-lol.9cache.com/photo/a7KwPAr_460s.jpg"></div>
</div>
JQUERY :
I added my jquery,as you can see it works only for the first one,and then stuck.. i need to "pass" it along the others div below him when the are getting to the same point. any ideas? :
$(document).ready(function() {
$(window).scroll(function() {
var scrollVal = $(this).scrollTop();
var navHeight = $("#div_menu").outerHeight();
if ( scrollVal > 55) {
$('#left_inside_center').css({'position':'fixed','top' :navHeight+'px'});
} else {
$('#left_inside_center').css({'position':'static','top':'auto'});
}
});
});
Are you looking for some thing like this?
http://jsfiddle.net/mcozkpv3/1/
This is just quick hack to find closes elements based on distance and selecting it. add data-did attribute to each item div.
$(document).ready(function () {
$(window).scroll(function () {
$('[data-did]').each(function (i, e) {
var dist = $(e).offset().top - $('#div_menu').offset().top
if (dist < 80) {
$(e).addClass('closest');
} else {
$(e).removeClass('closest');
}
});
var scrollVal = $(this).scrollTop();
var navHeight = $("#div_menu").outerHeight();
if (scrollVal > 55) {
// $('#left_inside_center').css({'position':'fixed','top' :navHeight+'px'});
} else {
$('#left_inside_center').css({
'position': 'static',
'top': 'auto'
});
}
});
});
Related
I have three divs, each one with some hidden content. When you click on a div, its content is being displayed by sliding down. And at the same time, I'm using scrollTop to make the browser scroll to the top of the block thats been clicked on. The HTML looks like this:
<div class="blocks block1"></div>
<div class="content block1_content"></div>
<div class="blocks block2"></div>
<div class="content block2_content"></div>
<div class="blocks block3"></div>
<div class="content block3_content"></div>
However, im having problems with parts of the scrollTop animation. Here is the JS:
$('.blocks').on("click", function() {
if (!$(this).hasClass('expanded')) {
collapseExpandedFunction();
$('html, body').animate({
scrollTop: $(this).offset().top
}, 500);
$(this).addClass('expanded');
$(this).next().slideDown();
} else if ($(this).hasClass('expanded')) {
collapseExpandedFunction();
}
});
collapseExpandedFunction = function() {
$('.blocks.expanded').removeClass('expanded');
$('.content').slideUp();
};
I made an jsfiddle to easier demonstrate the problem: https://jsfiddle.net/ss53ckyk/3/
Explaination:
If you start toggle the green block and then toggle the red or blue, it's all good. The greens content is being hidden, while the red/blue is displayed and scrolled to the top of the block.
The problem is if you start from the top and moving down. If you first toggle the red one and then either blue or green, the browser won't scroll down correctly.
Another thing i'd like is to make the slideDown happen after the scrollTop animation is done.
Hopefully someone can help me out!
EDIT:
There should only be one blocks content visible at a time. For example, if you click the red once and then the blue, the content of the red should slide up, while the blue is showing.
The asynchronous nature of javascript is causing your issues; namely .slidUp() function. When this event is triggered, it fires an asynchronous event, which is non-blocking to the rest of the function. Therefore, the animate top will take a snapshot of the DOM at a particular moment in time while the .slidUp() function is actioning. Replacing the .slidUp() and .slidDown() with .show() and .hide() to resolve this, but this doesn't provide the responsiveness you require. One thought would be to capture the offsets of each previous content div and use that in the scrollTop function.
EDIT :
Based on the edit, you need to make few adjustments in your code which calculates the scrolltop position based on scrollposition and adding margin based on the corresponding .content div
$(document).ready(function() {
var addMargin = false;
$('.blocks').on("click", function() {
if (!$(this).hasClass('expanded')) {
collapseExpandedFunction();
var doc = document.documentElement;
var ele = this;
var nextEle = $(ele).next();
$(this).addClass('expanded');
var margin = 0;
var scrollTo = 0;
if($(ele).hasClass('expanded'))
{
if(addMargin)
margin = $(nextEle).css('height').replace('px','');
scrollTo = $(ele).offset().top - margin;
}
if(doc.scrollTop != 0 && doc.scrollTop > scrollTo && addMargin)
{
console.log(margin);
scrollTo = scrollTo + 200;
}
$('html, body').animate({
scrollTop: scrollTo
}, 500, function()
{
$(ele).next().slideDown();
});
} else if ($(this).hasClass('expanded')) {
collapseExpandedFunction();
}
});
collapseExpandedFunction = function()
{
$('.blocks.expanded').removeClass('expanded');
$('.content').slideUp();
addMargin = false;
};
window.onscroll = function (e) {
addMargin = true;
}
});
Here's the working code : https://jsfiddle.net/ss53ckyk/13/
I have a div called #menu which I want to display when I scroll past the element #section3, if I scroll up past that element again, I want #menu to disappear
How would I code this?
Maybe something like this?
scrolled = "no"
$(window).scroll(function(){
scr = $("body").scrollTop();
if (scr > 100 && scrolled == "no"){
$("#menu").css({"display:block"})
displayed = "yes"
}
if (displayed == "yes" && scrolled = "yes"){
$("#menu").css({"display:none"})
}
});
The above assumes that #section3 is 100 pixels down the page. If you do not know where its going to be on the page then you could use the method outlined here:
Trigger event when user scroll to specific element - with jQuery
With jQuery you can get the scroll position with $("body").scrollTop();.
Expanding on what #Ned Hulton said, I recommend comparing the scroll position to the top of a "container element" (or 'row') in your page like this:
if ($('body').scrollTop() > $('#someRow').offset().top){
//do something
}
That way you can account for your container appearing at a variable distance down the page (which will come in handy for mobile browsing or cases where your text wraps to additional lines)
I just whipped this up in jsfiddle
https://jsfiddle.net/rb56j0yu/
it uses jQuery, and checks the scroll position against the target div. Css sets the menu as position: fixed, and defaults to hidden.
$(window).scroll(function(){
var yPos = $("body").scrollTop();
var yCheck = $("#c3").position().top;
if (yPos > yCheck && !$("#menu").is(":visible"))
{
$("#menu").show();
}
if (yPos <= yCheck && $("#menu").is(":visible"))
{
$("#menu").hide();
}
});
First, get your #section3 top offset and height. Which will be used as the threshold whether #section3 is actually on the window screen.
var top = $('#section3').offset().top;
var bot = topOffset + $('#section3').height();
Then, detect it on your scroll event.
$(window).on('scroll', function () {
var scrollTop = $(window).scrollTop();
if (scrollTop >= top && scrollTop <= bot) {
// #section3 is within the screen.
$('#menu').show();
}
else {
// #section3 is out of screen.
$('#menu').hide();
}
});
This is a common use case, I wrote following code:
// what does "Auto Header" mean, goto https://www.yahoo.com/
// scroll down and you will see the purple part auto fixed to top,
// while when scroll up, it restores and does not be fixed.
// 1. multiple auto header elements handled
// 2. dynamically create/remove elements issue handled
// 3. no unnecessary dom operation, high performance
// usage: just add 'class="auto-header"' to any element you want to auto header
// suggest set each auto-header element specific width and height
// do not guarantee it works when resize or scroll left/right
$(document).ready(function() {
var rawTops = [],
rawLefts = [],
rawStyles = [],
$locations = [], // record next sibling so that element easily find where to restore
fixed = []; // mark whether this element is fixed
$(".auto-header").each(function() {
var $this = $(this),
offset = $this.offset();
rawTops.push(offset.top);
rawLefts.push(offset.left);
rawStyles.push($this.attr("style"));
$locations.push($this.siblings().eq($this.index()));
fixed.push(false);
});
$(window).on("scroll", function() {
$(".auto-header").each(function(i, e) {
if(!fixed[i] && $(window).scrollTop() > rawTops[i]) {
var $te = $(this).clone(true);
$(this).remove();
$locations[i].before($te);
$te.css({
"position": "fixed",
"top": 0,
"left": rawLefts[i],
"z-index": 100
});
fixed[i] = true;
} else if(fixed[i] && $(window).scrollTop() < rawTops[i]) {
$(this).removeAttr("style").attr("style", rawStyles[i]);
fixed[i] = false;
}
});
});
});
i have one section inside 2 DIV's where the div's name 1st div and 2nd div . By Default 2nd div will be hidden, after scrolling 50% or more 1st div will be hidden and 2nd div will be displayed. How do i do that?
I used:
var heightDivid = $(window).height() / 2;
$(window).on('scroll', function(e){
$('.sections-class').each(function(){
if(this.getBoundingClientRect().top <= heightDivid ){
$(this).removeClass('heightDivids') ;
}
else{
$(this).addClass('heightDivids') ;
}
})
})
Perhaps you can alter something along these lines to do what you're attempting to do.
Utilize jQuery's scrollTop to identify where you want the change to occur.
Set a limit for when you want to hide the one div and show the two div.
$(window).scroll(function() {
var height = $(window).scrollTop();
if(height > 10) {
$('.two').show();
$('.one').hide();
}
});
Example: http://jsfiddle.net/xv2m4qn6/
If you want the effect to reverse simply add a second conditional:
Example: http://jsfiddle.net/xv2m4qn6/1/
At Last I did :) and it's work for me .... Thank you all for your help :)
var shadowEdgePoint = $(window).height() / 2;
$(window).on('scroll', function(e){
$('.section-class').each(function(){
if(this.getBoundingClientRect().top <= shadowEdgePoint){
$('.two').show();
$('.one').hide();
}
else{
$('.two').hide();
$('.one').show();
}
})
});
I am trying to add a class when the bottom of a div reaches the top of the window, but am not sure of how to do it.
I have managed to add the class when the top of the div gets to the top of the window, but am not having much luck with the bottom of the div.
Code I am using:
$(document).ready(function() {
var menuLinksTop = $('.container').offset().top;
var menuLinks = function(){
var scrollTop = $(window).scrollTop();
if (scrollTop > menuLinksTop) {
$('header').addClass('black-links');
} else {
$('header').removeClass('black-links');
}
};
menuLinks();
$(window).scroll(function() {
menuLinks();
});
Any help is appreciated.
You should use javascript's getBoundingClientRect() method, watch $(window).scroll event, and look at element's rectangle, its bottom value will give you what you need (if it's negative, your element is all the way up)
$(window).scroll(function() {
console.log($("div.watch")[0].getBoundingClientRect());
if ($("div.watch")[0].getBoundingClientRect().bottom < 0)
alert ("i'm out :3");
});
see jsFiddle http://jsfiddle.net/ja5nnbwr/2/
Add the height of the div. Assuming it is the .container :
var menuLinksTop = $('.container').offset().top + $('.container').height();
I need some help regarding auto scroll to each div or element when the user will use the scroll button in the mouse. Here goes the scenario
Suppose this is my structure of the page..
<div id="main-wrap">
<div class="my-div-1">
<p>here goes my content 1</p>
<img src="/images/sample-1" alt="sample-1"/>
</div>
<div class="my-div-2">
<p>here goes my content 2</p>
<img src="/images/sample-2" alt="sample-2"/>
</div>
<div class="my-div-3">
<p>here goes my content 3</p>
<img src="/images/sample-3" alt="sample-3"/>
</div>
</div><!-- end of main-wrap id -->
-Now suppose my each div has got enough content to make the page long. Suppose the user is on my-div-1 and when the viewer uses the scroll button to scroll down, instead of scrolling through the whole div, i want it to scroll automatically to the my-div-2.
I hope my explanation make sense here.
Is there any way to sort it out by using javascript and jquery?
I will appreciate any response..Thanks in advance.
Here's a fiddle with what you want: http://jsfiddle.net/3qxhY/9/
Source of plugin used in code (debounce/throttle plugin): http://benalman.com/projects/jquery-throttle-debounce-plugin/
Code
// debounce/throttle plugin
(function(b,c){var $=b.jQuery||b.Cowboy||(b.Cowboy={}),a;$.throttle=a=function(e,f,j,i){var h,d=0;if(typeof f!=="boolean"){i=j;j=f;f=c}function g(){var o=this,m=+new Date()-d,n=arguments;function l(){d=+new Date();j.apply(o,n)}function k(){h=c}if(i&&!h){l()}h&&clearTimeout(h);if(i===c&&m>e){l()}else{if(f!==true){h=setTimeout(i?k:l,i===c?e-m:e)}}}if($.guid){g.guid=j.guid=j.guid||$.guid++}return g};$.debounce=function(d,e,f){return f===c?a(d,e,false):a(d,f,e!==false)}})(this);
//elements you want to scroll to go here
divs = [$(".my-div-1"),$(".my-div-2"),$(".my-div-3")];
var lastScrollTop = 0; //we'll update this on every scroll and compare it to the last scroll to determine the scroll direction
var run = true;
$(window).scroll($.debounce(250, true, function () { //debounce so it only runs once per scroll
var st = $(window).scrollTop();
if (st > lastScrollTop) { // if the scrollTop when the scroll event fires is larger than the last scroll, we can assume the scroll was in a downward direction
$.each(divs, function (i, v) {
((v.offset().top - $(window).scrollTop()) < 0) && (next = i + 1); //compare each elements offset to the windows offset to determine which element we're currently scrolling through
});
run = (next != divs.length) ? true : false; //dont run if we are at the last div
} else {
$.each(divs, function (i, v) {
((v.offset().top - $(window).scrollTop()) < 0) && (next = i);
});
run = true;
}
if (run) {
$('html, body').animate({
scrollTop: divs[next].offset().top
}, 1000,'linear', function() {
lastScrollTop = $(window).scrollTop();
});
} else { lastScrollTop = $(window).scrollTop(); }
}));