I'm trying to check when a div is reached from scrollbar with jquery.
I read some similar question on stackoverflow, but all are on one div only.
I have 4 div, with height: 100% and I want know when the scroll bar pass every div.
I tried, but only works with the first div.
HTML:
<body>
<div id="main"></div>
<div id="service"></div>
<div id="clients"></div>
<div id="about"></div>
</body>
CSS:
body, html {
height: 100%;
padding: 0px;
margin: 0px;
}
#main {
background: red;
height: 100%;
}
#service {
background: green;
height: 100%;
}
#clients {
background: blue;
height: 100%;
}
#about {
background: yellow;
height: 100%;
}
JS:
$(document).ready(function() {
var passed_service = false;
var passed_service = false;
$('body,html').bind('scroll mousedown wheel DOMMouseScroll mousewheel keyup', function(event){
if($(window).scrollTop() >= ($("#service").height())){
if(!passed_service){
alert("To #service");
passed_service = true;
}
}
if($(window).scrollTop() >= ($("#service").height() + $("#clients").height())){
if(!passed_clients){
alert("To #clients");
passed_clients = true;
}
}
});
});
SORRY TO ALL, WAS A MY STUPID ERROR, I CAN'T DELETE THE QUESTION :(
var passed_service = false;
var passed_service = false; /* should be 'passed_clients' */
^ There's your problem
Also, instead of adding up the divs' heights, use the top offset instead.
DEMO
$(window).scrollTop() >= $("#service").offset().top
$(window).scrollTop() >= $("#clients").offset().top
...
You never declare the passed_clients variable.
Change this:
var passed_service = false;
var passed_service = false;
to this:
var passed_service = false;
var passed_clients = false;
Working fiddle: http://jsfiddle.net/XUEfD/8/
Working Demo link
use this: (parseInt($("#service").height()) + parseInt($("#clients").height()))
$(document).ready(function() {
var passed_service = false;
var passed_clients = false;
$('body,html').bind('scroll mousedown wheel DOMMouseScroll mousewheel keyup', function(event){
if($(window).scrollTop() >= ($("#service").height())){
if(!passed_service){
alert("To #service");
passed_service = true;
}
}
//console.log($(window).scrollTop());
if($(window).scrollTop() >= (parseInt($("#service").height()) + parseInt($("#clients").height()))){
if(!passed_clients){
alert("To #clients");
passed_clients = true;
}
}
});
});
Related
I am trying to make me character moving left and up and I think jump() and slideLeft()
functions are working properly and the problem is in the controller(e) function (else if (e.KeyCode===37)) . The first function is avaible but it isn't able to acces the second conditon function. Also, I would want to make the grid solid after I will make an slideRight() similar function ,so if my character is jumping on it, the platform would sustain the square . Has anyone any ideea for either of my questions ?
Code snippet:
var square = document.querySelector('.square');
var grid = document.querySelector('.grid');
var bottom = 0;
let isJumping = false;
let isGoingLeft = false;
var newBottom;
let left = 0;
let leftTimerId;
function jump() {
if (isJumping) return
let timerUpId = setInterval(function() {
if (bottom > 250) {
clearInterval(timerUpId);
let timerDownId = setInterval(function() {
if (bottom < 0) {
clearInterval(timerDownId);
isJumping = false;
}
bottom -= 5;
square.style.bottom = bottom + 'px';
}, 20)
}
isJumping = true;
bottom += 30;
square.style.bottom = bottom + 'px';
}, 20)
}
function slideLeft() {
console.log('da');
isGoingLeft = true;
leftTimerId = setInterval(function() {
left -= 5;
square.style.left = left + 'px';
}, 20)
}
function controller(e) {
if (e.keyCode === 32)
jump();
else if (e.KeyCode === 37)
slideLeft();
}
document.addEventListener('keydown', controller);
.grid {
position: absolute;
background-color: chartreuse;
height: 20px;
width: 500px;
bottom: 100px;
left: 100px;
}
.square {
position: absolute;
background-color: darkblue;
height: 100px;
width: 100px;
bottom: 0px;
left: 150px;
}
`
<div class="grid"></div>
<div class="square"></div>
EDIT:
There is a typo:
The second time you've written KeyCode
function controller(e) {
if(e.keyCode===32) {
jump();
}
else if(e.keyCode===37) {
slideLeft();
}
}
I don't really understand what you mean by the second part of your question. If you want a character to have the ability to jump on a square, you'll have to implement a collision detection. Something like this:
if ( isNotOnGround() ) {
fall()
}
I've searched for similar question for quite a long time but all my searches gone in vain. Here is my code
<div class="footer-sidebar container" style="height:40px;"></div>
<button class="button">Click</button>
Now if someone clicks on button then my .container height should increase to 400px and if someone clicks on the same button it must back to 40px.
Edit: (Added CSS)
.footer-sidebar {
position: fixed;
z-index: 1500;
bottom: 0;
left: 0;
right: 0;
margin: 0 auto;
overflow: hidden;
}
Thanks
You could do that by adding a class to your div like this:
$('.button').on('click', function(){
$('.container').toggleClass('open');
}
Inline styles for this should be avoided. Use your css file and add something like this to it:
.container {
height: 40px;
}
.container.open {
height: 400px;
}
Javascript version (opposed to the previously added JQuery option):
Using booleans (tested):
var fullSize = false; // Used for toggling
var button = document.getElementsByClassName("button")[0]; // Get button
var div = document.getElementsByClassName("footer-sidebar")[0]; // Get div
button.onclick = function() {
if(fullSize) { div.style.bottom = 0 + "px"; fullSize = false; } // If div is already 400px...
else { div.style.bottom = -360 + "px"; fullSize = true; } // If div is already 40px...
};
Fiddle
Using classes (untested):
CSS:
.open {
height: 400px;
}
.closed {
height: 40px;
}
Javascript:
var button = document.getElementById("button"); // Get button
var div = document.getElementsByClassName("footer-sidebar container")[0]; // Get div
button.onclick = function() {
if(div.className = "closed") { div.className = "open" }
else if(div.className = "open") { div.className = "closed" }
else { div.className = "open" }
}
Hope this helps.
For my website at work I am trying to get the webbrowser to scroll to the tope of the page when in a small screen mode. According to some answers it should already being doing this anyway. I have enclosed a copy of the website here:
http://www.synergy-clinics.com/
I believe the code to control navigation is here:
var $currentclass = 'currentpanel';
var $currentlinkclass = 'currentlink';
var $class = 'panel';
var $dotclass = '.panel';
//var $body = 'body';
var $body = '#content'
var $downkey = '38';
var $upkey = '40';
//$(function () {
// $($body).mousewheel(function (event, delta) {
// var $current = $('div.currentpanel');
// $next = (delta > 0)? $current.prev($dotclass) :$next = $current.next($dotclass);
// if ($next.length) { ChangeCSSClass($current, $next); }
// event.preventDefault();
// });
//});
$(function () {
$($body).keydown(function (event, delta) {
var $current = $('div.currentpanel');
if (event.keyCode == $downkey)
{
$next = $current.prev($dotclass);
if ($next.length) { ChangeCSSClass($current, $next); }
event.preventDefault();
}
else if (event.keyCode == $upkey)
{
$next = $current.next($dotclass);
if ($next.length) { ChangeCSSClass($current, $next); }
event.preventDefault();
}
});
});
function MenuItemClick(SectionName)
{
var $current = $('div.currentpanel');
var $next = $('#' + SectionName);
if ($next != null) { ChangeCSSClass($current, $next); }
//event.preventDefault();
}
function ChangeCSSClass(Current, New)
{
$($body).scrollTo(New, 100, { offset: -115 });
$('#' + Current[0].id + 'Link').removeClass($currentlinkclass);
$('#' + New[0].id + 'Link').addClass($currentlinkclass);
Current.removeClass($currentclass);
Current.addClass($class);
New.addClass($currentclass);
}
I have Identified the scrollto line so it must be around here somewhere, any help would be much appreciated.
I was looking for that a few hours , and finally i did.
can you try that :
http://jsfiddle.net/b4M66/
jQuery:
$(function() {
$(window).scroll(function() {
if($(this).scrollTop() != 0) {
$('#toTop').fadeIn();
} else {
$('#toTop').fadeOut();
}
});
$('#toTop').click(function() {
$('body,html').animate({scrollTop:0},800);
});
});
CSS:
#toTop { position: fixed; bottom: 50px; right: 30px; width: 84px; background-color: #CCC; cursor: pointer; display: none; }
HTML:
<div id="toTop">Back to Top</div>
The KeyCode functions arent supported on touch screen devices. You have your code based on that. Just try to move that to the touchstart or click function of an element.
So basically I'd like to remove the class from 'header' after the user scrolls down a little and add another class to change it's look.
Trying to figure out the simplest way of doing this but I can't make it work.
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll <= 500) {
$(".clearheader").removeClass("clearHeader").addClass("darkHeader");
}
}
CSS
.clearHeader{
height: 200px;
background-color: rgba(107,107,107,0.66);
position: fixed;
top:200;
width: 100%;
}
.darkHeader { height: 100px; }
.wrapper {
height:2000px;
}
HTML
<header class="clearHeader"> </header>
<div class="wrapper"> </div>
I'm sure I'm doing something very elementary wrong.
$(window).scroll(function() {
var scroll = $(window).scrollTop();
//>=, not <=
if (scroll >= 500) {
//clearHeader, not clearheader - caps H
$(".clearHeader").addClass("darkHeader");
}
}); //missing );
Fiddle
Also, by removing the clearHeader class, you're removing the position:fixed; from the element as well as the ability of re-selecting it through the $(".clearHeader") selector. I'd suggest not removing that class and adding a new CSS class on top of it for styling purposes.
And if you want to "reset" the class addition when the users scrolls back up:
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 500) {
$(".clearHeader").addClass("darkHeader");
} else {
$(".clearHeader").removeClass("darkHeader");
}
});
Fiddle
edit: Here's version caching the header selector - better performance as it won't query the DOM every time you scroll and you can safely remove/add any class to the header element without losing the reference:
$(function() {
//caches a jQuery object containing the header element
var header = $(".clearHeader");
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 500) {
header.removeClass('clearHeader').addClass("darkHeader");
} else {
header.removeClass("darkHeader").addClass('clearHeader');
}
});
});
Fiddle
Pure javascript
Here's javascript-only example of handling classes during scrolling.
const navbar = document.getElementById('navbar')
// OnScroll event handler
const onScroll = () => {
// Get scroll value
const scroll = document.documentElement.scrollTop
// If scroll value is more than 0 - add class
if (scroll > 0) {
navbar.classList.add("scrolled");
} else {
navbar.classList.remove("scrolled")
}
}
// Use the function
window.addEventListener('scroll', onScroll)
#navbar {
position: fixed;
top: 0;
left: 0;
right: 0;
width: 100%;
height: 60px;
background-color: #89d0f7;
box-shadow: 0px 5px 0px rgba(0, 0, 0, 0);
transition: box-shadow 500ms;
}
#navbar.scrolled {
box-shadow: 0px 5px 10px rgba(0, 0, 0, 0.25);
}
#content {
height: 3000px;
margin-top: 60px;
}
<!-- Optional - lodash library, used for throttlin onScroll handler-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>
<header id="navbar"></header>
<div id="content"></div>
Some improvements
You'd probably want to throttle handling scroll events, more so as handler logic gets more complex, in that case throttle from lodash lib comes in handy.
And if you're doing spa, keep in mind that you need to clear event listeners with removeEventListener once they're not needed (eg during onDestroy lifecycle hook of your component, like destroyed() for Vue, or maybe return function of useEffect hook for React).
Example throttling with lodash:
// Throttling onScroll handler at 100ms with lodash
const throttledOnScroll = _.throttle(onScroll, 100, {})
// Use
window.addEventListener('scroll', throttledOnScroll)
Add some transition effect to it if you like:
http://jsbin.com/boreme/17/edit?html,css,js
.clearHeader {
height:50px;
background:lightblue;
position:fixed;
top:0;
left:0;
width:100%;
-webkit-transition: background 2s; /* For Safari 3.1 to 6.0 */
transition: background 2s;
}
.clearHeader.darkHeader {
background:#000;
}
Its my code
jQuery(document).ready(function(e) {
var WindowHeight = jQuery(window).height();
var load_element = 0;
//position of element
var scroll_position = jQuery('.product-bottom').offset().top;
var screen_height = jQuery(window).height();
var activation_offset = 0;
var max_scroll_height = jQuery('body').height() + screen_height;
var scroll_activation_point = scroll_position - (screen_height * activation_offset);
jQuery(window).on('scroll', function(e) {
var y_scroll_pos = window.pageYOffset;
var element_in_view = y_scroll_pos > scroll_activation_point;
var has_reached_bottom_of_page = max_scroll_height <= y_scroll_pos && !element_in_view;
if (element_in_view || has_reached_bottom_of_page) {
jQuery('.product-bottom').addClass("change");
} else {
jQuery('.product-bottom').removeClass("change");
}
});
});
Its working Fine
Is this value intended? if (scroll <= 500) { ... This means it's happening from 0 to 500, and not 500 and greater. In the original post you said "after the user scrolls down a little"
In a similar case, I wanted to avoid always calling addClass or removeClass due to performance issues. I've split the scroll handler function into two individual functions, used according to the current state. I also added a debounce functionality according to this article: https://developers.google.com/web/fundamentals/performance/rendering/debounce-your-input-handlers
var $header = jQuery( ".clearHeader" );
var appScroll = appScrollForward;
var appScrollPosition = 0;
var scheduledAnimationFrame = false;
function appScrollReverse() {
scheduledAnimationFrame = false;
if ( appScrollPosition > 500 )
return;
$header.removeClass( "darkHeader" );
appScroll = appScrollForward;
}
function appScrollForward() {
scheduledAnimationFrame = false;
if ( appScrollPosition < 500 )
return;
$header.addClass( "darkHeader" );
appScroll = appScrollReverse;
}
function appScrollHandler() {
appScrollPosition = window.pageYOffset;
if ( scheduledAnimationFrame )
return;
scheduledAnimationFrame = true;
requestAnimationFrame( appScroll );
}
jQuery( window ).scroll( appScrollHandler );
Maybe someone finds this helpful.
For Android mobile $(window).scroll(function() and $(document).scroll(function() may or may not work. So instead use the following.
jQuery(document.body).scroll(function() {
var scroll = jQuery(document.body).scrollTop();
if (scroll >= 300) {
//alert();
header.addClass("sticky");
} else {
header.removeClass('sticky');
}
});
This code worked for me. Hope it will help you.
This is based of of #shahzad-yousuf's answer, but I only needed to compress a menu when the user scrolled down. I used the reference point of the top container rolling "off screen" to initiate the "squish"
<script type="text/javascript">
$(document).ready(function (e) {
//position of element
var scroll_position = $('div.mainContainer').offset().top;
var scroll_activation_point = scroll_position;
$(window).on('scroll', function (e) {
var y_scroll_pos = window.pageYOffset;
var element_in_view = scroll_activation_point < y_scroll_pos;
if (element_in_view) {
$('body').addClass("toolbar-compressed ");
$('div.toolbar').addClass("toolbar-compressed ");
} else {
$('body').removeClass("toolbar-compressed ");
$('div.toolbar').removeClass("toolbar-compressed ");
}
});
}); </script>
I want text to bounce of the left and right sides of a div tag (#header). It works fine when it bounces of the right, then goes back and hits the left. The problem is that after it hits the left and starts to go right again it never hits the right side. It just keeps going and the window scrollbar appears. It appears as soon as it hits the left side. It seems that the div tag.
var finishedGoingRight = false;
setInterval(function() {
slideText();
}, 10);
function slideText(){
if(!finishedGoingRight){
$('#header h1').css("right","-=1");
}else{
$('#header h1').css("left","-=1");
}
if($('#header h1').css("right") == "20px"){
finishedGoingRight = true;
}
if($('#header h1').css("left") == "485px"){
finishedGoingRight = false;
}
}
Hope I explained it clearly :)
Debugging your code revealed that $('#header h1').css("right") always equals "auto", unless you've set it explicitly somewhere.
This works:
http://jsfiddle.net/7z3a3/1/
var finishedGoingRight = false;
setInterval(function() { slideText(); }, 10);
function slideText() {
if (!finishedGoingRight) {
$('#header h1').css("left", "+=1");
} else {
$('#header h1').css("left", "-=1");
}
if ($('#header h1').position().left >= $('#header').width()-$('#header h1').width()) {
finishedGoingRight = true;
} else if ($('#header h1').position().left <= 0) {
finishedGoingRight = false;
}
}
Here's my solution using animate:
JS:
var inner = $('#inner'), widthInner = inner.width(), outer = $('#outer'), widthOuter = outer.width();
function animateRight() {
inner.animate({ left: widthOuter - widthInner }, 1000, function() {
animateLeft();
});
}
function animateLeft() {
inner.animate({ left: 0 }, 1000, function() {
animateRight();
});
}
animateRight();
HTML
<div id="outer"><h2 id="inner">Inner</h2></div>
CSS
div, h2 { border: 1px solid black; }
#outer { width: 300px; height: 200px; }
#inner { margin-top: 75px; width: 50px; position: relative; }
http://jsfiddle.net/rHEQA/2/