Why are "fadeIn" and "fadeOut" functions moving my divs? - javascript

I'm starting a new website and I'm using JQuery for display a div inside another (a title). I have 4 divs displayed inline-block and my result need to be like this :
I'm using Jquery for display the div containing "Accueil" with the function fadeIn and fadeOut but my problem is the following : When the move is over a div, the hidden div is animated and fade in like desired but the other div (on the right) is moving down !
My html is the following :
The left box :
<div class="box-interactive box-interactive1">
<div class="contenu-box">
titi 1
</div>
<div id="bandeau1" class="bandeau">
rr
</div>
</div>
The right box :
<div class="box-interactive box-interactive2">
<div class="contenu-box">
titi 2
</div>
<div id="bandeau2" class="bandeau" style="display : block;">
accueil 2
</div>
</div>
My css :
/*CSS for boxes and interactive text*/
.box-interactive {
width: 300px;
height: 200px;
background-color: red;
margin: 20px;
display: inline-block;
size: fixed;
}
.contenu-box{
width: 300px;
height: 160px;
}
.bandeau {
width: 300px;
height: 40px;
background-image: url("../../img/Alex/accueil.png");
background-size: auto 100%;
position: relative;
display: none;
}
And my JS :
$(function(){
$("div[class^='box-interactive']").hover(
function(){
var id = new Array;
id = $(this).attr('class').split(' ');
for (var i in id) {
if(id[i].match('box-interactive.+')){
var idnum = 'bandeau'+id[i].substring(15);
$("#"+idnum+"").fadeIn(800);
}
}
},
function(){
var id = new Array;
id = $(this).attr('class').split(' ');
for (var i in id) {
if(id[i].match('box-interactive.+')){
var idnum = 'bandeau'+id[i].substring(15);
$("#"+idnum+"").fadeOut(500);
}
}
}
);
});
The second div (it works in both ways) is moving down with specificities : the top of the moving div is equal to the bottom of the first div (the one befor the hidden). Do you have an explaination ?
Fiddle : http://jsfiddle.net/Msh2T/1/ open large the right window to see the problem ;) thx

fadeIn and fadeOut will set an element to "display: none" once the animation completes, removing it from the layout. If you don't want the animation to affect the layout, animate the opacity.
$("#"+idnum+"").animate({opacity: 0}, 800);
...
$("#"+idnum+"").animate({opacity: 1}, 800);

You can float the .bandeau divs so that they aren't affecting the inline layout flow, effectively limiting their scope to the parent div.
.bandeau {
width: 300px;
height: 40px;
background-image: url("../../img/Alex/accueil.png");
background-size: auto 100%;
position: relative;
display: none;
float: left; /* ADD THIS */
}
Fiddle: http://jsfiddle.net/Msh2T/3/

