How to get all HTML elements 500px below viewport using Javascript - 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>

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>

Dynamic ScrollTo function requires next element

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);

How to check if element is in viewport (div, no window)

Is there any way to check if specified html element is in viewport - no window but specified div? I found only one meaningful solution but I can't make it work for me.
According to this question Check if element is visible in div
I created a example here: http://jsfiddle.net/jm91n80u/
This is my html code:
<body style="overflow:hidden;">
<div id="outer" style="position:absolute;left:150px;top:20px;right:100px;bottom:30px;overflow:hidden;border:1px solid blue;">
<div id="inner" style="position:relative;height:300px;border:1px solid red;width:100px;overflow-y:auto;overflow-x:hidden;">
<div style="position:relative;width:100%;height:30px;border:1px solid grey;" class="test">1</div>
<div style="position:relative;width:100%;height:30px;border:1px solid grey;" class="test">2</div>
<div style="position:relative;width:100%;height:30px;border:1px solid grey;" class="test">3</div>
<div style="position:relative;width:100%;height:30px;border:1px solid grey;background:yellow;" class="test" id="id1">4</div>
<div style="position:relative;width:100%;height:30px;border:1px solid grey;" class="test">5</div>
<div style="position:relative;width:100%;height:30px;border:1px solid grey;" class="test">6</div>
<div style="position:relative;width:100%;height:30px;border:1px solid grey;" class="test">7</div>
<div style="position:relative;width:100%;height:30px;border:1px solid grey;" class="test">8</div>
<div style="position:relative;width:100%;height:30px;border:1px solid grey;" class="test">9</div>
<div style="position:relative;width:100%;height:30px;border:1px solid grey;" class="test">10</div>
<div style="position:relative;width:100%;height:30px;border:1px solid grey;" class="test">11</div>
<div style="position:relative;width:100%;height:30px;border:1px solid grey;" class="test">12</div>
<div style="position:relative;width:100%;height:30px;border:1px solid grey;" class="test">13</div>
<div style="position:relative;width:100%;height:30px;border:1px solid grey;" class="test">14</div>
</div>
</div>
<div id="result" style="position:absolute;bottom:0px;overflow:hidden;border:1px solid black;height:20px;width:100%;"></div>
</body>
This is a js function
$(document).ready(function () {
$.belowthefold = function (lookIn, elements, settings) {
var fold = $(lookIn).height() + $(lookIn).scrollTop();
return $(elements).filter(function () {
return fold <= $(this).offset().top - settings.threshold;
});
};
$.abovethetop = function (lookIn, elements, settings) {
var top = $(lookIn).scrollTop();
return $(elements).filter(function () {
return top >= $(this).offset().top + $(this).height() - settings.threshold;
});
};
$.rightofscreen = function (lookIn, elements, settings) {
var fold = $(lookIn).width() + $(lookIn).scrollLeft() + $(lookIn).offset().width;
return $(elements).filter(function () {
return fold <= $(this).offset().left - settings.threshold;
});
};
$.leftofscreen = function (lookIn, elements, settings) {
var left = $(lookIn).scrollLeft();
return $(elements).filter(function () {
return left >= $(this).offset().left + $(this).width() - settings.threshold;
});
};
$("#inner").scrollTop(100);
var b = $.belowthefold("#inner", ".test", { threshold: 0 }).toArray();
var t = $.abovethetop("#inner", ".test", { threshold: 0 }).toArray();
var r = $.rightofscreen("#inner", ".test", { threshold: 0 }).toArray();
var l = $.leftofscreen("#inner", ".test", { threshold: 0 }).toArray();
var el = $("#id1")[0];
var bS = "below the fold : ";
for (var i = 0; i < b.length; i++) {
bS += $(b[i]).html() + ",";
}
var tS = "above the top : ";
for (var i = 0; i < t.length; i++) {
tS += $(t[i]).html() + ",";
}
var rS = "right of screen : ";
for (var i = 0; i < r.length; i++) {
rS += $(r[i]).html() + ",";
}
var lS = "left of screen : ";
for (var i = 0; i < l.length; i++) {
lS += $(l[i]).html() + ",";
}
console.log(bS);
console.log(tS);
console.log(rS);
console.log(lS);
});
What I'm trying to do is get all '.test' elements which are currently invisible (or partial invisible in target solution, any switch will be appreciated) in inner container with information about their position. The result of this should be:
below the fold : 13, 14
above the top : 1,2,3,4
right of screen :
left of screen :
But in this particular case those functions doesn't work. I tried use several other solutions, but each one treats viewport as window.
Can you explain what am I doing wrong? Any help will be appreciated.
You should compare div's positions to: viewport size and windows bounds.
Roughly : if(div.top > (window.top + viewport.height )) {/*this is visible*/} else {/*this is not visible*/}
You could even make it more specific (how much area of div ?)
if((div.top **+ 50% of div.height**) > (window.top + viewport.height )) {/*this is visible*/}
This post gives some codes Check if element is between 30% and 60% of the viewport
$(document).ready(function() {
// Get viewport height, gridTop and gridBottom
var windowHeight = $(window).height(),
gridTop = windowHeight * .3,
gridBottom = windowHeight * .6;
$(window).on('scroll', function() {
// On each scroll check if `li` is in interested viewport
$('ul li').each(function() {
var thisTop = $(this).offset().top - $(window).scrollTop(); // Get the `top` of this `li`
// Check if this element is in the interested viewport
if (thisTop >= gridTop && (thisTop + $(this).height()) <= gridBottom) {
$(this).css('background', 'red');
} else {
$(this).css('background', 'gray');
}
});
});
});

