I want an image inside div to be moving vertically down whenever a user scrolls. It has to end only at the end of the page. Have used the below script solution from the another post, however it doesn`t help.
HTML
<div id="wrapper">
<img src="images/samp_scroll.png" class="ïmage">
</div>
CSS:
#wrapper {
position: absolute;
}
.image {
width: 560px;
height: 700px;
}
Script:
window.onscroll = function (e) {
var vertical_position = 0;
if (pageYOffset)//usual
vertical_position = pageYOffset;
else if (document.documentElement.clientHeight)//ie
vertical_position = document.documentElement.scrollTop;
else if (document.body)//ie quirks
vertical_position = document.body.scrollTop;
console.log( vertical_position);
var your_div = document.getElementById('wrapper');
your_div.top = (vertical_position + 200) + 'px';//200 is arbitrary.. just to show you could now position it how you want
}
What is that I am doing wrong here?? Verfying this further, though I could get the console value vertical_position I can`t really move the div using the below code.
var your_div = document.getElementById("wrapper");
your_div.top = 400 + 'px';
Is there any other best way to deal with Moving html elements with DIV? Any articles which explains? I am really new to this. Please help me out.
Adding style before the top, worked. However looks like the style applies only once as it moves only once as I scroll. Any ideas.
One small miss, it should be style.top:
your_div.style.top = (vertical_position + 200) + 'px';
Replace
var your_div = document.getElementById('wrapper');
your_div.top = (vertical_position + 200) + 'px';//200 is arbitrary.. just to show you could now position it how you want
with
$("#wrapper").css("top",(vertical_position + 200) + 'px');
Related
I want to add a class to an element when the user scrolls more than 100px from the top of the element but I seem to be triggering this as soon as the page loads. This is the code that I have at the moment
const content = document.getElementById("content");
document.addEventListener("scroll", () => {
content.classList.add(
'curtain-in',
content.scrollTop > 100
);
});
Also with your answer can you please explain where I've gone wrong.
Thank you in advance
Maybe what is happening is that content.scrollTop is always returning 0 and your condition is never fulfilled. I've struggled myself with that problem trying to make a fiddle to test your case.
To check if the scroll has passed the beginning of the element plus 100px we need to know where the element starts and the new position of the scroll, we can get both values like this:
var position = content.offsetTop;
var scrolled = document.scrollingElement.scrollTop;
With these, you can do something like this in your event function:
const content = document.getElementById("content");
document.addEventListener("scroll", (e) => {
var scrolled = document.scrollingElement.scrollTop;
var position = content.offsetTop;
if(scrolled > position + 100){
content.classList.add(
'curtain-in');
}
});
Here's the fiddle: https://jsfiddle.net/cvmw3L1o/1/
I want to add a class to an element when the user scrolls more than
100px from the top of the element
You should add addEventListener to content not document
const content = document.getElementById("content");
content.addEventListener("scroll", () => {
console.log('class added');
content.classList.add(
'curtain-in',
content.scrollTop >= 100
);
});
#content {
height: 200px;
width: 200px;
overflow: scroll;
}
p {
height: 1000px;
}
<div id="content">
<p></p>
</div>
I have a small function the uses a web socket to receive realtime updates. When a new response is received the function prepends a div in the html. I only want the updates to be shown in a window within the page, ie. only ~10 prepended divs should be showing at the most. Ideally I need to pop the oldest div before it overflows out of its parent div.
My question:
How do I pop divs before they overflow the parent? Considering I will receive a response nearly every second or so, what is the most efficient way of doing this?
#HTML
<div class="content">
<p>archienorman-thesis $ realtime_bitcoin</p>
<div id="messages"></div>
<!-- window content -->
</div>
#JS FUNCTION
var total = 0;
var btcs = new WebSocket('wss://ws.blockchain.info/inv');
btcs.onopen = function () {
btcs.send(JSON.stringify({"op": "unconfirmed_sub"}));
};
btcs.onmessage = function (onmsg) {
console.log(response);
var response = JSON.parse(onmsg.data);
var amount = response.x.out[0].value;
var calAmount = amount / 100000000;
var msgs = $('#messages .message');
var count = msgs.length;
if (count == 10) {
msgs.first().remove();
}
$('#messages').prepend("<p class='tx'> Amount: " + calAmount + "</p>");
}
Make the container div overflow: hidden, check if there is overflow using JS scrollHeight and clientHeight.
CSS
#messages {
overflow: hidden;
}
JS
Remove your if statement and add this after your prepend() line:
$('#messages').prepend("<p class='tx'> Amount: " + calAmount + "</p>");
$('#messages').css("overflow", "scroll");
if($('#messages')[0].scrollHeight > $('#messages').height())
msgs.last().remove();
$('#messages').css("overflow", "hidden");
The above quickly makes #messages have the overflow: scroll property in order for the scrollHeight property to work. If there is extra scroll, then it deletes the element.
See Demo.
NOTE
See my comment to your question. You should be removing last(), not first(). See the demo as an example -- try changing last() to first(), and it will not work.
I think something like this should work. This is test code that will basically remove the extra child elements when their combined width exceeds that of the container.
HTML
<div class="container">
<div>1.Test</div>
<div>2.Test</div>
<div>3.Test</div>
<div>4.Test</div>
<div>5.Test</div>
<div>6.Test</div>
<div>7.Test</div>
<div>8.Test</div>
<div>9.Test</div>
<div>10.Test</div>
<div>11.Test</div>
<div>12.Test</div>
<div>13.Test</div>
<div>14.Test</div>
<div>15.Test</div>
</div>
CSS
.container {
width:1000px;
}
.container div {
width: 100px;
display: inline-block;
}
Javascript
function a () {
var containerWidth = $('div.container').width();
var childWidth = $('div.container div').width();
var childCount = $('div.container div').length;
var removeCount = (childWidth * childCount) - containerWidth;
if(removeCount > 0) {
removeCount = Math.floor(removeCount/childWidth);
console.log(removeCount);
for(i = childCount; i > (childCount-removeCount); i--) {
$('div.container div:nth-child('+i+')').remove();
}
}
}
a();
Fiddle: https://jsfiddle.net/L3r2nk6z/5/
How do you get this result in css, javascript or jquery, or a combination of all:
I asked and posted a similar question before, but no one answered it.
Someone said:
"Maybe you can use javascript (or bether JQuery) for this.
If you use JQuery, you can use the scroll event. If you are scrolling, do a
check if it hits the other div. https://api.jquery.com/scroll/
Checking the positions of the divs is possible with offset/position.
http://api.jquery.com/offset/ https://api.jquery.com/position/
If you want to change the background, you give the div a background color
that is pink. If it hits then you can add an additional background-image
that has a specific background-position
(http://www.w3schools.com/cssref/pr_background-position.asp xpos ypos).
I don't have tried it yet, but I guess it is possible that way."
So my question is, how would you go about doing it to get this result or regardless of what way?
I came up with this after a couple of hours trying to make it work. It was pretty fun doing it, so I'm sharing it.
$(document).ready(function() {
var initScrollTop = $(window).scrollTop();
$('.div1').css('top', (initScrollTop+100)+"px");
$(window).scroll(function () {
var top = parseInt($('.div1').css('top').split("px")[0]);
// I GIVE A FIXED TOP TO .DIV1
var scrollTop = $(this).scrollTop() + 100;
$('.div1').css('top', scrollTop+"px");
// GETTING SOME VALUES
// DIV1
var div2Top = parseInt($('.div2').css('top').split('px')[0]);
var div2Height = parseInt($('.div2').css('height').split('px')[0]);
var div2Bottom = parseInt($('.div2').css('bottom').split('px')[0]);
// DIV2
var div1Width = parseInt($('.div1').css('width').split('px')[0]);
var div1Height = parseInt($('.div1').css('height').split('px')[0]);
var div1Top = parseInt($('.div1').css('top').split('px')[0]);
var div1Bottom = parseInt($('.div1').css('bottom').split('px')[0]);
var div1Left = parseInt($('.div1').css('left').split('px')[0]);
// WE ARE GOING THROUGH THE GREEN BOX
if(scrollTop + div1Height > div2Top) {
// OUTSIDE OF THE GREEN BOX (.div2)
if(scrollTop + div1Height > div2Height + div2Top) {
var div3Height = div2Top + div2Height - scrollTop;
$('.div3').css('top', scrollTop+ "px")
// .css('bottom', div2Bottom + "px")
.css('width', div1Width + "px")
.css('height', div3Height + "px")
.css('visibility','visible');
console.log("I'm out");
}
// INSIDE OF THE GREEN BOX (.div2)
else {
var div3Height = (div1Top > div2Top) ? div1Height : scrollTop + div1Height - div2Top;
var div3Top = (div1Top > div2Top) ? div1Top : div2Top;
$('.div3').css({
'top' : div3Top + "px",
'left': div1Left + "px",
'width': div1Width + "px",
'height': div3Height + "px",
'visibility':'visible'
});
}
} else {
$('.div3').css('visibility','hidden');
}
// WE ARE ABSOLUTELY OUT OF THE GREEN BOX (FROM THE BOTTOM GOING DOWN)
if(scrollTop > div2Top + div2Height) {
$('.div3').css('visibility','hidden');
}
});
});
Here's there a fiddle so you can test it http://jsfiddle.net/5076h670/2/
So basically what it does is create three divs, two of them will be visible and 'collide' between each other, the other one starts hidden and it shows only when the position of the div1 is in the range of the div2. This div3 (the third div) will be shown over the div1 (see the z-index). When it's absolutely out of the box div3 will be hidden.
I don't know what else to explain about the code, I don't know if (and I don't think, it took me a while to make it work) it's understandable what it does. If you have something to ask I'll be reading ;)
Hope it helps
I have a div section on my .ASPX form. The section just contains a load of links (standard
document.getElementById('Side1').style.display = 'none';
This worked great but was a bit abrupt for what I wanted, so I wrote the little routine below (with a little help from the internet) but although the DIV dection shrinks, and the content below scrolls up .. the links in the div section don't move, until the div section is made invisible .... is there a way round this, or am i going about this all wrong (ps my javascript is rubbish)
var originalSize =0;
var i = 0;
var ts;
function shrink() {
if (i != 28) {
document.getElementById('Side1').style.height = parseInt(document.getElementById('Side1').style.height) - 5 + 'px';
i++;
ts = setTimeout("shrink()", 10);
}
else {
document.getElementById('Side1').style.display = 'none';
i = 0;
clearTimeout(ts);
}
}
You probably just need to add this to your CSS:
#Side1 { overflow: hidden; }
I have 2 divs, one positioned absolutely right: 0 and the other relatively positioned center screen. When the window's width is too small, they overlap. How can I invoke a javascript function when this happens?
Thanks.
Mike
Edited to make clearer.
To check for overlapping div's you might wanna do a check once the page is loaded, and whenever the window is resized:
window.onload = checkOverlap;
window.onresize = checkOverlap;
And then use some offset-checking:
function checkOverlap() {
var centerBox = document.getElementById('centerDiv');
var rightBox = document.getElementById('rightDiv');
console.log("centerbox offset left: " + centerBox.offsetLeft);
console.log("centerbox width: " + centerBox.offsetWidth);
console.log("rightbox offset left: " + rightBox.offsetLeft);
if ((centerBox.offsetLeft + centerBox.offsetWidth) >= rightBox.offsetLeft) {
centerBox.style.display = "inline-block";
} else {
centerBox.style.display = "block";
}
}
You might wanna do some more checks in the function, e.g. to see if the box is already displayed inline, and such. But that should give you a good place to start.
edit: added some diagnostics and fixed error
Part 1:
Do it like this:
<script type="text/javascript">
document.getElementById('example').style.display = "inline";
</script>
...
<div id="example"> ... </div>
document.getElementById('div_id').style.display = 'inline-block'
document.getElementById('div_id').offsetWidth gives us width of div
offsetHeight, offsetLeft, offsetTop are useful also.