Auto-scroll to bottom of the result fetched by ajax - javascript

I'm making a live chat website for my users. I'm fetching the chat messages via ajax.
Whenever I enter a new message, it does get added to the database and is displayed, but the scroll doesn't go to the bottom of the results.
Here's the example :-
When I type in a new message. The scroll doesn't go to the bottom.
When I manually scroll, then I get all the messages.
Here's my HTML div in which data is fetched via ajax.
<div id="chat">
</div>
I tried this, but it didn't work.
window.setInterval(function(){
var elem = document.getElementById('chat');
elem.scrollTop = elem.scrollHeight;
}, 1000);
What would be the best way to get my result ?

I did a little more than was asked for, but here's my answer. Please note that I did not include the AJAX function, and instead used the first message as a template, and just inserted that over and over to simulate new messages from AJAX. You would replace the line $('#msg-template').clone()... with your AJAX function, and the completion function that runs after AJAX should contain the next line: if(autoScroll){ ScrollChat(); }.
The fiddle has comments too (and some HTML and CSS): http://jsfiddle.net/mmwu1920/
var autoScroll = true;
function ScrollChat(){
$('#chat').scrollTop($('#chat')[0].scrollHeight).trigger('scroll');
}
function RefreshMessages(){
$('#msg-template').clone().appendTo('#chat');
if(autoScroll){ ScrollChat(); }
}
setInterval(RefreshMessages, 1000);
ScrollChat();
$('#chat').on('scroll', function(){
if($(this).scrollTop() < this.scrollHeight - $(this).height()){
autoScroll = false;
}
else{
autoScroll = true;
}
});

Set the scroll position on the parent element (or the element that has the scrollbar):
<div id="container">
<div id="chat">
</div>
</div>
-
window.setInterval(function(){
var elem = document.getElementById('container');
elem.scrollTop = elem.scrollHeight;
}, 1000);

Related

how to hide django message after it is displayed for few seconds

For example, before redirect, I used
messages.add_message(request, messages.INFO, 'You have successfully updated your listing.')
Then the message will be automatically displayed after redirection, however the message will never disappear, may I know how to hide it after few seconds?
Thanks!!!
You need to write javascript code, use window setTimeout() method to hide message after some time.
// suppose the `id` attribute of element is `message_container`.
var message_ele = document.getElementById("message_container");
setTimeout(function(){
message_ele.style.display = "none";
}, 3000);
// Timeout is 3 sec, you can change it
Put this code inside base.html at the bottom inside <script> tag, so whenever page reloaded after 3
sec it will make your message disappear.
the script:
<script>
setTimeout(function(){
if ($('#msg').length > 0) {
$('#msg').remove();
}
}, 2000) // 2000 millisecond
</script>
the template:
<div id="msg">
{{message}}
</div>
To hide only messages with a certain tag (e.g only INFO messages) you can use the following code inside your HTML document.
<script>
// Get all info messages
var info_messages = document.getElementsByClassName('alert-info');
setTimeout(function(){
for (var i = 0; i < info_messages.length; i ++) {
// Set display attribute as !important, neccessary when using bootstrap
info_messages[i].setAttribute('style', 'display:none !important');
}
}, 3000);
</script>
This one is working fine for me:
var message_ele = document.getElementById("msg");
setTimeout(function() {
message_ele.style.display = "none";
}, 3000);
<span id="msg">
{{messages}}
</span>

Onload need to work only once

