Dynamic ScrollTo function requires next element - javascript

Please have a look at my example.
I have multiple rows on my website and a scrollto() button, wich is always at the bottom of the screen.
Depending on where the usere is located on my site at a certain moment, I would like him to move to the next row after he clicked the button.
I am aware of how to make a user scrollto(), but I have no clue what kind of selector I should use.
function myFunction() {
var winScroll = window.scrollTop; // current scroll of window
// find closest div
var rows = document.querySelectorAll('.row');
var closest = rows[0]; // first section
var closest_idx = 0;
var min = closest.offsetTop - winScroll;
rows.forEach(function(row, index) {
var divTopSpace = row.offsetTop - winScroll;
if( divTopSpace < min && divTopSpace > 0 ) {
closest = row;
closest_idx = index;
min = divTopSpace;
}
});
var next_idx = closest_idx + 1;
if (next_idx == rows.length) {
next_idx = 0;
}
console.log(rows[next_idx]);
}
.rowOne {
height: 100vh;
background-color: peachpuff;
}
.rowTwo {
height: 100vh;
background-color: firebrick;
}
.rowThree {
height: 100vh;
background-color: deepskyblue;
}
.btn {
position: fixed;
bottom: 0;
left: 0;
right: 0;
height: 30px;
}
<div class="main">
<div class="row rowOne">
<div class="a">
<div class="b">
Foo
</div>
</div>
</div>
<div class="row rowTwo">
<div class="a">
<div class="b">
Bar
</div>
</div>
</div>
<div class="row rowThree">
<div class="a">
<div class="b">
Foobar
</div>
</div>
</div>
<button id="btn" class="btn" onclick="myFunction()">Button</button>
</div>
Thank you in advance.

