fetch offsetTop of element with respect to another element - javascript

I want to calculate the scrolled distance of a div element within another div element. I am using offsetTop for that, but it always returns 0 in my code. I am unable to figure out where I am making the mistake.
function getScrollVal() {
console.log(window.pageYOffset);
var wrap = document.getElementById("wrapper");
console.log(wrap.id);
console.log(wrap.offsetParent.id);
var parent = wrap.offsetParent;
console.log("scrollTop: " + wrap.scrollTop + " scrollLeft: " + wrap.scrollLeft);
console.log("offsetTop: " + wrap.offsetTop + " offsetLeft: " + wrap.offsetLeft);
/*
var xx = wrap.offsetLeft;
var yy = wrap.offsetTop;
while(wrap = wrap.offsetParent){
xx += wrap.offsetLeft;
yy += wrap.offsetTop;
}
*/
}
body, html {
margin: 0;
padding: 0;
}
#contain {
position: relative;
width:100%;
height: 100vh;
background: yellow;
overflow: auto;
}
#wrapper {
width: 85%;
margin: 0 auto;
background: red;
}
.full {
height: 100vh;
width: 85%;
margin: 0 auto;
}
#one { background:#222;}
#two{ background:#00c590;}
#three{ background:#3429c5;}
#four{background:#bbb;}
#b {
position: fixed;
z-index: 1000;
top: 30px;
left: 30px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<div id="contain">
<div id="wrapper">
<div id="one" class="full"></div>
<div id="two" class="full"></div>
<div id="three" class="full"></div>
<div id="four" class="full"></div>
</div>
</div>
<button id="b" type="button" onClick="getScrollVal();" value="click me">Press me</button>
</body>
</html>
I have tried the js code inside the comment. That one is not providing a fruitful result. Thanks in advance.

Since the element #contain is the overflow element, you can try get the scrollTop like this:
console.log("scroll top:", document.getElementById('contain').scrollTop);
From MDN:
An element's scrollTop is a measurement of the distance of an element's top to its topmost visible content. Element.scrollTop

Related

Writing an If statement for the condition of a parameter