Good day everyone i'm having a trouble about working my onload only once . because when i refreshes the page or if i am going to another page it always load.
here is my code so far:
JS
<!--Auto load the on overlay function-->
<script>
window.onload = function openNav() {
document.getElementById("myNav").style.width = "100%";
splashScreen();
}
function closeNav() {
document.getElementById("myNav").style.width = "0%";
}
</script>
and here's my js functionality for my splashscreen.js
//use onload when in your html the context is not inside
//the <header>
//create a splashScreen function
function splashScreen(){
//get the element on the html side with the id of "skip"
var skipButton = document.getElementById("skip");
//counter for the countdown
var counter = 5;
//create an element <p>
var newElement = document.createElement("p");
newElement.innerHTML = "Skip this 5 seconds";
var id;
skipButton.parentNode.replaceChild(newElement, skipButton);
id = setInterval(function(){
counter--;
if(counter < 0){
//replace the newElement on else condition statement
newElement.parentNode.replaceChild(skipButton, newElement);
clearInterval(id);
} else {
newElement.innerHTML = "You can skip this in " + counter.toString() + " seconds.";
}
}, 1000);
}
and this is how i call it on my html
<html>
<body>
<!--SplashScreen JS-->
<script src="<?php echo base_url('assets/public/js/splashscreen.js');?>">
</script>
When you refresh the page or go to another page, then back to your original page, the page is reloading, thus the onLoad handler is being called.
If you want certain functionality to only happen once, then one thing you can try is setting a cookie that you can check on page load. If the cookie is set, you know you already loaded it once, and don't run the code again. If not, you run the code, then set the cookie.
Useful link for cookies:
https://www.w3schools.com/js/js_cookies.asp
To be able to know that the splash screen has already been displayed for a given user, you need to store something to that effect that persists between page load events. Since the page will reload when the refresh button is clicked or when coming back to the page after being there earlier, this stored item can't be in the page itself, because it will just get reinitialized every time the page loads.
Cookies (as mentioned in another answer) are an option, but localStorage, I think is much simpler. It works like this:
// Once the window is loaded...
window.addEventListener("load", function(){
// Check localStorage to see if the splash screen
// has NOT already been displayed
if(!localStorage.getItem("splash")){
// Splash has not been displayed, so show it:
splashScreen();
// Store a value in localStorage to denote that the splash screen
// has now been displayed
localStorage.setItem("splash", "true");
}
});
One approach is to set .name property of window, which remains set after window.
const NAME = "once";
window.onload = function openNav() {
document.getElementById("myNav").style.width = "100%";
if (this.name !== NAME) {
this.name = NAME;
splashScreen();
} else {
// do other stuff
console.log(this.name)
}
}

Chat div to scroll to bottom so as to display last message

I am making a web chat. I have a div called chatbody. I want the div to scroll to bottom using javascript so that the last message is displayed. However, the code that I am using scrolls it to top instead. Here is the code:
<script type="text/javascript">
function chatbody() {
var myDiv = document.getElementByClassName('chatbody');
myDiv.innerHTML = variableLongText;
myDiv.scrollTop = 0;
}
</script>
Kindly assist to solve my issue.
Try This
var myDiv = document.getElementByClassName('chatbody')[0];
function scrollToBottom(nameOfBlock) {
nameOfBlock.scrollTop = nameOfBlock.scrollHeight
}
U can pass your variable as an argument

reload div javascript only ajax needed?

please refer to JSFiddle link: https://jsfiddle.net/s11oo2gg/.
We are not allowed to use jQuery and iframe here.
The problem right now if you click on resistor first and hover over different content images then come back out by clicking the X mark, the content image would get stucked where you left off and would not load the the other content images properly. It would show a broken image link.
I like to reload only the <div id="slider1_contain"> everytime I click on <span class="closeButton">(X mark) so the target content images can be loaded accordingly.
I dont not want to have location.reload(); to resolve this when the X is click. I dont want to reload the whole page but only the div.
I saw people were asking the same question and solve it with AJAX. Do I need AJAX for this case? Or is there something we can do in the following javascript?
Thank you in advance!!
<script type="text/javascript">
function showContent(target){
document.getElementById(target).style.display = 'block';
document.getElementById("boxThumb").style.display = 'none';
}
function hideContent(target){
document.getElementById(target).style.display = 'none';
document.getElementById("boxThumb").style.display = 'block'
}
</script>
<script type="text/javascript">
var children = document.querySelectorAll('.toggle > section[id]');
function showDetailContent(target) {
// Simply loop over our children and ensure they are hidden:
for (var i = 0, child; child = children[i]; i++) {
child.style.display = 'none';
}
// Now, show our child we want to show
document.getElementById(target).style.display = 'block';
}
</script>
If you want to reload just the div, you can use innerHTML.
document.getElementById(target).innerHTML = '<img src="image.jpg">';

