Span value inside a style value - javascript

this maybe a very stupid question, but is this possibe ?
well i have a sort of a slider on a html page.
this is what it shows up like now:
<p>Illustrator</p>
<div class="w3-light-grey w3-round-xlarge w3-small">
<div class="w3-container w3-center w3-round-xlarge w3-teal" style="width:75%">75%</div>
</div>
This shows up a bar,
well what want to achieve is if its possible to change that value 75% to my script data :
style="width:75%">
like i have a script, it retrieves values from my server:
var input = "10;11;15";
var arr = input.split(";");
document.getElementById("humid").innerHTML = (arr[0 ]);
this shows up my data just normal
<span id="humid">0</span>
what i want to do is something like this, but i don't know how:
I want this value from style="width:75%"> to be the humid value.
so if my humid value is 50% the width goes 50%
i did try this but no result
style="width:humid+%">
or style="width:(humid)+%">
i'm still learning,
regards
<!DOCTYPE html>
<html>
<title>TESt</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<link rel='stylesheet' href='https://fonts.googleapis.com/css?family=Roboto'>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<style>
html,body,h1,h2,h3,h4,h5,h6 {font-family: "Roboto", sans-serif}
</style>
<body class="w3-light-grey">
<p>Original</p>
<div class="w3-light-grey w3-round-xlarge w3-small">
<div class="w3-container w3-center w3-round-xlarge w3-teal" style="width:75%">75%</div>
</div>
<p>Media</p>
<div class="w3-light-grey w3-round-xlarge w3-small">
<div class="w3-container w3-center w3-round-xlarge w3-teal" style="#humid">0</div>
</body>
<script>
var input = "10;11;15";
var arr = input.split(";");
//alert(arr[1 ]);
document.getElementById("humid").innerHTML = (arr[0]);
document.getElementById("temp").innerHTML = (arr[1 ]);
document.getElementById("uv").innerHTML = (arr[2 ]);
</script>
</html>
Retrieve my input:
function readForestall() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("ForestAll").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "readFORESTALL", false);
xhttp.send();
}
setInterval(function() {
readForestall();
}, 5000);

If I understand your question right, you want to change the width of an element based on a variable you receive. In that case you can change the inline style with JavaScript. You just need to grab the element and set the style by assigning values to the properties of the element's style property.
If you want to change the width, you can use the following:
element.style.width = '50%'
It sets the width to 50%. You can also include a variable like this:
const width = 50
element.style.width = `${width}%`
I've created a snippet below where you can set the value by using an input and it updates both the width and the content of that div. You can click on the "Run code snippet button" and see the result in live.
const barLeft = document.querySelector('#bar-left');
const barRight = document.querySelector('#bar-right');
const input = document.querySelector('[name="width"]');
const error = document.querySelector('.error');
input.addEventListener('input', (e) => {
const widthLeft = Number(e.target.value);
const widthRight = 100 - widthLeft;
if (widthLeft < 0 || widthLeft > 100) {
error.textContent =
"We don't do that here. Width must be between 0 and 100.";
return;
}
error.textContent = '';
barLeft.textContent = `${widthLeft}%`;
barLeft.style.width = `${widthLeft}%`;
barRight.textContent = `${widthRight}%`;
barRight.style.width = `${widthRight}%`;
});
body {
font-family: sans-serif;
margin: 0;
text-align: center;
}
.outer {
display: flex;
margin-bottom: 2rem;
}
.inner {
background-color: lightcoral;
box-shadow: 0 -4px 0 rgba(0, 0, 0, 0.2) inset;
height: 100%;
padding: 1rem;
}
.inner--blue {
background-color: lightblue;
}
.controls {
margin-bottom: 1rem;
}
input {
font-family: inherit;
font-size: inherit;
padding: 0.5rem 1rem;
}
.error {
color: #d32f2f;
}
<div class="outer">
<div class="inner" id="bar-left" style="width: 75%">75%</div>
<div class="inner inner--blue" id="bar-right" style="width: 25%">25%</div>
</div>
<div class="controls">
<label for="width">First bar's width:</label>
<input type="number" name="width" id="width" min="5" max="95" value="75" />
</div>
<div class="error"></div>
Update: Updated your example below. Make sure you close your tags, and check out how to add ids to elements.
<body class="w3-light-grey">
<p>Media</p>
<div class="w3-light-grey w3-round-xlarge w3-small">
<div class="w3-container w3-center w3-round-xlarge w3-teal" id="humid">
0
</div>
</div>
div>
<script>
var input = '10;11;15';
var arr = input.split(';');
// update the content of the div with ID "humid"
document.getElementById('humid').textContent = arr[0];
// change the width of the div with ID "humid"
document.getElementById('humid').style.width = `${arr[0]}%`;
</script>
</body>