One option would be to animate the opacity either to 1 or to 0 instead of using fadeIn and fadeOut:
$("#"+idnum+"").animate( { opacity:1 }, 800 );
and
$("#"+idnum+"").animate( { opacity:0 }, 500 );
Here's a working fiddle to demonstrate this approach.
A few other notes about the code...
First, your hover-in and hover-out functions are nearly identical. Any time you have that much code that is so similar, it's a very good idea to combine it into a single function.
Where you have this code:
var id = new Array;
id = $(this).attr('class').split(' ');
it's unnecessary to have the new Array, since you are just replacing the value in the next line. Also, I recommend using a plural name for an array instead of a singular name:
var ids = $(this).attr('class').split(' ');
The next line is:
for (var i in id) {
Never use a 'for..in' loop on an array. It will bite you if anyone ever augments Array.prototype with new methods or properties. Instead, use a numeric for loop or an iterator such as jQuery's $.each().
Next is this code:
if(ids[i].match('box-interactive.+')){
var idnum = 'bandeau'+id[i].substring(15);
...
When you use .match to test a string like this, you can also use it to extract the part of the string you want, without resorting to a brittle-to-maintain .substring(15) call:
var match = ids[i].match( /box-interactive(.+)/ );
if( match ) {
var idnum = 'bandeau' + match[1];
...
Now having said all this, why not simplify things much further and let jQuery do all the work for you? There's no need for any of this fancy array looping and checking of classnames. You can replace the entire JavaScript code with this:
$(function(){
$("div[class^='box-interactive']").hover(
function(){
$(this).find('.bandeau').animate( { opacity:1 }, 800 );
},
function(){
$(this).find('.bandeau').animate( { opacity:0 }, 500 );
}
);
});
Updated fiddle
(You may note that I've contradicted my first piece of advice here and didn't combine the bit of duplicate code in the hover-in and hover-out functions. But there's now so little code that that the duplication isn't worth worrying about.)

Try using z-index in your CSS to stack your divs on top of each other

Related

CSS flex property is not responding correctly when set to 0 from JS code

This might be a very simple oversight of something in my part, but so far I have a very simple project, that divides the screen into three parts, the first 2 parts are within a container with display: flex
and they are both given the same flex value of 1. In my JS code, when a specific boolean variable is set to false, I want one of those two parts to be hidden, and the other one to occupy its place.
This works as expected if I set 'flex: 0' in CSS, but not when I do it in JS.
// Init on page load
window.addEventListener("load", function() {
var gameContainer = document.getElementById("game-container");
if (!false) { //this is to be changed later on to check for a boolean value
gameContainer.style.flex = "0"; //this should hide the right part, but it does not
}
});
#whole-game {
display: flex;
}
#story-container {
background-color: black;
height: 80vh;
flex: 1;
}
#game-container {
background-color: blue;
height: 80vh;
flex: 1;
}
#settings-container {
background-color: rgb(83, 50, 8);
width: 100vw;
height: 20vh;
}
<body>
<div id="whole-game">
<div id="story-container"></div>
<div id="game-container"></div>
</div>
<div id="settings-container"></div>
</body>
This is how my screen looks on running the code
This is how I want it to look
As I see on your code, you have declared the "gameManager" variable as array not object. So, if you want to execute the "trial" function, you need first to access the object index in the array, then the function:
var gameManager = [{
},
{trial: function (){
var gameContainer = document.getElementById("game-container");
if(!false){ //this is to be changed later on to check for a boolean value
gameContainer.style.flex = "0"; //this should hide the right part, but it does not
}},
}]
// Init on page load
window.addEventListener("load", gameManager[1].trial);
Of course you gonna change index [1] to the actual index of the object.
Maybe it's because of the zero being a string?
Try making it gameContainer.style.flex = 0;

Set height of a div in vue js

I am using vue js . I want to set one div based on another div height, with pure javascript. the problem I am facing is I can't set the height using pure java script. but I can set it using jquery. can any one please help me to change this jquery to javascript . the code I am using is given
Vue.nextTick(function () {
var offsetHeight = document.getElementById('filterSection').offsetHeight;
$(".searchResultSection").css("max-height",`calc(100% - ${offsetHeight}px)`);
});
I need to change the jquery part into java script.
In fact, computed properties (https://v2.vuejs.org/v2/guide/computed.html#Computed-Properties) is the perfect option to solves your problem:
Declare a computed property who will return the filterSectionHeight
export default {
name: "App",
computed: {
filterSectionHeight() {
const filterSectionDOM = document.getElementById("filterSection");
return filterSectionDOM ? filterSectionDOM.offsetHeight : 0;
},
}
};
Define your div filterSection and searchResultsSection in your component (or App component), don't forget to add a :style attribute who handle the dynamic max-height provided to .searchResultsSection in your template
<div id="filterSection"></div>
<div class="searchResultsSection"
:style="{
'max-height': `calc(100% - ${filterSectionHeight}px)`
}">
</div>
Set height of each div to 100% in your css
#app {
height: 600px;
width: 100%;
}
#filterSection {
height: 100%;
background: rebeccapurple; //https://en.wikipedia.org/wiki/Eric_A._Meyer
}
.searchResultsSection{
height: 100%;
background: rebeccapurple;
opacity: 0.6;
}
You will find a full demo here > https://codesandbox.io/s/1rkmwo1wq
Not sure about the context of this change, but I'll try to give you some solutions based on best practices on how to achieve that:
If parent element has a fixed height, then children with height: 100% will adopt parents height.
.parent {
height: 200px;
}
.child {
height: 100%;
}
Use a vue-directive for DOM manipulation: https://v2.vuejs.org/v2/guide/custom-directive.html
Use v-bind:style="height: calc(100% - ${offsetHeight}px)\" on the element that you want to achieve the height!
You need to use the javascript DOM-style to do this.
Try this.
Vue.nextTick(function () {
var offsetHeight = document.getElementById('filterSection').offsetHeight;
var x = document.getElementsByClassName("searchResultSection");
x[0].style.maxHeight = "calc(100% - ${offsetHeight}px)";
});

