jquery scrolltop stay position after response - javascript

I wrote a code to view the chat history. Everything works fine, but I realized that. When you scroll up the div to view the history, old posts are displayed at a time. I've added this code $("#messages").scrollTop(200); to be able to continue scrolling, but this should not be. When you want to view old messages in apps like whatsapp or facebook, you can continue to scroll up for viewing old messages.
What am I supposed to do to stay position after response?
Here is DEMO page.
$(document).ready(function() {
var logDown = $(".chatContainer");
logDown.animate({ scrollTop: logDown.prop("scrollHeight") }, 0);
var messages = ''; // New Posts are in demo
var scrollLoading = true;
$("#messages").scrollTop($("#messages")[0].scrollHeight);
$("#messages").on("scroll", function() {
if (scrollLoading && $("#messages").scrollTop() == 0) {
$("#messages").prepend(messages);
$("#messages").scrollTop(200);
}
});
});

now I understood, i solved it by subtracting the old-height from the new height and set this "old-position" as scrolltop
var old_height,new_height;
$("#messages").on("scroll", function() {
if (scrollLoading && $("#messages").scrollTop() == 0) {
old_height = $("#messages")[0].scrollHeight;
$("#messages").prepend(messages);
new_height = $("#messages")[0].scrollHeight;
$("#messages").scrollTop(new_height - old_height);
}
});
works optimal for me

If I understood your problem you don't want to scroll to the top of the messages at every batch of prepends.
I managed to pull a version without jQuery and using window.requestAnimationFrame for good scroll performance.
Just my $0.02 on the problem.
var container = document.querySelector("#messages");
container.scrollTop = container.scrollHeight;
container.addEventListener("scroll", function(e) {
last_known_scroll_position = e.target.scrollTop;
var ticking;
if (!ticking) {
window.requestAnimationFrame(function() {
if (last_known_scroll_position == 0) {
var delta = e.target.scrollHeight;
for (var i = 1; i <= 5; i++) {
var message = document.createElement("DIV");
message.textContent = "Message Here";
message.classList.add("message", "red");
e.target.prepend(message);
}
delta = e.target.scrollHeight - delta;
e.target.scrollTop = delta;
ticking = false;
}
});
ticking = true;
}
});
DIV.chatContainer {
height: 200px;
overflow: auto;
}
.message {
margin-bottom:10px;
}
.red {
background-color:red;
}
<div class="container">
<div class="chatContainer" id="messages">
<div class="message">Message HERE</div>
<div class="message">Message HERE</div>
<div class="message">Message HERE</div>
<div class="message">Message HERE</div>
<div class="message">Message HERE</div>
<div class="message">Message HERE</div>
<div class="message">Message HERE</div>
<div class="message">Message HERE</div>
<div class="message">Message HERE</div>
<div class="message">Message HERE</div>
<div class="message">Message HERE</div>
<div class="message">Message HERE</div>
<div class="message">Message HERE</div>
<div class="message">Message HERE last</div>
</div>
</div>

Related

change properties of two divs with one onclick and querySelectorAll()