Tranq,
i am not exactly sure why you would want to call the width from an array and use DOM when you can simply use CSS to accomplish this with #media instead. correct me if i am wrong, but you're just trying to adjust the width based on values of the current width of the device? this seems like a whole lot of work for what is a simple solution.
use something like to set the appropriate widths depending on the screen widths:
#media only screen and (max-width: 600px) {
#humid { width: 75%; }
}
also, it is likely you're not passing your array properly and it is returning NULL(0). you can check this via a debugger and ensure it is being passed properly. FireFox has a Great built in debugger for this. use CMD/CTRL+SHIFT+K to open the debugger in FireFox.
P.S. you are not passing the array properly. you're setting it to change the 'innerHTML' which changes everything inside of the
document.getElementById("humid").innerHTML = (arr[0 ]);
if you change "(arr[0 ]);" to something like "string" it will replace the value 0 to "string".

Related

How to add numbers value in ONE input text?

I have coded and used for loop but only works if I use multiple Input text.
I want to achieve:
Every time I input number on one Input text and hit the buttons "add" or "deduct, I want the total below will keep updating while adding or deducting.
let total = 0;
for(var i=0; i<priceTrim.length; i++){
if(parseInt(priceTrim[i].value))
total += parseInt(priceTrim[i].value);
}
document.getElementById('total').value = total;
Please see the screenshot
What I understand, that you want to enter the name and price of item and then by add or deduct button, perform add or subtract operation. Plus you also want to manage the Total Value.
I create a program through your screenshot. Code is written below.
// Selecting the Elements from Html
Item_Name = document.getElementById("Item_Name");
var Price = document.getElementById("Price");
var Add = document.getElementById("Add");
var Deduct = document.getElementById("Deduct");
var Name_Here = document.getElementById("name_here");
var Price_Here = document.getElementById("price_here");
var Total = document.getElementById("Total");
var Total_Value = 0;
// Get and Set the values
Add.onclick = function(){
Name_Here.innerText = Item_Name.value;
Price_Here.innerText = Price.value;
Total_Value += parseInt(Price.value);
Total.innerText = Total_Value;
}
Deduct.onclick = function(){
Name_Here.innerText = Item_Name.value;
Price_Here.innerText = Price.value;
Total_Value -= parseInt(Price.value);
Total.innerText = Total_Value;
}
.flex_container{
display: flex;
justify-content: center;
}
.container{
width: 300px;
min-height: 220px;
border: 1px solid black;
padding: 10px;
}
button{
margin: 12px 0px;
}
.Span_Header{
display: flex;
justify-content: space-between;
}
input{
width: 100%;
margin: 8px 0px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="flex_container">
<div class="container">
<span>Item name</span><br>
<input type="text" name="item_name" id="Item_Name" placeholder="Item name"><br>
<span>Price</span><br>
<input type="number" name="price" id="Price" placeholder="Price"><br>
<button id="Add">Add</button>
<button id="Deduct">Deduct</button>
<div class="Span_Header">
<span>Item name</span>
<span>Price</span>
</div>
<hr>
<div class="Span_Header">
<span id="name_here">Name Here</span>
<span id="price_here">Price Here</span>
</div>
<hr>
<div class="Total_div">
<span>Total: </span>
<span id="Total"></span>
</div>
</div>
</div>
</body>
</html>
Please include all of your code if you would like an answer. What is priceTrim?
Are you trying to loop through a number of textbox values? If so you will have to use the querySelectorAll domElement method to loop as it returns an array type of all the text boxes , then you can specify what it is you want to do with that information in the function.
Also your if statement syntax is all wrong. You have no code block for code to perform if your testing condition returns true.
Please put in all the code and try ans explain what exactly it is you are trying to achieve? I feel like you’ve given half a story!

Change image position on button click

I don't know very much about coding, but I would like to be able to make it so when I click one of the "test" buttons, the image moves. I would like it to be a variable, so that it is constantly checking the variable (I have no idea how to use variables), and at any given moment, when variable = number, it is in a specific position I have designated. And when I click test 1, that variable goes up by one, and when I click test 2, it goes down by one. And at any given variable from 0-10, there is a specific place the image should be for each number. And once the variable reaches 11, the variable will instantly reset to 0 as if in a loop. It can include HTML, CSS and Javascript, sorry if this is confusing I really am a noob at coding :(
This is all the code I have so far, it really isn't helpful but I thought I should add it anyway.
<img id="img01" src="https://cdn.shopify.com/s/files/1/0080/8372/products/tattly_triangle_yoko_sakao_ohama_00_1200x1200.png?v=1575322215" height="300">
<button id="test1" type="button">test 1</button>
<button id="test2" type="button">test 2</button>
Thank you for any help :)
Take a look at the code below. I hope this example will help you to undestand a block move principe.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>moved image</title>
</head>
<body>
<div class="wrapper">
<div>
<img class="image" src="" width="50" style="left: 200px;">
</div>
</div>
<button class="button" type="button" id="left-button" onclick="moveLeft()">Left</button>
<button class="button" type="button" id="right-button" onclick="moveRight()">Right</button>
<style>
.wrapper {
position: relative;
width: 500px;
min-height: 200px;
background-color: yellow;
}
.image {
position: absolute;
top: 40px;
width: 100px;
height: 70px;
background-color: blue;
}
</style>
<script>
'use strict'
const getNumber = function(str) {
return parseInt(str, 10);
}
const transformToString = function(num) {
return num + 'px';
}
const SHIFT = 10;
const MARGIN = 10;
const element = document.querySelector('.image');
const LEFT_MARGIN = getNumber(element.style.left) - SHIFT * MARGIN;
const RIGHT_MARGIN = getNumber(element.style.left) + SHIFT * MARGIN;
const moveLeft = function() {
if (getNumber(element.style.left) > LEFT_MARGIN) {
element.style.left = transformToString(getNumber(element.style.left) - SHIFT);
}
}
const moveRight = function() {
if (getNumber(element.style.left) < RIGHT_MARGIN) {
element.style.left = transformToString(getNumber(element.style.left) + SHIFT);
}
}
</script>
</body>
</html>