I have a basic Graphics User Interface where if the user clicks "move"
then a div (yellow rectangle) moves across the screen.
However, I want there to be an event based on Where the rectangle is on the page. In example, If the div is at 400px (right) then alert "hey", else, move the div.
here is the moving div
<html>
<head>
<title>Move Div</title>
<script language ="javascript">
<!--
function MoveDiv()
{
div = document.getElementById("myDiv");
div.style.left = parseInt(div.style.left) + 100 + "px";
}
//-->
</script>
</head>
<body>
<input type="button" value="Move Div" onclick="MoveDiv()" />
<div id="myDiv" style="border: 10px solid black; background-color: Yellow; width: 100px; height: 30px; position: absolute; top: 1px; left: 100px;"></div>
</body>
</html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
here is the moving div
<html>
<head>
<title>Move Div</title>
<script language ="javascript">
<!--
function MoveDiv(){
if ($('#myDiv').css == marginTop: '-=15px' ) {
div = document.getElementById("myDiv");
div.style.left = parseInt(div.style.left) + 100 + "px";
}}
//-->
</script>
</head>
<body>
<input type="button" value="Move Div" onclick="MoveDiv()" />
<div id="myDiv" style="border: 10px solid black; background-color: Yellow; width: 100px; height: 30px; position: absolute; top: 1px; left: 100px;"></div>
</body>
</html>
errors mostly because im not sure on the syntax :(
hope its help you
You must use var (let, const) when create a new variable
I added CONSTANTS for easy configuration,
isDivCanMoveForward for your:
Where the rectangle is on the page. In example, If the div is at 400px (right) then alert "hey", else, move the div.
var MAX_POSITION_OF_DIV_NODE = 400;
var STEP_OF_DIV_NODE = 100;
var div = document.getElementById("myDiv");
var currentPositionOfDivNode = parseInt(div.style.left, 10);
function MoveDiv() {
currentPositionOfDivNode += STEP_OF_DIV_NODE; // increment
if (!isDivCanMoveForward()) {
return; // stop functinon when div have max position
}
div.style.left = currentPositionOfDivNode + "px";
}
function isDivCanMoveForward() {
if (currentPositionOfDivNode > MAX_POSITION_OF_DIV_NODE) {
currentPositionOfDivNode = MAX_POSITION_OF_DIV_NODE // set max of value
alert('hey')// user message
return false;
}
return true;
}
<html>
<head>
<title>Move Div</title>
</head>
<body>
<input type="button" value="Move Div" onclick="MoveDiv()" />
<div id="myDiv" style="border: 10px solid black; background-color: Yellow; width: 100px; height: 30px; position: absolute; top: 1px; left: 100px;"></div>
</body>
</html>

Why am I getting errors with my JavaScript?

I am trying to practice JavaScript with basic DOM manipulation but I keep getting 2 errors:
1.SyntaxError: missing ; before statement
2.TypeError: size is not a function
function size() {
var height = document.body.getElementById('hover1').style.height: 500 px;
var width = document.body.getElementById('hover1').style.width: 500 px;
}
console.log(hover);
<!DOCTYPE html>
<html>
<head>
<title>javascript practice</title>
<meta charset="utf-8" />
<style>
body {
margin: 7em auto;
background-color: green;
width: 90%;
}
#size1 {
background-color: blue;
width: 150px;
height: 150px;
margin: 3em auto;
}
</style>
</head>
<body>
<div id="size1"></div>
<input type="button" value="size" onclick="size();">
</body>
your error is here:
var height = document.body.getElementById('hover1').style.height: 500px;
var width = document.body.getElementById('hover1').style.width: 500px;
// -------------------^ and -------------------------------------^
replace those lines with these:
var height = document.getElementById('hover1').style.height;
var width = document.getElementById('hover1').style.width;
There is nothing called document.body.getElementById instead change this to document.getElementById use as below
var height = (document.getElementById('hover1'))?document.getElementById('hover1').style.height: "500px";
var width = (document.getElementById('hover1'))?document.getElementById('hover1').style.width: "500px";
function size1() {
console.log("test")
var height = (document.getElementById('hover1'))?document.getElementById('hover1').style.height: "500px";
var width = (document.getElementById('hover1'))?document.getElementById('hover1').style.width: "500px";
}
//console.log(hover);
<!DOCTYPE html>
<html>
<head>
<title>javascript practice</title>
<meta charset="utf-8"/>
<style>
body {
margin: 7em auto;
background-color: green;
width: 90%;
}
#size1 {
background-color: blue;
width: 150px;
height: 150px;
margin: 3em auto;
}
</style>
</head>
<body>
<div id="size1">
</div>
<input type="button" value="size" onclick="size1()">
</body>
If you are going to set the height of the element and assign the height to var height then you need to do the following:
var height = document.getElementById("size1").style.height = "500px";
If you are going to just assign the height of the element to var height then you need to do the following:
var height = document.getElementById("size1").style.height;
If you are just going to set the height of the element then you just need to do:
document.getElementById("size1").style.height = "500px";
You should also make your 500px with quotes as numbers do not need " " around them but once you add text...it all becomes text. So either way you should have "500px"
I would also make your button into this:
<button type="button" value="size" onclick="size()">Size</button>
Based on a belief that you are trying to make the div larger onclick of Size button then you should have the following:
Style
body {
margin: 7em auto;
background-color: green;
width: 90%;
}
#size1 {
background-color: blue;
width: 150px;
height: 150px;
margin: 3em auto;
}
HTML
<div id="size1"></div>
<button type="button" value="size" onclick="size()">Size</button>
JavaScript
function size() {
document.getElementById('size1').style.height = "500px";
document.getElementById('size1').style.width = "500px";
}

javascript mouseout function flickering