I have multiple elements that are seperatet in two divs. The first div contains a Text and the second div a color.
When I click on one element the text and color should change and if I click it again it should change back.
The problem is that no matter which one I click, its always the last one which changes.
The HTML part:
<style>
.colorGreen {
background-color: green;
}
.colorRed {
background-color: red;
}
</style>
<div class="box2">Text1</div>
<div class="box1 colorGreen">O</div>
<div class="box2">Text1</div>
<div class="box1 colorGreen">O</div>
<div class="box2">Text1</div>
<div class="box1 colorGreen">O</div>
The JavaScript part:
<script type='text/javascript'>
var box1Temp = document.querySelectorAll(".box1");
var box2Temp = document.querySelectorAll(".box2");
for (var i = 0; i < box1Temp.length; i++) {
var box1 = box1Temp[i];
var box2 = box2Temp[i];
box2.onclick = box1.onclick = function() {
if (box1.classList.contains("colorGreen")) {
box1.classList.add("colorRed");
box1.classList.remove("colorGreen");
box2.innerHTML = "Text2";
} else {
box1.classList.add("colorGreen");
box1.classList.remove("colorRed");
box2.innerHTML = "Text1";
}
}
}
</script>
It works, when I use only one div.
Then I can use 'this', instead of the 'box1' variable, to addres the right element.
But if I replace 'box1' with 'this' its still the text div that changes.
(I know it's obvious that this is happening, but I'm lost)
With a few small tweaks, this can be written a lot more cleanly:
// Capture click event for parent container, .toggle-set
for (const ele of document.querySelectorAll(".toggle-set")) {
ele.addEventListener("click", function() {
// Grab text and color elements
const textToggle = ele.querySelector(".toggle-text");
const colorToggle = ele.querySelector(".toggle-color");
// Toggle text
// NOTE: This could use further refinement with regex or something similar to strip whitespace before comparison
textToggle.textContent = textToggle.textContent == "Text1" ? "Text2" : "Text1";
// Toggle css classes
colorToggle.classList.toggle("colorGreen");
colorToggle.classList.toggle("colorRed");
});
}
.colorGreen { background-color: green; }
.colorRed { background-color: red; }
<div class="toggle-set">
<div class="toggle-text">Text1</div>
<div class="toggle-color colorGreen">
O
</div>
</div>
<div class="toggle-set">
<div class="toggle-text">Text1</div>
<div class="toggle-color colorGreen">
O
</div>
</div>
Your code is so confused
You were right for the this option.
you can do with simple onclick function :
function change(el){
box1 = el.querySelector('.box1');
box2 = el.querySelector('.box2');
if (box1.classList.contains("colorGreen")) {
box1.classList.add("colorRed");
box1.classList.remove("colorGreen");
box2.innerHTML = "Text2";
} else {
box1.classList.add("colorGreen");
box1.classList.remove("colorRed");
box2.innerHTML = "Text1";
}
}
<style>
.colorGreen {
background-color: green;
}
.colorRed {
background-color: red;
}
</style>
<div onclick="change(this)">
<div class="box2">Text1</div>
<div class="box1 colorGreen">O</div>
</div>
<div onclick="change(this)">
<div class="box2">Text1</div>
<div class="box1 colorGreen">O</div>
</div>
<div onclick="change(this)">
<div class="box2">Text1</div>
<div class="box1 colorGreen">O</div>
</div>
I think following code snippet would help you to get your desired result
let box1 = document.querySelectorAll(".box1");
let box2 = document.querySelectorAll(".box2");
box1.forEach((b1,i) => {
b1.addEventListener("click",(ev) => {
ev.target.classList.toggle("colorGreen");
ev.target.classList.toggle("colorRed");
console.log(box2[i]);
if(ev.target.classList.contains("colorGreen")){
box2[i].textContent = "Text1";
}else{
box2[i].textContent = "Text2"
}
})
})

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 page turn function - vanilla javascript

I want to write a dynamic function for an element with several pages. At time just one page is visible and with a click on the forward or backward button the next or previous page is shown.
I have several of these elements with different amount of pages.
function pageTurn(forwardID, backwardID, pageClass, counter, numbers) {
var forward = document.getElementById(forwardID);
var backward = document.getElementById(backwardID);
var page = document.getElementsByClassName(pageClass);
var count = document.getElementById(counter);
var pageCount = 1;
forward.addEventListener('click', function() {
pageCount ++;
count.innerHTML = pageCount + ' / ' + numbers;
page[pageCount - 2].classList.add('invisible')
page[pageCount - 2].addEventListener("transitionend", OnTransitionEnd());
buttonCheck();
})
backward.addEventListener('click', function() {
pageCount --;
count.innerHTML = pageCount + ' / ' + numbers;
page[pageCount].classList.add('invisible')
page[pageCount].addEventListener("transitionend", OnTransitionEnd());
buttonCheck();
})
function buttonCheck() {
//SHOW AND HIDE PAGETURN BUTTONS
if(pageCount == 1) {
backward.classList.add('invisible');
} else if (pageCount > 1) {
backward.classList.remove('invisible');
} else if (pageCount == numbers) {
forward.classList.add('invisible');
} else if (pageCount < numbers) {
forward.classList.remove('invisible');
}
}
function OnTransitionEnd() {
page[pageCount - 1].classList.remove('invisible');
}
}
Same logic for the backwards button, just reversed.
I want the function to add value of 1 to the pageCount on a click on the forward button. To dynamicly add and remove the .invisible class from the page element i want to use the pageCount variable to choose the right page out of the class array. But it doesn't work.
What am i doing wrong here?
https://jsfiddle.net/1qt8p9of/12/
There are quite a few things to consider here: I think you'd be better of posting on codereview.stackexchange.com.
However, here's a snippet where I slightly modified the code you provided to make it work. Don't hesitate to take a look!
function initialize(forwardID, backwardID, pageClass) {
const forward = document.getElementById(forwardID);
const backward = document.getElementById(backwardID);
const pages = document.getElementsByClassName(pageClass);
let counter = 0;
function buttonCheck() {
if (counter <= 0) {
backward.setAttribute('disabled', true);
} else {
backward.removeAttribute('disabled');
}
if (counter >= pages.length - 1) {
forward.setAttribute('disabled', true);
} else {
forward.removeAttribute('disabled');
}
}
forward.addEventListener('click', function() {
pages[counter].classList.add('invisible');
counter++;
pages[counter].classList.remove('invisible');
buttonCheck();
});
backward.addEventListener('click', function() {
pages[counter].classList.add('invisible');
counter--;
pages[counter].classList.remove('invisible');
buttonCheck();
});
}
initialize('forwards', 'backwards', 'page');
initialize('forwards2', 'backwards2', 'page2');
.pages .invisible {
display: none;
}
<fieldset>
<legend>First set of page</legend>
<div class="controls">
<button id="backwards" disabled>←</button>
<button id="forwards">→</button>
</div>
<div class="pages">
<div class="page">Page One</div>
<div class="page invisible">Page Two</div>
<div class="page invisible">Page Three</div>
<div class="page invisible">Last Page</div>
</div>
</fieldset>
<hr />
<fieldset>
<legend>Second set of pages</legend>
<div class="controls">
<button id="backwards2" disabled>←</button>
<button id="forwards2">→</button>
</div>
<div class="pages">
<div class="page2">Page One</div>
<div class="page2 invisible">Page Two</div>
<div class="page2 invisible">Page Three</div>
<div class="page2 invisible">Page Four</div>
<div class="page2 invisible">Last Page</div>
</div>
</fieldset>
I hope this will help you.