css apply style if parent width more than specific value

Want to apply css selectors if only parent element width more than specific value.
CSS must not use media query to implement this because no relation between viewport width and the parent div width.
Javascript is welcome but avoid continuous width check please.
Ex.
<style>
/* something like that div[width>400px] */
.parent div[width>400px]{
background:red;
}
</style>
<!--ok width is more than 400 so apply style to child div-->
<div class="parent" style="width:500px;">
<div>
</div>
</div>
<!--width is still less than 400 so don;t apply styles-->
<div class="parent" style="width:300px;">
<div>
</div>
</div>
The Resize event only works on the window element.
Vanilla JavaScript would be something like this.
var parentDivTriggrtWidth = 400;
var childDivClassNames = ["red", "blue"];
window.addEventListener("load", function(e){
var list = document.getElementsByClassName("parent");
for(var i=0; i<list.length; i++){
var parentDiv = list[i];
parentDiv.resizeParent = function(width){
if(typeof width!="undefined"){ this.style.width = width+"px"; }
var k = this.clientWidth > parentDivTriggrtWidth ? 1 : 0;
this.children[0].className = childDivClassNames[k];
// Debug only
this.children[0].innerHTML = "Parent Size: "+this.clientWidth+"<br />Class: "+this.children[0].className;
}
window.addEventListener("resize", function(e){ parentDiv.resizeParent(); },false);
parentDiv.resizeParent();
}
},false);
Look at the snippet in "fullpage"
var parentDivTriggrtWidth = 400;
var childDivClassNames = ["red", "blue"];
window.addEventListener("load", function(e){
var list = document.getElementsByClassName("parent");
for(var i=0; i<list.length; i++){
var parentDiv = list[i];
parentDiv.resizeParent = function(width){
if(typeof width!="undefined"){ this.style.width = width+"px"; }
var k = this.clientWidth > parentDivTriggrtWidth ? 1 : 0;
this.children[0].className = childDivClassNames[k];
// Debug only
this.children[0].innerHTML = "Parent Size: "+this.clientWidth+"<br />Class: "+this.children[0].className;
}
window.addEventListener("resize", function(e){ parentDiv.resizeParent(); },false);
parentDiv.resizeParent();
}
},false);
.parent {
border: 3px solid #aaaaaa;
}
.parent div {
width: 200px;
height: 200px;
color: white
}
.red {
background-color: red;
}
.blue {
background-color: blue;
}
<h3>width 500px (resize by JavaScript)</h3>
<div id="p1" class="parent" style="width:500px;">
<div></div>
</div>
<button type="button" onclick="document.getElementById('p1').resizeParent(800)">Resize +</button>
<button type="button" onclick="document.getElementById('p1').resizeParent(200)">Resize -</button>
<button type="button" onclick="document.getElementById('p1').resizeParent(500)">Reset</button>
<hr />
<h3>width 100% (resize window)</h3>
<!--width is still less than 400 so don;t apply styles-->
<div id="p2" class="parent" style="width:100%;">
<div></div>
</div>
jQuery is an option :
$( document ).ready(function() {
if ($(".parent").width() > 700) {
$('.parent').css("background-color", "red");
}
});
if i got you right...
JQuery:
$(document).ready(function(){
var ParentWidth = $('.parent').width();
if (ParentWidth > 400) {
$('.parent').addClass('newstyle');
}
});
CSS:
.newstyle
{
background: red;
/*** add more css ***/
}
i Recommends you to use class because you can add more css to the class later.