Since they are all the same height (100% of the window height), the simple solution would be to simply scroll by that amount.
window.scrollBy(0, window.innerHeight);
Otherwise, you'll need to detect which element is the "current" one, and then get it's next sibling, and then scroll to it. Something like this (haven't tested, so syntax might be off, but this should give you an idea)
var winScroll = window.scrollTop; // current scroll of window
// find closest div
var rows = document.querySelectorAll('.row');
var closest = rows[0]; // first section
var closest_idx = 0;
var min = closest.offsetTop - winScroll;
rows.forEach(function(row, index) {
var divTopSpace = row.offsetTop - winScroll;
if( divTopSpave < min && divTopSpave > 0 ) {
closest = row;
closest_idx = index;
min = divTopSpace;
}
});
var next_idx = closest_idx + 1;
if (next_idx == rows.length) {
next_idx = 0;
}
window.scrollTo(rows[next_idx].scrollTop);

Related

How to detect correct div data attribute when each hitting the top of the page

I am working on the below code. Why am I not able to detect which div is reaching at the top of page in both down or up scroll?
$(window).scroll(function() {
$(".container").each(function() {
var $that = $(this);
var po = $(this).offset().top;
if (po >= 0 && po <= 300) {
console.log($that.data('map'));
}
});
});
.container {
height: 690px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container" data-map="One">One</div>
<div class="container" data-map="Two">Tow</div>
<div class="container" data-map="Three">Three</div>
<div class="container" data-map="Four">Four</div>
<div class="container" data-map="Five">Five</div>
You'll need to use $(window).scrollTop(); as well as $that.outerHeight()
$(window).scroll(function() {
var windowScrollTop = $(this).scrollTop(); // window scroll top
$(".container").each(function() {
var $that = $(this);
var po = $that.offset().top;
var poHeight = $that.outerHeight(true); // the height of the element
var distanceTop = 100; // the distance from top to run the action .. it can be 0 if you want to run the action when the element hit the 0 top
if (windowScrollTop + distanceTop >= po && windowScrollTop + distanceTop <= po + poHeight) {
if(!$that.hasClass('red')){ // if element dosen't has class red
console.log($that.data('map'));
$(".container").not($that).removeClass('red'); // remove red class from all
$that.addClass('red'); // add red class to $that
}
}
});
}).scroll(); // run the scroll onload
.container {
height: 690px;
}
.container.red{
background : red;
color : #fff;
font-size: 30px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container" data-map="One">One</div>
<div class="container" data-map="Two">Two</div>
<div class="container" data-map="Three">Three</div>
<div class="container" data-map="Four">Four</div>
<div class="container" data-map="Five">Five</div>

Why does one calculation for my onClick get applied to all elements that I'm looping through

Currently doing some exercise for CSS/Javascript animation. I'm attempting to make a Carousel slider from scratch.. I have 4 divs with 550px in width nested in a wrapper of 2200px, which is then nested in a 550px wrapper with overflow hidden.
I then created 4 LI's that I want to make clickable so that it'll translate the wrapper -550*I degrees for every LI.
I performed a queryselectorall to get all the li's, looped through it with a for loop, and created a function that should apply onclick functionality for each LI button.
The issue that I'm running into is that the first calculation of this transform property is applied to all LI's (the 550 * i for [1] [2] and [3] aren't applied).
Here's the HTML that I'm currently using.
<div id="container">
<div id="wrapper">
<div id="itemOne" >
</div>
<div id="itemTwo">
</div>
<div id="itemThree">
</div>
<div id="itemFour">
</div>
</div>
</div>
<ul>
<li class="button"></li>
<li class="button"></li>
<li class="button"></li>
<li class="button"></li>
</ul>
The Javascript
var wrapper = document.querySelector("#wrapper");
var buttons = document.querySelectorAll(".button");
for(var i = 0; i < buttons.length; i++){
var curBut = buttons[i];
curBut.addEventListener("click", function(){
wrapper.style[transformProperty] = 'translate3d(-'+((0-i) * 550) +'px,0,0'
})
console.log(((0-i) * 550));
}
console.log(buttons);
var transforms = ["transform",
"msTransform",
"webkitTransform",
"mozTransform",
"oTransform"];
var transformProperty = getSupportedPropertyName(transforms);
function getSupportedPropertyName(properties) {
for (var i = 0; i < properties.length; i++){
if(typeof document.body.style[properties[i]] != "undefined") {
return properties[i];
}
}
return null;
}
If anyone could explain why the function isn't applying the different changes for the wrapper for each LI, that'd be great! Thanks!!
The global variable i is not copied into each listener, it's shared between the listeners. When you click a button, i is already set to its final value which is 4. As a possible workaround you could override the global variable with a local variable, and get the index on click using indexOf :
var wrapper = document.querySelector("#wrapper");
var buttons = document.querySelectorAll("button");
for (var i = 0; i < buttons.length; i++) {
var curBut = buttons[i];
curBut.addEventListener("click", function() {
var i = Array.prototype.indexOf.call(buttons, this);
wrapper.style[transformProperty] = 'translate3d(-' + (i * 260) + 'px,0,0)';
});
}
var transforms = ["transform",
"msTransform",
"webkitTransform",
"mozTransform",
"oTransform"];
var transformProperty = getSupportedPropertyName(transforms);
function getSupportedPropertyName(properties) {
for (var i = 0; i < properties.length; i++) {
if (typeof document.body.style[properties[i]] != "undefined") {
return properties[i];
}
}
return null;
}
#container {
overflow: hidden;
background: gray;
margin-bottom: 1em;
width: 260px;
height: 100px;
}
#wrapper {
width: calc(4 * 260px);
height: 100px;
}
#wrapper div {
padding: 0 1em;
width: calc(260px - 2em);
line-height: 100px;
height: 100px;
float: left;
color: white;
font-size: 3em;
font-weight: bold;
text-align: center;
}
<div id="container">
<div id="wrapper">
<div id="itemOne">1</div>
<div id="itemTwo">2</div>
<div id="itemThree">3</div>
<div id="itemFour">4</div>
</div>
</div>
<div>
<button type="button">button 1</button>
<button type="button">button 2</button>
<button type="button">button 3</button>
<button type="button">button 4</button>
</div>

How to get all HTML elements 500px below viewport using Javascript

I am trying to get all the HTML elements(div with particular id) which are there 500px below viewport on the page. I want to have this on scroll event.
var windowHeight = window.outerHeight;
var gridTop = windowHeight + 500;
var elements = document.getElementsByClassName('test');
window.addEventListener('scroll', function () {
for (let i = 0; i < elements.length; i++) {
var thisTop = elements[i].offsetTop - document.body.scrollTop;
if (thisTop >= gridTop) {
console.log('hi');
}
}
});
I need help on finding elements 500px below viewport.
EDIT:
I want to do it with pure JavaScript and I am using above code. But every time I am getting thisTop as 0. Please let me know the approach to do this.
Check following solution, here I put parent div which is scrollable.
Note- I have put offset of 50px, in order to support the example.
var parent = document.documentElement
var elements = document.getElementsByClassName('test');
var gridTop = parent.clientHeight + 50;
window.addEventListener('scroll', function() {
var printStr = "";
for (let i = 0; i < elements.length; i++) {
var thisTop = elements[i].offsetTop - parent.scrollTop;
if (thisTop >= gridTop) {
printStr += " "+elements[i].id
}
}
console.clear();
console.log('selected ', printStr);
});
.container div {
width: 40px;
height: 70px;
margin: 5px;
background-color: red;
text-align: center;
}
<div class="container">
<div class="test" id="1">1</div>
<div class="test" id="2">2</div>
<div class="test" id="3">3</div>
<div class="test" id="4">4</div>
<div class="test" id="5">5</div>
<div class="test" id="6">6</div>
<div class="test" id="7">7</div>
<div class="test" id="8">8</div>
<div class="test" id="9">9</div>
<div class="test" id="10">10</div>
<div class="test" id="11">11</div>
<div class="test" id="12">12</div>
</div>
You should not set multiple elements to have the same ID.
It will have a conflict in your js.
If you want to identify a set of DIVs, you should use CLASS instead.
Here, what I did was to find all elements classed as some-class-name iterated through the list,
Then get their width, both style.width and offsetWidth
<div id="the_900px_div" class="some-class-name" style="width:900px;border:1px solid blue;"></div>
<div id="the_200px_div" class="some-class-name" style="width:200px;border:1px solid blue;"></div>
<div id="the_100px_div" class="some-class-name" style="width:100px;border:1px solid red;"></div>
<script type="text/javascript">
function autorun()
{
var elements = document.getElementsByClassName('some-class-name');
var elementsLength = elements.length;
console.log(elements);
for (var i = 0; i < elementsLength; i++){
var sw = elements[i].style.width.replace('px','');
var ow = elements[i].offsetWidth;
var id = elements[i].id;
console.log(sw > 500)
console.log(id + ' style.width is ' + sw + 'px')
console.log(ow > 500)
console.log(id + ' offsetWidth is ' + ow + 'px')
}
}
if (document.addEventListener) document.addEventListener("DOMContentLoaded", autorun, false);
else if (document.attachEvent) document.attachEvent("onreadystatechange", autorun);
else window.onload = autorun;
</script>

Use editable div height change to add and remove classes to other DOM elements

I have and editable div that allow users to enter text. This is part of a chat widget so the design needs the box to be fixed to the bottom.
When a user types I need javascript to catch the resize and append classes to elements where needed.
I managed to get the box to resize upwards but I have had a lot of trouble scaling it back down again.
I have been stuck on this for days now, so any help now would be greatly appreciated.
I have the function and a basic UI version here JSFiddle
Its probably really simple but I am having no luck figuring this out
JSFiddle
var chatBoxSize = {
oldHeight : 0,
scrollHeight : 0,
lastClass : 1,
minClass : 1,
maxClass : 5,
min_height : 0,
last_size : 0,
getClass : function (size){
var sizes = [chatBoxSize.min_height, chatBoxSize.min_height * 2, chatBoxSize.min_height * 3, chatBoxSize.min_height * 4, chatBoxSize.min_height * 5];
switch (size){ case sizes[0] : return 1; break; case sizes[1] : return 2; break; case sizes[2] : return 3; break; case sizes[3] : return 4; break; case sizes[4] : return 5; break; };
//is not exact
var r = null;
console.log(size);
for(var x = 0; x < sizes.length; x++){
if(x < sizes.length){
if(size >= sizes[x] && size < sizes[(x + 1)]){
return (x + 1);
}
}
}
return chatBoxSize.maxClass;
}
};
$(function () {
chatBoxSize.min_height = parseInt($('#msgWriteArea').height());
chatBoxSize.max_height = chatBoxSize.min_height * 4;
chatBoxSize.last_size = chatBoxSize.min_height;
});
function updateChatSize() {
var id = '#msgWriteArea';
var element = document.querySelector(id);
var size = $(id)[0].scrollHeight;
var container = $('.container');
var toRemove = 'size_' + chatBoxSize.lastClass;
console.log(chatBoxSize.getClass(size));
chatBoxSize.lastClass = chatBoxSize.getClass(size);
console.log('Add new class', chatBoxSize.lastClass);
chatBoxSize.last_size = size;
$(id).removeClass(toRemove);
$(id).addClass('size_' + chatBoxSize.lastClass);
container.removeClass(toRemove);
container.addClass('size_' + chatBoxSize.lastClass);
$('#display').val('Removed ' + toRemove + ' Added ' + chatBoxSize.lastClass);
};
$(function (){
$('#msgWriteArea').bind('change keydown input', function () {
if(event.type == 'keydown'){
updateChatSize();
}
});
})
I have thought of just setting the heights to auto but that will not work with the rest of the ui elements.
Sorry to say but No JS needed at all
flex to the rescue, overflow-y: auto; and max-height to the editable DIV:
Heres a jsBin demo so you can play and resize the browser
*{box-sizing:border-box; -webkit-box-sizing:border-box;}
html, body{height:100%; margin:0;font:16px/1 sans-serif; color:#444;}
#chat{
display: flex;
flex-direction: column;
height:100%;
}
#messages{
flex:1;
overflow-y: auto;
}
#messages > div{
padding: 24px;
background: #eef;
margin: 4px 0;
}
#ui{
background: #eee;
}
#msgWriteArea{
padding: 24px;
overflow-y: auto;
height:100%;
background:#ddd;
max-height:100px; /* if max height is exceeded */
overflow-y: auto; /* add scrollbars */
}
<div id="chat">
<div id="messages">
<div>Message 1</div>
<div>Message 2</div>
<div>Message 3</div>
<div>Message 4</div>
<div>Message 5</div>
<div>Message 6</div>
</div>
<div id="ui">
<div id="msgWriteArea" contenteditable>Some text message</div>
</div>
</div>
Now, if you still really need to the the message area height (for some reasons) you could count the number of lines using JS.