Fire AJAX jQuery if scroll reach to each div

I want make ajax fire if scroll reach to each div element.
Item div 1
Item div 2 (fire ajax if scroll to this element)
Item div 3 (fire ajax again if scroll to this element)
Item .....N
I use this code, but only fire if scroll to end.
$( window ).scroll( function() {
if( $( window ).scrollTop() == $( document ).height() - $( window ).height() ) {
alert('Fire!');
}
});
Please help.
Use $.offset().top instead of heights.
To check all sections you can use $.each(). Since I am guessing you only want to fire the event once, you will need a variable to remember all sections, that already fired.
let firedEvents = [];
$(window).scroll(function() {
$("div.section").each(function() {
if (!firedEvents.includes(this) && $(window).scrollTop() > $(this).offset().top) {
firedEvents.push(this);
alert("fire " + $(this).data("nr"));
}
});
});
div {
height: 500px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="section" data-nr="0" style="background-color: red;"></div>
<div class="section" data-nr="1" style="background-color: green;"></div>
<div class="section" data-nr="2" style="background-color: blue;"></div>
<div class="section" data-nr="3" style="background-color: yellow;"></div>
I took the liberty of writing a simple html that will fullfil your needs.
In my example scroll happens via button click; u can change it with your usecase; Hope this helps; here's the fiddle https://jsfiddle.net/39z82axt/
html
<div id="wrapper">
<div class="divel">Element 1</div>
<div class="divel">Element 2</div>
<div class="divel">Element 3</div>
<div class="divel">Element 4</div>
<div class="divel">Element 5</div>
</div>
<button id="scrollButton">
Click to Scroll
</button>
css
.divel {
height:80px;
}
#wrapper {
height: 100px;
overflow:scroll;
}
js
let crossedFirstDiv = false,
crossedSecondDiv = false;
document.getElementById('scrollButton').onclick = function() {
document.getElementById("wrapper").scrollTop += 10;
let scrollLocation = scrollPosition("wrapper");
if (scrollLocation > 10 && scrollLocation <20 && crossedFirstDiv == false) {
alert("crossing div 1");
crossedFirstDiv = true;
}
else if (scrollLocation > 20 && scrollLocation <30 && crossedSecondDiv == false) {
crossedSecondDiv = true;
alert("crossing div 2");
}
// and so on..
}
function scrollPosition(elementId) {
let a = document.getElementById(elementId).scrollTop;
let b = document.getElementById(elementId).scrollHeight - document.getElementById(elementId).clientHeight;
let c = a / b;
return Math.floor(c * 100);
}
$(window).scroll( function() {
var scrolled = $( window ).scrollTop();
$('div:not(.fired)').each(function () {
var position_of_div = $(this).offset();
if (scrolled > position_of_div.top) {
$(this).addClass('fired');
alert('fire');
}
});
});
Save the scrolled pixels in an variable. On scroll get the position of each div. If the amount of pixels scrolled is greater than the offset of the div (related to the document) fire a AJAX call.