Could help me to resolve mouse events?

<script>
var theNumOfWins;
var part;
theNumOfWins = 0;
function openWindow(){
part = partOfWindow("outlayer",theNumOfWins,"section0");
setCSS(part.css,"-1","400px","400px","#65A8E8","relative","30px","30px","initial","none");
part = partOfWindow("headerOfWindow",theNumOfWins,part.id);
setCSS(part.css,"1","400px","25px","#65A8E8","relative","0px","0px","initial","none");
part = partOfWindow("zoneOfWindowPosition",theNumOfWins,part.id);
setCSS(part.css,"1","204px","22px","transparent","absolute","192px","4px","move","1px solid red");
document.getElementById("5").innerHTML = document.getElementById(part.id).attributes[2].value;
theNumOfWins++;
}
function partOfWindow(name,theNumOfWins,parent){
var id;
var css;
var idAndCSS;
var tag;
var att;
id = name + "Id" + theNumOfWins;
css = name + "CSS";
tag = document.createElement("div");
tag.setAttribute("id",id);
tag.setAttribute("class",css);
document.getElementById(parent).appendChild(tag);
idAndCSS = {
tag: tag,
id: id,
css: css
}
return idAndCSS;
}
function setCSS(className,zIndex,width,height,backgroundColor,position,left,top,cursor,border){
var i;
var cssPart;
cssPart = document.getElementsByClassName(className);
document.getElementById("1").innerHTML = cssPart.length;
document.getElementById("2").innerHTML = cssPart[0];
document.getElementById("3").innerHTML = cssPart[1];
document.getElementById("4").innerHTML = cssPart[2];
for(i=0; i < cssPart.length; i++){
cssPart[i].style.zIndex = zIndex;
cssPart[i].style.width = width;
cssPart[i].style.height = height;
cssPart[i].style.backgroundColor = backgroundColor;
cssPart[i].style.position = position;
cssPart[i].style.left = left;
cssPart[i].style.top = top;
cssPart[i].style.cursor = cursor;
cssPart[i].style.border = border;
}
}
</script>
Hi!!! I need help!!!
I made a object of "div".
and then I added one more "div" into first "div".
second "div" is a red box. You can see it when you click the "+"mark.
But, second "div" has mouse event, and the event does not work.
I want to change mouse cursor when cursor become on the red box.
Why does not the mouse event work?
My last purpose is to make window object.
And there will be a lot of mouse events.
I already made window object similar to this one. However, it also did not work.
How can I try mouse event?
This is my full source: https://drive.google.com/file/d/0B4p8lZSEMXcqZUdacVJyVlBiUWc/view?usp=sharing
This is a CSS issue. Your problem is here:
part = partOfWindow("outlayer",theNumOfWins,"section0");
setCSS(part.css,"-1","400px","400px","#65A8E8","relative","30px","30px","initial","none");
Specifically, where you set the z-index to -1, by doing so you place the div and everything contained in it under the active layer so to speak. As such the hover event doesn't propagate to your div. change this to 1 and the cursor will behave as expected.
var theNumOfWins;
var part;
theNumOfWins = 0;
function openWindow(){
part = partOfWindow("outlayer",theNumOfWins,"section0");
setCSS(part.css,"1","400px","400px","#65A8E8","relative","30px","30px","initial","none");
part = partOfWindow("headerOfWindow",theNumOfWins,part.id);
setCSS(part.css,"1","400px","25px","#65A8E8","relative","0px","0px","initial","none");
part = partOfWindow("zoneOfWindowPosition",theNumOfWins,part.id);
setCSS(part.css,"1","204px","22px","transparent","absolute","192px","4px","pointer","1px solid red");
document.getElementById("5").innerHTML = document.getElementById(part.id).attributes[1].value;
theNumOfWins++;
}
function partOfWindow(name,theNumOfWins,parent){
var id;
var css;
var idAndCSS;
var tag;
var att;
id = name + "Id" + theNumOfWins;
css = name + "CSS";
tag = document.createElement("div");
tag.setAttribute("id",id);
tag.setAttribute("class",css);
document.getElementById(parent).appendChild(tag);
idAndCSS = {
tag: tag,
id: id,
css: css
}
return idAndCSS;
}
function setCSS(className,zIndex,width,height,backgroundColor,position,left,top,cursor,border){
var i;
var cssPart;
cssPart = document.getElementsByClassName(className);
document.getElementById("1").innerHTML = cssPart.length;
document.getElementById("2").innerHTML = cssPart[0];
document.getElementById("3").innerHTML = cssPart[1];
document.getElementById("4").innerHTML = cssPart[2];
for(i=0; i < cssPart.length; i++){
cssPart[i].style.zIndex = zIndex;
cssPart[i].style.width = width;
cssPart[i].style.height = height;
cssPart[i].style.backgroundColor = backgroundColor;
cssPart[i].style.position = position;
cssPart[i].style.left = left;
cssPart[i].style.top = top;
cssPart[i].style.cursor = cursor;
cssPart[i].style.border = border;
}
}
#buttonToOpenWindow{
width:50px;
height:20px;
border: 1px solid #DCDCDC;
margin: 2px;
position:fixed;
left:-1px;
top:0px;
}
#buttonToOpenWindow div.positionOfPlus{
width:20px;
height:20px;
position:absolute;
left:30px;
}
div.wrapOfPlus{
width:20px;
height:20px;
}
div.inside01{
width:15px;
height:5px;
background-color: #B0C4DE;
position:absolute;
left:2.5px;
top:7.5px;
}
div.inside02{
width:5px;
height:15px;
background-color: #B0C4DE;
position:absolute;
left:7.5px;
top:2.5px;
}
<section id="section0">
<div id="buttonToOpenWindow" onclick="openWindow()">
<div class="positionOfPlus">
<div class="wrapOfPlus">
<div class="inside01"></div>
<div class="inside02"></div>
</div>
</div>
</div>
</section>
<footer>
<br><br><br><br><br>
<div style="display:inline-flex;">00: <div id="0"></div></div><br>
<div style="display:inline-flex;">01: <div id="1"></div></div><br>
<div style="display:inline-flex;">02: <div id="2"></div></div><br>
<div style="display:inline-flex;">03: <div id="3"></div></div><br>
<div style="display:inline-flex;">04: <div id="4"></div></div><br>
<div style="display:inline-flex;">05: <div id="5"></div></div><br>
<div style="display:inline-flex;">06: <div id="6"></div></div><br>
<div style="display:inline-flex;">07: <div id="7"></div></div><br>
<div style="display:inline-flex;">08: <div id="8"></div></div><br>
<div style="display:inline-flex;">09: <div id="9"></div></div><br>
<div style="display:inline-flex;">10: <div id="10"></div></div><br>
<div style="display:inline-flex;">11: <div id="11"></div></div><br>
<div style="display:inline-flex;">12: <div id="12"></div></div><br>
<div style="display:inline-flex;">13: <div id="13"></div></div><br>
<div style="display:inline-flex;">14: <div id="14"></div></div><br>
<div style="display:inline-flex;">15: <div id="15"></div></div><br>
<div style="display:inline-flex;">16: <div id="16"></div></div><br>
<div style="display:inline-flex;">17: <div id="17"></div></div><br>
<div style="display:inline-flex;">18: <div id="18"></div></div><br>
<div style="display:inline-flex;">19: <div id="19"></div></div><br>
<div style="display:inline-flex;">20: <div id="20"></div></div><br>
<div style="display:inline-flex;">21: <div id="21"></div></div><br>
<div style="display:inline-flex;">22: <div id="22"></div></div><br>
<div style="display:inline-flex;">23: <div id="23"></div></div><br>
<div style="display:inline-flex;">24: <div id="24"></div></div><br>
<div style="display:inline-flex;">25: <div id="25"></div></div><br>
<div style="display:inline-flex;">26: <div id="26"></div></div><br>
<div style="display:inline-flex;">27: <div id="27"></div></div><br>
<div style="display:inline-flex;">28: <div id="28"></div></div><br>
<div style="display:inline-flex;">29: <div id="29"></div></div><br>
<div style="display:inline-flex;">30: <div id="30"></div></div><br>
<div style="display:inline-flex;">111: <div id="111"></div></div><br>
<div style="display:inline-flex;">222: <div id="222"></div></div><br>
<div style="display:inline-flex;">333: <div id="333"></div></div><br>
<div style="display:inline-flex;">444: <div id="444"></div></div><br>
<div style="display:inline-flex;">555: <div id="555"></div></div><br>
<div style="display:inline-flex;">666: <div id="666"></div></div><br>
<div style="display:inline-flex;">777: <div id="777"></div></div><br>
<div style="display:inline-flex;">888: <div id="888"></div></div><br>
<div style="display:inline-flex;">999: <div id="999"></div></div><br>
</footer>

Categories

Resources