How to make UI more responsive for other screen sizes?

I have an html page in which I have a textbox (Type your text) and TextArea list. I need to type into the textbox and then click Add button so that whatever is there in textbox goes to my TextArea list. I need to type in this below format in the textbox.
Name=Value
This textbox will be used by the user to quickly add Name Value pairs to the list which is just below that textbox. let's say if we type Hello=World in the above textbox and click add, then in the below list, it should show as
Hello=World
And if we again type ABC=PQR in the same textbox, then in the below list, it should show like this so that means it should keep adding new Name Value pair just below its original entry.
Hello=World
ABC=PQR
But if the syntax is incorrect like if it is not in Name=Value pair then it should not add anything to the list and instead show a pop up that wrong input format. Names and Values can contain only alpha-numeric characters. I also have three more buttons Sort by name, Sort by value and Delete button. Once I click either of these buttons, then it should sort entries in TextArea list using either name or value and delete entries as well. Now I have all above things working fine without any issues.
Here is my jsfiddle. I need to use plain HTML, CSS and Javascript, I don't want to use any library yet as I want to keep it simple as I am still learning. Now I am trying to see whether we can make UI more responsive like the UI should adjust based on what screen size is viewing it. For example, if viewed on a mobile phone (i.e. Android or iPhone), the page should automatically adjust to present the layout in a better way. This also applies to re-sizing the browser on desktop, and viewing the page on a tablet.
What are the changes I need to make in my CSS or HTML to make it more responsive? Any improvements I can make here? Since my UI is very simple so there should be some easy way or some improvements I can make here.
Below is my code:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Test</title>
<style type="text/css">
.main{
background:white;
padding: 35px;
border-radius: 5px;
}
#my-text-box {
font-size: 18px;
height: 1.5em;
width: 585px;
}
#list{
width:585px;
height:300px;
font-size: 18px;
}
.form-section{
overflow:hidden;
width:700px;
}
.fleft{float:left}
.fright{float:left; padding-left:15px;}
.fright button{display:block; margin-bottom:10px;}
html, body {
height: 100%;
font-family: "Calibri";
font-size: 20px;
}
html {
display: table;
margin: auto;
}
body {
display: table-cell;
vertical-align: middle;
background-color: #5C87B2;
}
</style>
<script language="javascript" type="text/javascript">
document.getElementById('add').onclick = addtext;
function addtext() {
var nameValue = document.getElementById('my-text-box').value;
if (/^([a-zA-Z0-9]+=[a-zA-Z0-9]+)$/.test(nameValue)){
var x = document.getElementById("list");
var option = document.createElement("option");
option.text = nameValue;
x.add(option);
}
else
alert('Incorrect Name Value pair format.');
}
document.getElementById('btnDelete').onclick = deleteText;
function deleteText(){
var myList = document.getElementById('list');
var i;
for (i = myList.length - 1; i>=0; i--) {
if (myList.options[i].selected) {
myList.remove(i);
}
}
}
document.getElementById('sortByValue').onclick = sortByValue;
function sortByValue(){
var myList = document.getElementById('list');
var values = new Array();
for (var i=0;i<myList.options.length;i++) {
values[i] = myList.options[i].text;
}
values.sort(function(a, b){
if(a != "" && b != ""){
return a.split('=')[1].localeCompare(b.split('=')[1])
} else {
return 0
}
});
clearList(myList);
fillList(myList, values);
}
document.getElementById('sortByName').onclick = sortByName;
function sortByName(){
var myList = document.getElementById('list');
var values = new Array();
for (var i=0;i<myList.options.length;i++) {
values[i] = myList.options[i].text;
}
values.sort(function (a, b){
if(a != "" && b != ""){
return a.split('=')[0].localeCompare(b.split('=')[0])
} else {
return 0
}
});
clearList(myList);
fillList(myList, values);
}
function clearList(list) {
while (list.options.length > 0) {
list.options[0] = null;
}
}
function fillList(myList, values){
for (var i=0;i<values.length;i++) {
var option = document.createElement("option");
option.text = values[i];
myList.options[i] = option;
}
}
</script>
</head>
<body>
<div class = 'main'>
<h3>Test</h3>
<label for="pair">Type your text</label></br>
<div class="form-section">
<div class="fleft">
<input type='text' id='my-text-box' value="Name=Value" />
</div>
<div class="fright">
<button type="button" id='add' onclick='addtext()'>Add</button>
</div>
</div>
<label for="pairs">Name/Value Pair List</label></br>
<div class="form-section">
<div class="fleft">
<select id="list" multiple></select>
</div>
<div class="fright">
<button type="button" id='sortByName' onclick='sortByName()'>Sort by name</button>
<button type="button" id='sortByValue' onclick='sortByValue()'>Sort by value</button>
<button type="button" id='btnDelete' onclick='deleteText()'>Delete</button>
<button type="button">Show XML</button>
</div>
</div>
</div>
</body>
</html>
W3 have a number of resources on responsive web design:
http://www.w3schools.com/html/html_responsive.asp
http://www.w3schools.com/css/css_responsive_intro.asp
Without using PHP to detect the browser/user agent, your responsive design will typically involve ensuring the site is more fluid and flowing, allowing for changing browser widths (as in the first example above) and/or by delivering differing stylesheets depending on the viewport size and media type in CSS (second example).