I'm trying to create a mouse in and out effect that shows and disappears DIV's according to the mouse function. I've successfully done this, but the mouseout function flickers on and off when im inside the div instead of staying on.
Heres my sample code:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Kow Your Face</title>
<style>
#face {
background-image: url(face.png);
width: 262px;
height: 262px;
}
#lefteye {
background-image: url(circle.png);
width: 28px;
height: 28px;
position: relative;
top: 69px;
left: 59px;
}
#righteye {
background-image: url(circle.png);
width: 28px;
height: 28px;
position: relative;
top: 41px;
left: 167px;
}
#mouth {
background-image: url(circle.png);
width: 28px;
height: 28px;
position: relative;
top: 84px;
left: 114px;
}
</style>
</head>
<body>
<div id="face">
<div id="lefteye" onMouseOver="getElementById('lefteye').style.visibility='hidden'; getElementById('lefteyedes').style.visibility='visible';" onMouseOut="getElementById('lefteye').style.visibility='visible'; getElementById('lefteyedes').style.visibility='hidden';">
</div>
<div id="righteye" onMouseOver="getElementById('righteye').style.visibility='hidden'; getElementById('righteyedes').style.visibility='visible';" onMouseOut="getElementById('righteye').style.visibility='visible'; getElementById('righteyedes').style.visibility='hidden';">
</div>
<div id="mouth" onMouseOver="getElementById('mouth').style.visibility='hidden'; getElementById('mouthdes').style.visibility='visible';" onMouseOut="getElementById('mouth').style.visibility='visible'; getElementById('mouthdes').style.visibility='hidden';">
</div>
</div>
<div id="lefteyedes" style="visibility: hidden;">
<p>Left Eye</p>
</div>
<div id="righteyedes" style="visibility: hidden;">
<p>Right Eye</p>
</div>
<div id="mouthdes" style="visibility: hidden;">
<p>Mouth</p>
</div>
</body>
</html>
Use document.getElementById instead of just getElementById and you can use this keyword to refer to the current element:
<div id="lefteye" onMouseOver="this.style.visibility='hidden'; document.getElementById('lefteyedes').style.visibility='visible';" onMouseOut="this.style.visibility='visible'; document.getElementById('lefteyedes').style.visibility='hidden';">
</div>
For some reason your onmouseout function is being repeatedly called "onmousemove"...this solution should help you suppress the onmouseout function being repeatedly called. I've rewritten your code a little to help make it easier to enforce changes later (illustrated with one of the onmouseover/onmouseout pairs)...give this a shot:
<script type="text/javascript">
function leftEyeVisibility(vis1, vis2) {
//this function should work for the left eye when the left eye is hidden (lefteyedes is visible) and the mouse is moving over (or not moving at all) the hidden left eye div but has not moused out of it
var dg = document.getElementById("lefteye");
var divStyle = window.getComputedStyle(dg, "");
var mousePosition = function (e) {
var xCoord = e.pageX;
var yCoord = e.pageY;
return xCoord + "," + yCoord;
}
var positionArray = mousePosition.split(","); //split the xy coordinates returned by previous function
if ((positionArray[0] > dg.offsetLeft) && (positionArray[0] < dg.offsetLeft + dg.offsetWidth) && (positionArray[1] > dg.offsetTop) && (positionArray[1] < dg.offsetTop + dg.offsetHeight)) {
var mouseOverlap = 'yes';
} else var mouseOverlap = 'no';
if ((divStyle.visibility === 'hidden') && (mouseOverlap === 'yes')) {
return false;
} else {
document.getElementById("lefteye").style.visibility = vis1;
document.getElementById("lefteyedes").style.visibility = vis2;
}
}
</script>
<div id="lefteye" onmouseover="leftEyeVisibility('hidden', 'visible')" onmouseout="leftEyeVisibility('visible', 'hidden')">
</div>
With jQuery it would be much easier to do this...let me know if it works.

Slide to next div