managing several show/hide divs

I have some scripts here that show and hide divs when click. Now what I need is to just only display one div at a time. I have a code that controls them all but its not working I don't know about much of javascript.
This is the first example of show/hide function that can be done simultaneously without hiding the other divs.
FIDDLE HERE
HTML:
<a href="javascript:ReverseDisplay('uniquename')">
Click to show/hide.
</a>
<div id="uniquename" style="display:none;">
<p>Content goes here.</p>
</div>
<a href="javascript:ReverseDisplay('uniquename1')">
Click to show/hide.
</a>
<div id="uniquename1" style="display:none;">
<p>Content goes here.</p>
</div>
SCRIPT:
function HideContent(d) {
document.getElementById(d).style.display = "none";
}
function ShowContent(d) {
document.getElementById(d).style.display = "block";
}
function ReverseDisplay(d) {
if (document.getElementById(d).style.display == "none") {
document.getElementById(d).style.display = "block";
} else {
document.getElementById(d).style.display = "none";
}
}
function HideAllShowOne(d) {
// Between the quotation marks, list the id values of each div.
var IDvaluesOfEachDiv = "idone idtwo uniquename1 uniquename";
//-------------------------------------------------------------
IDvaluesOfEachDiv = IDvaluesOfEachDiv.replace(/[,\s"']/g," ");
IDvaluesOfEachDiv = IDvaluesOfEachDiv.replace(/^\s*/,"");
IDvaluesOfEachDiv = IDvaluesOfEachDiv.replace(/\s*$/,"");
IDvaluesOfEachDiv = IDvaluesOfEachDiv.replace(/ +/g," ");
var IDlist = IDvaluesOfEachDiv.split(" ");
for(var i=0; i<IDlist.length; i++) { HideContent(IDlist[i]); }
ShowContent(d);
}
The other fiddle I created would do what I need but the script seems not to be working. Fiddle here
Found the solution on my code thanks to #Abhas Tandon
Fiddle here the extra id's inside the IDvaluesOfEachDiv seems to be making some error with the codes.
If you are happy with IE10+ support then
function ReverseDisplay(d) {
var els = document.querySelectorAll('.toggle.active:not(#' + d + ')');
for (var i = 0; i < els.length; i++) {
els[i].classList.remove('active');
}
document.getElementById(d).classList.toggle('active')
}
.toggle {
display: none;
}
.toggle.active {
display: block;
}
<a href="javascript:ReverseDisplay('uniquename')">
Click to show/hide.
</a>
<div id="uniquename" class="toggle">
<p>Content goes here.</p>
</div>
<a href="javascript:ReverseDisplay('uniquename1')">
Click to show/hide.
</a>
<div id="uniquename1" class="toggle">
<p>Content goes here.</p>
</div>
I would suggest to use jQuery which is far easier.
Include thiswithin
<head>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
</head>
HTML
<div id="id_one">Item 1</div>
<div id="content_one">
content goes here
</div>
<div id="id_two">Item 1</div>
<div id="content_two">
content goes here
</div>
Script:
$(function()
{
$("#content_one").hide();
$("#content_two").hide();
});
$("#id_one").on("click",function()
{
$("#content_one").slideDown("fast");
});
$("#id_two").on("click",function()
{
$("#content_two").slideDown("fast");
});
If you have a "Button" for every DIV inside your HTML - you can go by element index
var btn = document.querySelectorAll(".btn");
var div = document.querySelectorAll(".ele");
function toggleDivs() {
for(var i=0; i<btn.length; i++) {
var us = i===[].slice.call(btn).indexOf(this);
btn[i].tog = us ? this.tog^=1 : 0;
div[i].style.display = ["none","block"][us?[this.tog]:0];
}
}
for(var i=0; i<btn.length; i++) btn[i].addEventListener("click", toggleDivs);
.btn{/* Anchors Buttons */ display:block; cursor:pointer; color:#00f;}
.ele{/* Hidden Divs */ display:none;}
<a class="btn"> 1Click to show/hide.</a>
<div class="ele"><p>1Content goes here.</p></div>
<hr>
<a class="btn">2Click to show/hide.</a>
<div class="ele"><p>2Content goes here.</p></div>
<hr>

Categories

Resources