Random card/Image using buttonjavascript

I want to create a card game using java script. Being a beginner at java script, I am finding great difficulty finding a suitable tutorial for what I am trying to do. When the 'start game' button is selected, I want the computer to produce a random card. I have tried many ways of doing this and have came to no avail. Here is my code.
<html>
<head>
<title> Christmas Assignment </title>
<link rel="stylesheet" type="text/css" href="xmasass_1.css">
<script type = "text/javascript">
function randomImg(){
var myimages= [];
myimages[1] = "cards/1.gif";
myimages[2] = "cards/2.gif";
myimages[3] = "cards/3.gif";
myimages[4] = "cards/4.gif";
myimages[5] = "cards/5.gif";
myimages[6] = "cards/6.gif";
myimages[7] = "cards/7.gif";
myimages[8] = "cards/8.gif";
myimages[9] = "cards/9.gif";
myimages[10] = "cards/10.gif";
myimages[11] = "cards/11.gif";
myimages[12] = "cards/12.gif";
myimages[13] = "cards/13.gif";
function oddTrivia(){
var randomImg = Math.floor(Math.random()*(oddtrivia.length));
document.getElementById('comp').InnerHTML=myimages[randomImg];
}
ar total = 0;
function randomImg(){
var x = Math.floor(Math.random()*13)+1;
document.getElementById('img1').src = 'die'+x+'.gif';
document.getElementById('img2').src = 'die'+y+'.gif';
document.getElementById('score').innerHTML = total;
}
var card1Image;
var card2Image;
var card3Image;
var card4Image;
var card5Image;
var card6Image;
function start(){
var button = document.getElementById("startButton");
button.addEventListener("click", pickCards, false);
card1Image = document.getElementById("1");
card2Image = document.getElementById("2");
card3Image = document.getElementById("3");
card4Image = document.getElementById("4");
card5Image = document.getElementById("5");
card6Image = document.getElementById("6");
}
function pickCards(){
setImage(card1Image);
setImage(card2Image);
setImage(card3Image);
setImage(card4Image);
setImage(card5Image);
setImage(card6Image);
}
function setImage(cardImg){
var cardValue = Math.floor(1 + Math.random() * 13);
cardImg.setAttribute("src", "C:Xmas Assignment/cards/" + cardValue + ".gif");
}
window.addEventListener("load", start, false);
</script>
</head>
<body>
<div id = "settings">
<img src = "settings_img.png" width = "60" height = "60">
</div>
<div id = "bodydiv">
<h1> Card Game</h1>
<div id = "computer">
<img src = " cards/back.gif">
</div>
<div id = "comp" > Computer </div>
<div id ="arrow">
<img src ="arrow2.png" width = "100" height="100">
</div>
<div id = "player">
<img src = " cards/back.gif">
</div>
<div id = "play"> Player </div>
<div id = "kittens">
<button id = "startButton" onclick ="randomImg" > Start Game </button>
<div id = "buttons_1">
<button id ="higher"> Higher
</button>
<button id = "equal"> Equal
</button>
<button id = "lower"> Lower
</button>
</div>
<button id = "draw"> Draw your Card
</button>
<div id = "resetscore"> Reset Score
</div>
</div>
<div id = "score">
</div>
</div>
</body>
</html>
body {
background:#66ccff;
}
h1 {
text-align:center;
}
#settings {
float:right;
margin-top:10px;
}
#bodydiv {
width: 800px;
height:600px;
margin-left:200px;
margin-top:40px;
margin-bottom:60px;
background:#ffccff;
border-radius: 10px;
}
#computer {
border-radius: 10px;
position: absolute;
left:35%;
top:27%;
}
#player {
border-radius: 10px;
position: absolute;
left:55%;
top:27%;
}
#start_game {
width :120px;
height: 55px;
margin-left: 350px;
margin-top:50px;
background:white;
border:1px solid black;
}
#buttons_1 {
text-align: center;
margin-top:20px;
}
#higher {
width:140px;
height:50px;
font-size: 15px;
border-radius:10px;
font-weight:bold;
}
#equal {
width:140px;
height:50px;
font-size: 15px;
border-radius:10px;
font-weight:bold;
}
#lower {
width:140px;
height:50px;
font-size: 15px;
border-radius:10px;
font-weight:bold;
}
#draw {
width:160px;
height:30px;
margin-left:325px;
margin-top: 30px;
border:1px solid black;
background:#FFFFCC;
}
#resetscore {
text-align: center;
margin-top: 40px;
}
#arrow {
margin-left:370px;
margin-top:-130px;
}
#comp {
margin-top:240px;
margin-left:265px;
}
#play{
margin-top:10px;
margin-left:540px;
}
You code is kind of hard to read.
You forgot to close the "{" of your main function.
You are declaring "randomImg" again in the body of the "randomImg" function(use a different name).
You wrote
ar total = 0;
I think you meant to write:
var total = 0;
oddtrivia in the function "OddTrivia" is not defined.
y in the inner randomImg function is not defined.
Having poked a little bit at the code, here is a few things:
Problem no 1: randomImg()
It's hard to know your intentions, but you should likely begin with removing the start of your first function randomImg(){.
Because 1) It does not have an end and 2) If it actually spans everything then this line window.addEventListener("load", start, false); will not load on startup (since it does not get executed until randomImg() gets executed, and by then the page has already loaded.)
Problem no 2: Cannot set property 'src' of null"
Now when the first problem is out of the way, you should see "Uncaught TypeError: Cannot set property 'src' of null" if you look in your console. Yes, USE YOUR CONSOLE. Click on the error to show what causes it. Here it is:
cardImg.setAttribute("src", "C:Xmas Assignment/cards/" + cardValue + ".gif");
This means that cardImg is null. We backtrack the first call of setImage() and find that the variable card1Image is passed in. So that must mean that card1Image also is null. You can check it yourself by adding a console.log('card1Image', card1Image); in your code. Or you add a breakpoint at that point. (Use the sources-tab in chrome dev tools, click at the line-numbering to add a break point. Refresh the page and it will stop at the break point. Now you can mouse-over variables to see their values.)
Let's look at where 'card1Image' is set.
card1Image = document.getElementById("1");
So why is this returning null? Do we even have a id="1" element in the html? That could be the reason. (It is.)
There are more problems, but I'll stop there, but when you have fixed this part AND have no errors please ask again. Always check your errors and if you ask a question here you should provide errors. And when you can also be more specific with your questions.
What might someone else have done differently?
When it comes to playing cards, why not an array of objects?
var cards = [
{ src : 'cards/1.gif', value: 1 },
{ src : 'cards/2.gif', value: 2 },
{ src : 'cards/3.gif', value: 3 },
{ src : 'cards/4.gif', value: 4 }
]; // (You can of course use code to generate it.)
// Then a function to put cards in the player's hand.
var playerHand = _.sample(cards, 2);
console.log(playerHand);
Here I assume lodash, a lightweight library for when you don't want to re-invent the wheel.