HTML:
<div class="inline-wrapper">
<div class="inline-blocks" id="f">123</div>
<div class="inline-blocks" id="s">123</div>
<div class="inline-blocks" id="t">123</div>
<div class="inline-blocks" id="fo">123</div>
</div>
CSS:
html, body {
width: 100%;
height: 100%;
/* overflow: hidden;*/
}
.inline-wrapper{
width: 400%;
height: 100%;
font-size: 0;
position: relative;
}
.inline-blocks{
display: inline-block;
width: 25%;
height: 100%;
vertical-align: top;
position: relative;
}
>.inline-blocks:nth-child(1){
background-color: #000;
}
.inline-blocks:nth-child(2){
background-color: blue;
}
.inline-blocks:nth-child(3){
background-color: red;
}
.inline-blocks:nth-child(4){
background-color: green;
}
How can I slide them without ID?
In fact this is the work of the slider. But I can not understand the logic.
Want to understand how flipping without ID.
We must check the blocks and give them сurrent class.
Auto Slide
HTML:
<div class="inline-wrapper">
<div class="inline-blocks" id="f">123</div>
<div class="inline-blocks" id="s">123</div>
<div class="inline-blocks" id="t">123</div>
<div class="inline-blocks" id="fo">123</div>
</div>
jQuery:
(function () {
var numDivs = $('.inline-wrapper').children().length; //Count children ELements
var counter = 1;
function slide(time, counter) {
var $currentDiv = $('.inline-wrapper .inline-blocks:nth-child(' + counter + ')'); //get next element
var position = $currentDiv.position(); //get position of next element
if (numDivs > 1) {
$('html,body').animate({
scrollLeft: position.left
}, time / 2); //Animate to next element
}
};
$('.inline-blocks').on('click', function () {
counter = counter + 1;
slide(2000, counter);
});
})();
DEMO

how to center columns based on window width

<link rel="stylesheet" type="text/css" href="reset.css" />
<style type="text/css">
body { position: relative; }
.contain { position:relative; overflow: hidden; width: 80%; height: 100%; margin: 0 auto; }
.box {
background-color: #F0F0F0;
color: #888;
font-family: Arial, Tahoma, serif;
font-size: 13px; }
.box p { padding: 10px; }
.box span {
float: left;
font-size: 26px;
font-weight: bold; }
div.alt { background-color: #CCC; }
</style>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript">
var myFluidGrid = {
COLNUMBER : 2, // Minimum column number.
COLMARGIN : 10, // Margin (in pixel) between columns/boxes.
COLWIDTH : 240, // Fixed width of all columns.
doLayout : function() {
var self = this;
var pointer = 0;
var arr = [];
var columns = Math.max(this.COLNUMBER, parseInt($('body').innerWidth() / (this.COLWIDTH + this.COLMARGIN)));
$('.box').css('position', 'absolute').css('width', this.COLWIDTH + 'px');
$('.box').each(function() {
var tempLeft = (pointer * (self.COLWIDTH + self.COLMARGIN));
$(this).css('left', tempLeft + 'px');
var tempTop = 0;
if (arr[pointer]) { tempTop = arr[pointer]; }
$(this).css('top', tempTop + 'px');
arr[pointer] = tempTop + $(this).outerHeight() + self.COLMARGIN;
pointer++;
if (pointer === columns) { pointer = 0; }
});
}
};
$(window).ready(function() {
myFluidGrid.doLayout();
}).resize(function() {
myFluidGrid.doLayout();
});
</script>
<div class="contain">
<div class="box">This is box number 1...</div>
<div class="box">This is box number 2...</div>
<div class="box">This is box number 3...</div>
</div>
Demo of current code: http://grahamthomas.me/temp/test.html
Trying to get the above grid to remain centered in the window no matter its size. I currently have it roughly centered, but when the window size is adjusted, the centering becomes untrue until the new column is populated with content (i.e. when the dynamic grid is between columns--larger than 3 columns, but no quite 4).
I'm not great at JS, but my logic is:
create a 100% wrapper (which would mimic the body.innerWidth
dimension in the JS)
create a centered wrapper inside this (80% for example)
place the content in the centered wrapper
once the 100% wrapper is large enough to handle an additional column, append the new div within the centered wrapper
You can clearly see the overflow:hidden property 'run over' the right-most boxes when dragging the window smaller. I assume from this, the window width isn't being calculated properly. I tried variants of var columns, like:
var columns = Math.max(this.COLNUMBER, parseInt(($('body').innerWidth() * 0.8)/ (this.COLWIDTH + this.COLMARGIN)));
..which keeps the columns within the window, but still isn't a proper center.
I've been looking at this for a while, anyone have any ideas?
Thanks
No JavaScript required:
<html>
<head>
<style>
body {
text-align: center;
}
div.main {
position: absolute;
top: 100px;
left: 50%;
margin-left: -40%;
width: 80%;
}
div.main div.block {
height: 180px;
width: 180px;
background: #a00;
float: right;
margin: 10px;
}
</style>
</head>
<body>
<div class="main">
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
</div>
</body>
</html>

Categories

Resources