Only one Active class and Visible Div at a time

There are a bunch of div elements on the page.
I have a nested div inside of them.
I want to be able to add a class to the clicked element, and .show() the child div.
$('.container').on('click', function(){
$(this).toggleClass('red').children('.insideItem').slideToggle();
});
I can click on it, it drops down.
Click again, it goes away.
So, now I need some method to removeClass() and slideUp() all of the other ones in the event of a click anywhere except the open div. Naturally, I tried something like this:
$('html').on('click', function(){
$('.container').removeClass('red').children('div').slideUp();
});
Well, that just stops the effect from staying in the first place. I've read around on event.Propagation() but I've read that should be avoided if possible.
I'm trying to avoid using any more prebuilt plugins like accordion, as this should be a pretty straightforward thing to accomplish and I'd like to know a simple way to make it work.
Would anyone be able to show a quick example on this fiddle how to resolve this?
Show only one active div, and collapse all others if clicked off
https://jsfiddle.net/4x1Lsryp/
One way to go about it is to update your code with the following:
1) prevent the click on a square from bubbling up to the parent elements
2) make sure to reset the status of all the squares when a new click is made anywhere.
$('.container').on('click', function(){
$this = $(this);
$('.container').not($this).removeClass('red').children('div').slideUp();
$this.toggleClass('red').children('div').slideToggle();
return false;
});
See the updated JSfiddle here: https://jsfiddle.net/pdL0y0xz/
You need to combine your two approaches:
for (var i = 0; i < 10; i++) {
$('#wrap').append("<div class='container'>" + i + "<div class='insideDiv'>Inside Stuff</div></div>");
}
$('.container').on('click', function() {
var hadClassRed = $(this).hasClass('red');
$('.container').removeClass('red').children('div').slideUp();
if (!hadClassRed) {
$(this).toggleClass('red').children('div').slideToggle();
}
});
.container {
width: 200px;
height: 200px;
float: left;
background: gray;
margin: 1em;
}
.insideDiv {
display: none;
}
.red {
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrap"></div>

Store positioning information from each element (JQuery/Javascript)

Pleasantries
I've been playing around with this idea for a couple of days but can't seem to get a good grasp of it. I feel I'm almost there, but could use some help. I'm probably going to slap myself right in the head when I get an answer.
Actual Problem
I have a series of <articles> in my <section>, they are generated with php (and TWIG). The <article> tags have an image and a paragraph within them. On the page, only the image is visible. Once the user clicks on the image, the article expands horizontally and the paragraph is revealed. The article also animates left, thus taking up the entire width of the section and leaving all other articles hidden behind it.
I have accomplished this portion of the effect without problem. The real issue is getting the article back to where it originally was. Within the article is a "Close" <button>. Once the button is clicked, the effect needs to be reversed (ie. The article returns to original size, only showing the image, and returns to its original position.)
Current Theory
I think I need to retrieve the offset().left information from each article per section, and make sure it's associated with its respective article, so that the article knows where to go once the "Close" button is clicked. I'm of course open to different interpretations.
I've been trying to use the $.each, each(), $.map, map() and toArray() functions to know avail.
Actual Code
/*CSS*/
section > article.window {
width:170px;
height:200px;
padding:0;
margin:4px 0 0 4px;
position:relative;
float:left;
overflow:hidden;
}
section > article.window:nth-child(1) {margin-left:0;}
<!--HTML-->
<article class="window">
<img alt="Title-1" />
<p><!-- I'm a paragraph filled with text --></p>
<button class="sClose">Close</button>
</article>
<article class="window">
<!-- Ditto + 2 more -->
</article>
Failed Attempt Example
function winSlide() {
var aO = $(this).parent().offset()
var aOL = aO.left
var dO = $(this).offset()
var dOL = dO.left
var dOT = dO.top
var adTravel = dOL-aOL
$(this).addClass('windowOP');
$(this).children('div').animate({left:-(adTravel-3)+'px', width:'740px'},250)
$(this).children('div').append('<button class="sClose">Close</button>');
$(this).unbind('click', winSlide);
}
$('.window').on('click', winSlide)
$('.window').on('click', 'button.sClose', function() {
var wW = $(this).parents('.window').width()
var aO = $(this).parents('section').offset()
var aOL = aO.left
var pOL = $(this).parents('.window').offset().left
var apTravel = pOL - aOL
$(this).parent('div').animate({left:'+='+apTravel+'px'},250).delay(250, function() {$(this).animate({width:wW+'px'},250); $('.window').removeClass('windowOP');})
$('.window').bind('click', winSlide)
})
Before you go scratching your head, I have to make a note that this attempt involved an extra div within the article. The idea was to have the article's overflow set to visible (.addclass('windowOP')) with the div moving around freely. This method actually did work... almost. The animation would fail after it fired off a second time. Also for some reason when closing the first article, the left margin was property was ignored.
ie.
First time a window is clicked: Performs open animation flawlessly
First time window's close button is clicked: Performs close animation flawlessly, returns original position
Second time SAME window is clicked: Animation fails, but opens to correct size
Second time window's close button is clicked (if visible): Nothing happens
Thank you for your patience. If you need anymore information, just ask.
EDIT
Added a jsfiddle after tinkering with Flambino's code.
http://jsfiddle.net/6RV88/66/
The articles that are not clicked need to remain where they are. Having problems achieving that now.
If you want to go for storing the offsets, you can use jQuery's .data method to store data "on" the elements and retrieve it later:
// Store offset before any animations
// (using .each here, but it could also be done in a click handler,
// before starting the animation)
$(".window").each(function () {
$(this).data("closedOffset", $(this).position());
});
// Retrieve the offsets later
$('.window').on('click', 'button.sClose', function() {
var originalOffset = $(this).data("originalOffset");
// ...
});
Here's a (very) simple jsfiddle example
Update: And here's a more fleshed-out one
Big thanks to Flambino
I was able to create the effect desired. You can see it here: http://jsfiddle.net/gck2Y/ or you can look below to see the code and some explanations.
Rather than having each article's offset be remembered, I used margins on the clicked article's siblings. It's not exactly pretty, but it works exceptionally well.
<!-- HTML -->
<section>
<article>Click!</article>
<article>Me Too</article>
<article>Me Three</article>
<article>I Aswell</article>
</section>
/* CSS */
section {
position: relative;
width: 404px;
border: 1px solid #000;
height: 100px;
overflow:hidden
}
article {
height:100px;
width:100px;
position: relative;
float:left;
background: green;
border-right:1px solid orange;
}
.expanded {z-index:2;}
//Javascript
var element = $("article");
element.on("click", function () {
if( !$(this).hasClass("expanded") ) {
$(this).addClass("expanded");
$(this).data("originalOffset", $(this).offset().left);
element.data("originalSize", {
width: element.width(),
height: element.height()
});
var aOffset = $(this).data("originalOffset");
var aOuterWidth = $(this).outerWidth();
if(!$(this).is('article:first-child')){
$(this).prev().css('margin-right',aOuterWidth)
} else {
$(this).next().css('margin-left',aOuterWidth)
}
$(this).css({'position':'absolute','left':aOffset});
$(this).animate({
left: 0,
width: "100%"
}, 500);
} else {
var offset = $(this).data("originalOffset");
var size = $(this).data("originalSize");
$(this).animate({
left: offset + "px",
width: size.width + "px"
}, 500, function () {
$(this).removeClass("expanded");
$(this).prev().css('margin-right','0')
$(this).next().css('margin-left','0')
element.css({'position':'relative','left':0});
});
}
});​

Scroll to bottom of div?

I am creating a chat using Ajax requests and I'm trying to get messages div to scroll to the bottom without much luck.
I am wrapping everything in this div:
#scroll {
height:400px;
overflow:scroll;
}
Is there a way to keep it scrolled to the bottom by default using JS?
Is there a way to keep it scrolled to the bottom after an ajax request?
Here's what I use on my site:
var objDiv = document.getElementById("your_div");
objDiv.scrollTop = objDiv.scrollHeight;
This is much easier if you're using jQuery scrollTop:
$("#mydiv").scrollTop($("#mydiv")[0].scrollHeight);
Try the code below:
const scrollToBottom = (id) => {
const element = document.getElementById(id);
element.scrollTop = element.scrollHeight;
}
You can also use Jquery to make the scroll smooth:
const scrollSmoothlyToBottom = (id) => {
const element = $(`#${id}`);
element.animate({
scrollTop: element.prop("scrollHeight")
}, 500);
}
Here is the demo
Here's how it works:
Ref: scrollTop, scrollHeight, clientHeight
using jQuery animate:
$('#DebugContainer').stop().animate({
scrollTop: $('#DebugContainer')[0].scrollHeight
}, 800);
Newer method that works on all current browsers:
this.scrollIntoView(false);
var mydiv = $("#scroll");
mydiv.scrollTop(mydiv.prop("scrollHeight"));
Works from jQuery 1.6
https://api.jquery.com/scrollTop/
http://api.jquery.com/prop/
alternative solution
function scrollToBottom(element) {
element.scroll({ top: element.scrollHeight, behavior: 'smooth' });
}
smooth scroll with Javascript:
document.getElementById('messages').scrollIntoView({ behavior: 'smooth', block: 'end' });
If you don't want to rely on scrollHeight, the following code helps:
$('#scroll').scrollTop(1000000);
Java Script:
document.getElementById('messages').scrollIntoView(false);
Scrolls to the last line of the content present.
My Scenario: I had an list of string, in which I had to append a string given by a user and scroll to the end of the list automatically. I had fixed height of the display of the list, after which it should overflow.
I tried #Jeremy Ruten's answer, it worked, but it was scrolling to the (n-1)th element. If anybody is facing this type of issue, you can use setTimeOut() method workaround. You need to modify the code to below:
setTimeout(() => {
var objDiv = document.getElementById('div_id');
objDiv.scrollTop = objDiv.scrollHeight
}, 0)
Here is the StcakBlitz link I have created which shows the problem and its solution : https://stackblitz.com/edit/angular-ivy-x9esw8
If your project targets modern browsers, you can now use CSS Scroll Snap to control the scrolling behavior, such as keeping any dynamically generated element at the bottom.
.wrapper > div {
background-color: white;
border-radius: 5px;
padding: 5px 10px;
text-align: center;
font-family: system-ui, sans-serif;
}
.wrapper {
display: flex;
padding: 5px;
background-color: #ccc;
border-radius: 5px;
flex-direction: column;
gap: 5px;
margin: 10px;
max-height: 150px;
/* Control snap from here */
overflow-y: auto;
overscroll-behavior-y: contain;
scroll-snap-type: y mandatory;
}
.wrapper > div:last-child {
scroll-snap-align: start;
}
<div class="wrapper">
<div>01</div>
<div>02</div>
<div>03</div>
<div>04</div>
<div>05</div>
<div>06</div>
<div>07</div>
<div>08</div>
<div>09</div>
<div>10</div>
</div>
You can use the HTML DOM scrollIntoView Method like this:
var element = document.getElementById("scroll");
element.scrollIntoView();
Javascript or jquery:
var scroll = document.getElementById('messages');
scroll.scrollTop = scroll.scrollHeight;
scroll.animate({scrollTop: scroll.scrollHeight});
Css:
.messages
{
height: 100%;
overflow: auto;
}
Using jQuery, scrollTop is used to set the vertical position of scollbar for any given element. there is also a nice jquery scrollTo plugin used to scroll with animation and different options (demos)
var myDiv = $("#div_id").get(0);
myDiv.scrollTop = myDiv.scrollHeight;
if you want to use jQuery's animate method to add animation while scrolling down, check the following snippet:
var myDiv = $("#div_id").get(0);
myDiv.animate({
scrollTop: myDiv.scrollHeight
}, 500);
I have encountered the same problem, but with an additional constraint: I had no control over the code that appended new elements to the scroll container. None of the examples I found here allowed me to do just that. Here is the solution I ended up with .
It uses Mutation Observers (https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver) which makes it usable only on modern browsers (though polyfills exist)
So basically the code does just that :
var scrollContainer = document.getElementById("myId");
// Define the Mutation Observer
var observer = new MutationObserver(function(mutations) {
// Compute sum of the heights of added Nodes
var newNodesHeight = mutations.reduce(function(sum, mutation) {
return sum + [].slice.call(mutation.addedNodes)
.map(function (node) { return node.scrollHeight || 0; })
.reduce(function(sum, height) {return sum + height});
}, 0);
// Scroll to bottom if it was already scrolled to bottom
if (scrollContainer.clientHeight + scrollContainer.scrollTop + newNodesHeight + 10 >= scrollContainer.scrollHeight) {
scrollContainer.scrollTop = scrollContainer.scrollHeight;
}
});
// Observe the DOM Element
observer.observe(scrollContainer, {childList: true});
I made a fiddle to demonstrate the concept :
https://jsfiddle.net/j17r4bnk/
Found this really helpful, thank you.
For the Angular 1.X folks out there:
angular.module('myApp').controller('myController', ['$scope', '$document',
function($scope, $document) {
var overflowScrollElement = $document[0].getElementById('your_overflow_scroll_div');
overflowScrollElement[0].scrollTop = overflowScrollElement[0].scrollHeight;
}
]);
Just because the wrapping in jQuery elements versus HTML DOM elements gets a little confusing with angular.
Also for a chat application, I found making this assignment after your chats were loaded to be useful, you also might need to slap on short timeout as well.
Like you, I'm building a chat app and want the most recent message to scroll into view. This ultimately worked well for me:
//get the div that contains all the messages
let div = document.getElementById('message-container');
//make the last element (a message) to scroll into view, smoothly!
div.lastElementChild.scrollIntoView({ behavior: 'smooth' });
small addendum: scrolls only, if last line is already visible. if scrolled a tiny bit, leaves the content where it is (attention: not tested with different font sizes. this may need some adjustments inside ">= comparison"):
var objDiv = document.getElementById(id);
var doScroll=objDiv.scrollTop>=(objDiv.scrollHeight-objDiv.clientHeight);
// add new content to div
$('#' + id ).append("new line at end<br>"); // this is jquery!
// doScroll is true, if we the bottom line is already visible
if( doScroll) objDiv.scrollTop = objDiv.scrollHeight;
Just as a bonus snippet. I'm using angular and was trying to scroll a message thread to the bottom when a user selected different conversations with users. In order to make sure that the scroll works after the new data had been loaded into the div with the ng-repeat for messages, just wrap the scroll snippet in a timeout.
$timeout(function(){
var messageThread = document.getElementById('message-thread-div-id');
messageThread.scrollTop = messageThread.scrollHeight;
},0)
That will make sure that the scroll event is fired after the data has been inserted into the DOM.
This will let you scroll all the way down regards the document height
$('html, body').animate({scrollTop:$(document).height()}, 1000);
You can also, using jQuery, attach an animation to html,body of the document via:
$("html,body").animate({scrollTop:$("#div-id")[0].offsetTop}, 1000);
which will result in a smooth scroll to the top of the div with id "div-id".
Scroll to the last element inside the div:
myDiv.scrollTop = myDiv.lastChild.offsetTop
You can use the Element.scrollTo() method.
It can be animated using the built-in browser/OS animation, so it's super smooth.
function scrollToBottom() {
const scrollContainer = document.getElementById('container');
scrollContainer.scrollTo({
top: scrollContainer.scrollHeight,
left: 0,
behavior: 'smooth'
});
}
// initialize dummy content
const scrollContainer = document.getElementById('container');
const numCards = 100;
let contentInnerHtml = '';
for (let i=0; i<numCards; i++) {
contentInnerHtml += `<div class="card mb-2"><div class="card-body">Card ${i + 1}</div></div>`;
}
scrollContainer.innerHTML = contentInnerHtml;
.overflow-y-scroll {
overflow-y: scroll;
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/css/bootstrap.min.css" rel="stylesheet"/>
<div class="d-flex flex-column vh-100">
<div id="container" class="overflow-y-scroll flex-grow-1"></div>
<div>
<button class="btn btn-primary" onclick="scrollToBottom()">Scroll to bottom</button>
</div>
</div>
Css only:
.scroll-container {
overflow-anchor: none;
}
Makes it so the scroll bar doesn't stay anchored to the top when a child element is added. For example, when new message is added at the bottom of chat, scroll chat to new message.
Why not use simple CSS to do this?
The trick is to use display: flex; and flex-direction: column-reverse;
Here is a working example. https://codepen.io/jimbol/pen/YVJzBg
A very simple method to this is to set the scroll to to the height of the div.
var myDiv = document.getElementById("myDiv");
window.scrollTo(0, myDiv.innerHeight);
On my Angular 6 application I just did this:
postMessage() {
// post functions here
let history = document.getElementById('history')
let interval
interval = setInterval(function() {
history.scrollTop = history.scrollHeight
clearInterval(interval)
}, 1)
}
The clearInterval(interval) function will stop the timer to allow manual scroll top / bottom.
I know this is an old question, but none of these solutions worked out for me. I ended up using offset().top to get the desired results. Here's what I used to gently scroll the screen down to the last message in my chat application:
$("#html, body").stop().animate({
scrollTop: $("#last-message").offset().top
}, 2000);
I hope this helps someone else.
I use the difference between the Y coordinate of the first item div and the Y coordinate of the selected item div. Here is the JavaScript/JQuery code and the html:
function scrollTo(event){
// In my proof of concept, I had a few <button>s with value
// attributes containing strings with id selector expressions
// like "#item1".
let selectItem = $($(event.target).attr('value'));
let selectedDivTop = selectItem.offset().top;
let scrollingDiv = selectItem.parent();
let firstItem = scrollingDiv.children('div').first();
let firstItemTop = firstItem.offset().top;
let newScrollValue = selectedDivTop - firstItemTop;
scrollingDiv.scrollTop(newScrollValue);
}
<div id="scrolling" style="height: 2rem; overflow-y: scroll">
<div id="item1">One</div>
<div id="item2">Two</div>
<div id="item3">Three</div>
<div id="item4">Four</div>
<div id="item5">Five</div>
</div>

Categories