I am looking for way to make page scroll on menu click.
My found place where to go. When I use translateY it work(but ofcouse I can't use it).
I need a scroll I tried to use scrollTop and scrollBy but it doesn't work for me.
What I do wrong?
function scroll(id: number) {
for (let k = 0; k < sectionsForScroll.length; k++) {
if (sectionsForScroll[k].dataset.navId == id) {
const bigginer = sectionsForScroll[0].getBoundingClientRect().top;
console.log( bigginer + 'px how far we from the start ');
const distanceToGo= sectionsForScroll[k].getBoundingClientRect().top;
console.log(sectionsForScroll[k].offsetTop);
const distanceToScroll = bigginer - distanceToGo;
console.log(distanceToGo + ' where we have to go ');
console.log(distanceToScroll + ' what the distanse we need to scroll ');
main.style.transform = 'translateY(' + distanceToScroll + 'px)';
// main.scrollTop=distanceToGo;
// window.scrollBy(0, distanceToGo);
}
}
}
window.scroll will work for you. Here is an example of scrolling 300px after clicking the scroll button.
Before using it you should checkout the compatibility table for the smooth option.
document.getElementById("myButton").addEventListener("click", scrollMe);
function scrollMe() {
window.scroll({
top: 300,
left: 0,
behavior: 'smooth'
});
}
.myDiv {
background-color: green;
height: 1000px;
}
<div class="myDiv">
<button id="myButton">Scroll</button>
</div>
Related
Is it possible to make a <button> (<input type="button">) work with HTML5 drag and drop in Mozilla Firefox (while still being clickable)?
The following snippet works in Google Chrome but the button and div with button cannot be dragged Mozilla Firefox (unless the Alt key is pressed down, no idea about mobile):
document.getElementById("myDiv").addEventListener(
"dragstart",
function (e) {
e.dataTransfer.setData("Text", "myDiv")
}
);
document.getElementById("myButton").addEventListener(
"dragstart",
function (e) {
e.dataTransfer.setData("Text", "myButton")
}
);
document.getElementById("myDivWithButton").addEventListener(
"dragstart",
function (e) {
e.dataTransfer.setData("Text", "myDivWithButton")
}
);
<div id="myDiv" draggable="true">Div</div>
<button id="myButton" draggable="true">Button</button>
<div id="myDivWithButton" draggable="true"><button>Div with Button</button></div>
I used draggable="true" and dataTransfer.setData, is there something I missed? Is there some sensible workaround?
(If you want to know what I need this for: I have something which can be either dragged at a certain position or set at the default position [center of current view], my idea was to do both through the button [d&d → choose position, click → default position]. I know that I guess I could try to format a <div> to make it look like a <button> or simply split the control into two elements but I'd rather not.)
There is already a bug on Firefox where you can't drag a button.
https://bugzilla.mozilla.org/show_bug.cgi?id=568313
However you can drag your div containing button (which is not draggable right now) using 'after' pseudo class.
Example:
document.getElementById("myDivWithButton").addEventListener(
"dragstart",
function (e) {
e.dataTransfer.setData("Text", "myDivWithButton")
}
);
.frontdrop {
position: relative;
}
.frontdrop:after {
content: '';
top: 0;
left: 0;
right: 0;
bottom: 0;
position: absolute;
}
<div id="myDivWithButton" class="frontdrop" draggable="true"><button>Div with Button</button></div>
I found a tricky solution:
<label draggable="true" ondragstart="event.dataTransfer.setData('text/plain', '')">
<input type="button" value="Click me!" style="pointer-events: none" onclick="console.log(event)">
</label>
Wrap input with a draggable label and set pointer-events CSS property to none. Using this method, your button will be interactive and draggable.
From others, I came to know that your issue is because of a bug exists in Firefox. I suggest you to implement custom listeners to imitate drag event.
My solution is as follows:
var btn = document.getElementById('btn');
var btnPressed = false;
btn.addEventListener('mousedown', function(e) {
btnPressed = true;
px = e.clientX;
py = e.clientY;
});
btn.addEventListener('mouseup', function(e) {
btnPressed = false;
})
window.addEventListener('mouseup', function(e) {
btn.style.MozTransform = "";
btn.style.WebkitTransform = "";
btn.style.opacity = 1;
})
window.addEventListener('mousemove', function(e) {
if(btnPressed) {
dx = e.clientX - px;
dy = e.clientY - py;
btn.style.opacity = 0.85;
btn.style.MozTransform = "translate(" + dx + "px, " + dy + "px)";
btn.style.WebkitTransform = "translate(" + dx + "px, " + dy + "px)";
}
})
<button id="btn">Drag Me</button>
I know its not perfect. Hard-coding is the only way to resolve this issue until Firefox fix this bug.
You can give a little ledge that is draggable next to the button.
.frontdrop:after {
content: '';
top: 0;
left: 0;
right: 20;
bottom: 0;
border-width="1";
border-style: solid;
position: absolute;
}
I'm trying to add two .height()'s together in order to get a responsive number for my onScroll event how do I add two of these together?
I'm general, I'm just trying to get the animation to fire after getting to the bottom of everything above the element. Is there any other way to do that besides just adding the heights of everything above?
window.addEventListener('load', function() {
$(window).scroll(function() {
var eventScroll = window.pageYOffset;
var eventScrollAmount = ($("#sectionOneImage").height() + $("#bannerOne").height());
if( eventScroll > eventScrollAmount) {
$("#sectionOneImage").addClass("animated slideInLeft ");
}
else {
$("#sectionOneImage").removeClass("animated slideInLeft ");
}
});
});
Here's an example of how to grab two heights using vanilla JS.
var sizeOfOne = document.getElementById('one').offsetHeight;
var sizeOfTwo = document.getElementById('two').offsetHeight;
document.getElementById('hook').innerHTML = 'The first div is ' + sizeOfOne + ' pixels in height, the second div is ' + sizeOfTwo + ' pixels in height. The total size of both div\'s are ' + (sizeOfOne + sizeOfTwo) + ' pixels.';
#one {
height: 50px;
background: red;
}
#two {
height: 75px;
background: blue;
}
<div id="hook"></div>
<div id="one"></div>
<div id="two"></div>
I'm trying to fade in/out and fix the blue div on the left when scrolled relative to the image blocks on the right.
http://www.warface.co.uk/#/testing/
pass: squared
.meta { /*This is the block I'm trying to stick/*
background: blue;
position: fixed;
width: 372px;
float: left;
z-index: 3;
right: 100%;
}
Here is the basics in JavaScript:
function controlMeta() {
var meta = document.querySelector("div.meta");
console.log(meta);
if (window.scrollY > 500) {
meta.style.display = "none";
} else {
meta.style.display = "block";
}
}
window.addEventListener("scroll", function () {
controlMeta();
})
You can get your elements scroll position with something like this:
document.getElementById("57513a9220c6475fb77061c5").getBoundingClientRect().top+window.scrollY
EDIT 1
Here is a method for associating elements with the meta box, based upon the previous:
//Load elements that affect the meta box
var meta = [];
var images = document.querySelector('.sqs-gallery').getElementsByTagName('img');
for (var i = 0; i < images.length; i++) {
meta.push({
node : images[i],
height : images[i].height,
//top is used with scroll position to determine which element we are looking at
top : images[i].getBoundingClientRect().top + window.scrollY
});
}
function controlMeta() {
meta.filter(function (el) {
//You might need to pad your filter a little
return window.scrollY < el.top && window.scrollY > el.top - el.height;
}).forEach(function (el) {
//These are the matching elements. I'm just fetching the src as an example
document.querySelector("div.meta div.body").innerHTML = el.node.src;
});
}
window.addEventListener("scroll", function () {
controlMeta();
});
I am using jquery function element.scrollTop() to get the current scroll position of the page using following line:
var currentScrollPosition= $('html').scrollTop() || $('body').scrollTop();
But it always return a value of previous scroll position. Please check the code below (which is same as is in here).
As you can try yourself and see in the code, after each tiny scroll, we get following series of values:
(1: when code is first run and no move is made yet)
delta:0
cumulativeDelta:0
functionCallCount:0
currentScrollPosition:0
(delta gives how much is scrolled, cumulativeDelta gives total amount of scroll, functionCallCount is how many times you scrolled and currentScrollPosition is value returned by scrolltop() )
(2: when scrolled a little)
delta:-120
cumulativeDelta:-120
functionCallCount:1
currentScrollPosition:0
(note here, currentScrollPosition is still not updated)
(3: when scrolled a little further)
delta:-120
cumulativeDelta:-240
functionCallCount:2
currentScrollPosition:90.90908893868948
(here, cumulativeDelta, which is addition of total scroll made so far, is doubled and currentScrollPosition is updated for the first time)
(4: when scrolled a little more)
delta:-120
cumulativeDelta:-360
functionCallCount:3
currentScrollPosition:181.81817787737896
(now, cumulativeDelta is tripled while currentScrollPosition is doubled. Hence, this is value after two scrolls but is updated adter 3 scrolls)
I apologize for long question, but would have been difficult to ask otherwise. I would like to know why is this happening and if I should use this function some other way there are any alternative to this function.
document.addEventListener("mousewheel", MouseWheelHandler);
var cumulativeDelta = 0,
functionCallCount = 0;
function MouseWheelHandler(e) {
e = window.event || e; // 'event' with old IE support
var delta = e.wheelDelta || -e.detail; // get delta value
cumulativeDelta += delta;
functionCallCount += 1;
currentScrollPosition = $('html').scrollTop() || $('body').scrollTop();
document.getElementById("info1").innerHTML = "delta:" + delta;
document.getElementById("info2").innerHTML = "cumulativeDelta:" + cumulativeDelta;
document.getElementById("info3").innerHTML = "functionCallCount:" + functionCallCount;
document.getElementById("info4").innerHTML = "currentScrollPosition:" + currentScrollPosition;
}
body {
height: 2000px;
border: solid red 3px;
}
.normalPart {
border: solid green 2px;
height: 900px;
}
.stationary {
position: fixed;
top: 0px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<div class="stationary">
<div id="info1"></div>
<div id="info2"></div>
<div id="info3"></div>
<div id="info4"></div>
</div>
The issue is because the mousewheel event fires when the mousewheel movement starts. You are reading the scrollTop at the point before the update has happened. You need to use a timer to get the scrollTop after the mouse wheel scroll has finished. Try this:
document.addEventListener("mousewheel", MouseWheelHandler);
var cumulativeDelta = 0,
functionCallCount = 0,
currentScrollPosition = 0;
function MouseWheelHandler(e) {
e = window.event || e; // 'event' with old IE support
var delta = e.wheelDelta || -e.detail; // get delta value
cumulativeDelta += delta;
functionCallCount += 1;
setTimeout(function() {
currentScrollPosition = $(window).scrollTop();
document.getElementById("info4").innerHTML = "currentScrollPosition:" + currentScrollPosition;
}, 200); // update currentScrollPos 200ms after event fires
document.getElementById("info1").innerHTML = "delta:" + delta;
document.getElementById("info2").innerHTML = "cumulativeDelta:" + cumulativeDelta;
document.getElementById("info3").innerHTML = "functionCallCount:" + functionCallCount;
}
body {
height: 2000px;
border: solid red 3px;
}
.normalPart {
border: solid green 2px;
height: 900px;
}
.stationary {
position: fixed;
top: 0px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<div class="stationary">
<div id="info1"></div>
<div id="info2"></div>
<div id="info3"></div>
<div id="info4"></div>
</div>
Alternatively you could read the currentScrollTop position directly on the scroll event of the window as that will always be in sync with its current position.
I would listen for the scroll event instead of wheel. Scroll activates after the scrollTop value has been updated.
target.onscroll = functionRef
Great example here
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>