jQuery/Javascript : How to prepend elements without going back to the top of last prepended element?

Whenever I click prepend, after all elements are prepended, the view of the chat area switches to the top of the chat area or the last prepended element. This is different from append, whereby after all elements are appended, the view of the chat area does not switch to the end of the chat area or last appended element but still stays at its previous position.
How do I make the prepend function act in the same way as append in the sense that the view of the chat area does not change similar to FB's load previous message function?
Here is a sample code that illustrates what I mean.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="http://maxcdn.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
</head>
<style type="text/css">
.chatbox{
border:1px solid #2a6496;
height: 600px;
margin-top:50px;
}
.chatbox div{
height: 100%;
}
.rightP{
border-left: 1px solid #2a6496;
}
.rightP .contents{
border-bottom: 1px solid #2a6496;
height: 70%;
}
.rightP .send{
padding : 5% 5% 5% 5%;
height: 30%;
}
#response{
height: 200px;
overflow-y: scroll;
overflow-wrap: break-word;
}
</style>
<script>
function appendMessage()
{
var data = 'hello';
var message = document.createElement('p');
message.innerHTML = data;
console.log(message.innerHTML);
$('#response').append(message);
$('#response').append($('.load'));
}
function prependMessage()
{
for(var $i = 0;$i<10;$i++)
{
var data = 'hello'+$i;
var message = document.createElement('p');
message.innerHTML = data;
console.log(message.innerHTML);
$('#response').prepend(message);
$('#response').prepend($('.load2'));
}
}
</script>
<body>
<div class="container">
<div class="chatbox">
<div class="col-sm-8 rightP">
<div class="row contents">
<div class="row msg">
<div id="response" class="msg form-group">
<a onclick="return appendMessage()" class="load btn btn-default">Append</a>
<a onclick="return prependMessage()" class="load2 btn btn-default">Prepend</a>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
In HTML there should be return in your onlick:
<a onclick="return loadMessage();" class="load btn btn-default">Load More Msg</a>
In JS you need to add return false to your function loadMessage.
var loadMessage = function(){
var firstMessage = $messagesWrapper.find('> p:nth-child(2)');
$.ajax({
....
if(messages.length<10){
$('.load').hide();//hide the load button if remaining messages to load is <10
}
success: function(messages){
$.each(messages, function() {
prependMessage(this);
});
},
....
});
return false;
};
Try this:
<div id="response" class="msg form-group">
<a onclick="loadMessage(); return false;" class="load btn btn-default">Load More Msg</a>
</div>
If this doesn't work, try another way:
var loadMessage = function(){
e.preventDefault(); // preventing any scroll action
var firstMessage = $messagesWrapper.find('> p:nth-child(2)');
(...)
And
var prependMessage = function(data){
e.preventDefault(); // preventing any scroll action
var message = document.createElement('p');
(...)
If this doesn't work please provide the whole code so we can reproduce.

Categories

Resources