EBAY slideshow in Javascript tweak required

I have been searching for a slideshow script that works with Ebay, and found http://xlo.co/blog/web-development/javascript-image-fade?quip_thread=blog-post-19&quip_parent=76 this one that seemed to work ok. I wanted to add a third image to the slideshow and that's when things started going south. The following is the code that I altered from the original page to add the third image.
I've put beside any of the code that I inserted. It works, however, the transitions stop working after the first image. If any one can help, it would be greatly appreaciated.
<div id="test">alpha</div>
<div id="slides" style="display: none;">
<div id="slide0" style="background-image: url('/ebay/images/image1.jpg'); width: 670px; height: 240px;">Content0</div>
<div id="slide1" style="background-image: url('/ebay/images/image1.jpg'); width: 670px; height: 240px;">Content1</div>
<!--ADDITION --><div id="slide2" style="background-image: url('/ebay/images/image1.jpg'); width: 670px; height: 240px;">Content2</div>
</div>
<div id="transition" style="width: 670px; height: 240px;">
<!--ADDITION --><div id="imageholder2" style="position: absolute;"></div>
<div id="imageholder1" style="position: absolute;"></div>
<div id="imageholder0" style="position: absolute;"></div>
<!--first last to avoid messing with z-indices-->
</div>
<!-- SCRIPT FUNCTION -->
<script type="text/javascript">
// <![CDATA[
//image transition
var interval = 3000;
var fadeTime = 10;
var currentImage;
var alpha = 100;
var images = new Array();
images[0]=document.getElementById('slide0');
images[1]=document.getElementById('slide1');
<!--ADDITION -->images[2]=document.getElementById('slide2');
var image0Holder = document.getElementById('imageholder0');;
var image1Holder = document.getElementById('imageholder1');;
<!--ADDITION -->var image2Holder = document.getElementById('imageholder2');;
var currentImageHolder = image0Holder;
var currentImage = 0;
var testId = document.getElementById('test');
image0Holder.appendChild(images[0]);
image1Holder.appendChild(images[1]);
<!--ADDITION -->image2Holder.appendChild(images[2]);
function transition() {
function fade() {
if (alpha > 0) {
alpha = alpha - 1;
document.getElementById('test').innerHTML = alpha;
currentImageHolder.style.opacity = (alpha/100);
currentImageHolder.style.MozOpacity = currentImageHolder.style.opacity;
currentImageHolder.style.filter = 'alpha(opacity='+alpha+')';
}
else {
clearInterval(timer0);
document.getElementById('test').innerHTML = "xx";
if (currentImage == image0Holder) {
image0Holder.style.zIndex = 0;
image1Holder.style.zIndex = 1;
<!--ADDITION -->image2Holder.style.zIndex = 2;
alpha = 100;
currentImageHolder.style.opacity = (alpha/100);
currentImageHolder.style.MozOpacity = currentImageHolder.style.opacity;
currentImageHolder.style.filter = 'alpha(opacity='+alpha+')';
currentImageHolder = image1Holder;
image0Holder.removeChild(image0Holder.lastChild);
image0Holder.appendChild(images[currentImage]);
}
else {
image0Holder.style.zIndex = 2;
image1Holder.style.zIndex = 1;
<!--ADDITION -->image2Holder.style.zIndex = 0;
alpha = 100;
currentImageHolder.style.opacity = (alpha/100);
currentImageHolder.style.MozOpacity = currentImageHolder.style.opacity;
currentImageHolder.style.filter = 'alpha(opacity='+alpha+')';
currentImageHolder = image0Holder;
image1Holder.removeChild(image1Holder.lastChild);
image1Holder.appendChild(images[currentImage]);
}
currentImage = (currentImage+1)%images.length;
timer1 = setTimeout(transition, interval);
}
}
timer0 = setInterval(fade, 20);
}
timer1 = setTimeout(transition, interval);
// ]]>
</script>

Categories

Resources