How to prevent iframe load event?

I have an iframe and couple of tables on my aspx page. Now when the page loads these tables are hidden. The iframe is used to upload file to database. Depending on the result of the event I have to show a particular table on my main page (these tables basically have "Retry","next" buttons...depending on whether or not the file is uploaded I have to show respective button).
Now I have a JavaScript on the "onload" event of the iframe where I am hiding these tables to start with. When the control comes back after the event I show a particular table. But then the iframe loads again and the tables are hidden. Can any one help me with this problem. I don't want the iframe to load the second time.
Thanks
mmm you said you're on aspx page,
I suppose that the iframe do a postback, so for this it reload the page.
If you can't avoid the postback, you've to set a flag on the main page just before posting back, and check against that while you're loading...
...something like:
mainpage.waitTillPostBack = true
YourFunctionCausingPostBack();
..
onload=function(){
if(!mainpage.waitTillPostBack){
hideTables();
}
mainpage.waitTillPostBack = false;
}
I am not sure what your problem is, but perhaps your approach should be a little different. Try putting code into the iframe what would call functions of the parent. These functions would display the proper table:
<!-- in the main page --->
function showTable1() {}
<!-- in the iframe -->
window.onload = function () {
parent.showTable1();
}
This would put a lot of control into your iframe, away from the main page.
I don't have enough specifics from your question to determine if the iframe second load can be prevented. But I would suggest using a javascript variable to check if the iframe is being loaded a second time and in that case skip the logic for hiding the tables,
This is my code
function initUpload()
{
//alert("IFrame loads");
_divFrame = document.getElementById('divFrame');
_divUploadMessage = document.getElementById('divUploadMessage');
_divUploadProgress = document.getElementById('divUploadProgress');
_ifrFile = document.getElementById('ifrFile');
_tbRetry = document.getElementById('tbRetry');
_tbNext=document.getElementById('tblNext');
_tbRetry.style.display='none';
_tbNext.style.display='none';
var btnUpload = _ifrFile.contentWindow.document.getElementById('btnUpload');
btnUpload.onclick = function(event)
{
var myFile = _ifrFile.contentWindow.document.getElementById('myFile');
//Baisic validation
_divUploadMessage.style.display = 'none';
if (myFile.value.length == 0)
{
_divUploadMessage.innerHTML = '<span style=\"color:#ff0000\">Please select a file.</span>';
_divUploadMessage.style.display = '';
myFile.focus();
return;
}
var regExp = /^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))(.doc|.txt|.xls|.docx |.xlsx)$/;
if (!regExp.test(myFile.value)) //Somehow the expression does not work in Opera
{
_divUploadMessage.innerHTML = '<span style=\"color:#ff0000\">Invalid file type. Only supports doc, txt, xls.</span>';
_divUploadMessage.style.display = '';
myFile.focus();
return;
}
_ifrFile.contentWindow.document.getElementById('Upload').submit();
_divFrame.style.display = 'none';
}
}
function UploadComplete(message, isError)
{
alert(message);
//alert(isError);
clearUploadProgress();
if (_UploadProgressTimer)
{
clearTimeout(_UploadProgressTimer);
}
_divUploadProgress.style.display = 'none';
_divUploadMessage.style.display = 'none';
_divFrame.style.display = 'none';
_tbNext.style.display='';
if (message.length)
{
var color = (isError) ? '#008000' : '#ff0000';
_divUploadMessage.innerHTML = '<span style=\"color:' + color + '\;font-weight:bold">' + message + '</span>';
_divUploadMessage.style.display = '';
_tbNext.style.display='';
_tbRetry.style.display='none';
}
}
tblRetry and tblNext are the tables that I want to display depending on the result of the event.

Categories

Resources