New message background highlighting - javascript

I have created a comment system using ajax and php with the usage of append system now I am looking to make it look more attractive so I want when ever a new comment is posted it should be highlighted background like background color fadein and then fadeout smoothly like whenever new answer is posted it is highlighted with an orange background color can anyone help me out how it would be done and what jquery function is used
my jquery
$(document).ready(function() {
$('#sub_comment').on('click', function() {
var comment = $('#comment').val();
var store_id = $('#store_id').val();
$(document).ajaxStart(function() {
$('#wait').css('display', 'block');
});
$(document).ajaxComplete(function() {
$('#wait').css('display', 'none');
});
$.ajax({
type : "POST",
data : {comment: comment, store_id: store_id, command: 'Comment'},
dataType : 'text',
url : "includes/get_data.php",
success : function(data) {
$('#comment').val('');
$('#comments').append($(data).hide().fadeIn(2000));
}
});
});
});

you can use the transition: background-color 1s linear; css property.
Set initial background to the comment div and add the above property. Then change the background (to orange) of the div, it will create a fadein effect and after some setTimeout remove this background, then it will create a fadeout effect.
Check this example for reference.
Another way is to use the animation property of CSS. An example is given here

Try this:
Javascript
$(document).ready(function() {
$('#sub_comment').on('click', function() {
var apend_data = '<div class="data orange"><p>Hello World</p></div>';
$('#comments').append($(apend_data).hide().fadeIn(2000));
setTimeout(function() {
$("#comments .data").removeClass('orange');
}, 1000);
});
});
Css
#comments {
width: 100%;
}
.data {
padding: 15px;
border: 1px solid #000;
margin: 10px auto;
}
.orange {
background-color: orange;
}
HTML
<div id="comments">
<div class="data">
<p>
Hello World
</p>
</div>
</div>
<button id="sub_comment">
Click Me
</button>
fiddle

$(() => {
var index = 1;
$('#btnSubmit').on('click', () => {
$("#conteiner").append('<p id="_' + index + '" style="display:none;width:50%" class="backColor"> ' + $('#txtComment').val() + ' </p>');
var id = "#_" + index + "";
$(id).fadeIn();
index++;
setInterval(function () {
$(id).removeClass('backColor');
}, 1000);
});
});
.backColor {
background-color:red;
}
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<div class='row' id='conteiner' style="padding-left:50px">
</div>
<br />
<div class='row' style='width:50%;padding-left:50px'>
<form>
<div class="form-group">
<input type="text" class="form-control" id="txtComment" placeholder="comment">
</div>
<button type="button" class="btn btn-default" id='btnSubmit'>Submit</button>
</form>
</div>
</body>
</html>

Your code:
$('#comments').append($(data).hide().fadeIn(2000));
cannot work because data is text. You have to make something like
$('#comments').append(data).hide().fadeIn(2000);
but this will always hide all comments and show them again. A workaround is to put the new comment to a new container and only handle this one:
var comments = $('#comments').append('<div>' + data + '</div>');
$('div',comments).css('background-color','');
var newcom = $('div:last-child',comments);
newcom.hide().css('background-color','#ffff00').fadeIn(2000);
With the newcom object you can do any css transition or other things.

Related

How do I give my `<div>` elements a animation entry when my website loads

I want my <div> contents to make a smooth entry when my website loads. They have to start appearing one after the other when the website loads. And also, the background image loads late as it is filtered by the weatherType.
This is a localWeather webpage which gives you the weather information based on where you open the page.
Note:- Please post the code on other third party Web Development sites like codepen.io to access the API.
Here is my Code:
$(document).ready(function() {
$(".text-center").fadeIn();
var lon, lat, weatherType, ftemp, ktemp, ctemp, wspeed;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
lon = position.coords.longitude;
lat = position.coords.latitude;
var api = 'https://api.openweathermap.org/data/2.5/forecast?lat=' + lat + '&lon=' + lon + '&appid=bb4b778076b0c8c79c7eb8fcd1fd4330';
$.getJSON(api, function(data) {
// $("#data").html(api);
var city = data.city.name;
weatherType = data.list[0].weather[0].description;
//weatherType="clear sky";
ktemp = data.list[0].main.temp;
console.log(ktemp);
ftemp = (9 / 5 * (ktemp - 273) + 32).toFixed(1);
ctemp = (5 / 9 * (ftemp - 32)).toFixed(1);
wspeed = data.list[0].wind.speed;
wspeed = (wspeed * 5 / 18).toFixed(1);
/* $("#city").addClass("animated fadein",function(){
$("#city").html(city);
}); */
$("#city").addClass("animated fadein");
$("#city").html(city);
$("#weatherType").html(weatherType);
$("#temp").html(ctemp + " ℃");
//$("[name='my-checkbox']").bootstrapSwitch();
$("#degree-toggle").attr("value", $("<div/>").html("℉").text());
var celsius = true;
$("#degree-toggle").on("click", function() {
if (celsius === true) {
$("#temp").html(ftemp + " ℉");
$("#temp").fadeIn();
$("#degree-toggle").attr("value", $("<div/>").html("℃").text());
celsius = false;
} else {
$("#temp").html(ctemp + " ℃");
$("#temp").fadeIn();
$("#degree-toggle").attr("value", $("<div/>").html("℉").text());
celsius = true;
}
});
$("#wspeed").html(wspeed + " kmph");
weatherType=weatherType.toLowerCase();
if (weatherType === "clear sky")
$("body").css("background-image", "url('https://static.pexels.com/photos/281260/pexels-photo-281260.jpeg')");
else if (weatherType === "few clouds")
$("body").css("background-image", "url('https://clearalliance.org/wp-content/uploads/2015/01/CLEAR-see-clear-flowers-e1422658973500.jpg')");
else if (weatherType === "cloudy")
$("body").css("background-image", "url('http://www.gazetteseries.co.uk/resources/images/5360796/')");
else if (weatherType === "sunny")
$("body").css("background-image","url('https://i2-prod.examiner.co.uk/incoming/article10372520.ece/ALTERNATES/s1227b/JS75768352.jpg')");
else if (weatherType==="showers")
$("body").css("background-image","url('http://ak8.picdn.net/shutterstock/videos/1479838/thumb/1.jpg')");
else if(weatherType==="overcast clouds")
$("body").css("background-image","url('https://patchegal.files.wordpress.com/2012/07/img_2406.jpg')");
else if(weatherType==="light rain")
$("body").css("background-image","url('https://i.ytimg.com/vi/LbAigABOm_E/maxresdefault.jpg')");
else
$("body").css("background-image","url('https://www.almanac.com/sites/default/files/image_nodes/thanksgiving-weather.jpg')");
});
});
}
});
.text-center{
display: none;
}
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Open+Sans:300,400,600,700&lang=en" /><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="text-center" id="content">
<div> <h1><b>Weather Today</b></h1></div><br/>
<h2>Location : <span id="city"></span></h2> <br/>
<h2>Weather : <span id="weatherType"></span></h2><br/>
<h2>Temperature : <span id="temp">
</span>
<input type="button" id="degree-toggle" checked="checked">
</h2><br/>
<h2>Wind Speed : <span id="wspeed"></span></h2><br/>
</div>
</body>
</html>
First I would use animations to achieve smooth entry, not only switch elements to visible.
Second I wouldn't write elements manually, what if you have 20 of them? What about 1000?
Start with a frame like this then adjust to your case:
HTML
<div id="elementsInThis">
<div class="K">ELEMENT 1</div>
<div class="K">ELEMENT 2</div>
<div class="K">ELEMENT 3</div>
<div class="K">ELEMENT 4</div>
<div class="K">ELEMENT 5</div>
<div class="K">ELEMENT 6</div>
<div class="K">ELEMENT 7</div>
<div class="K">ELEMENT 8</div>
<div class="K">ELEMENT 9</div>
</div>
JS
var delay = 0;
function animate(element, delay){
window.setTimeout(function(){
element.style.display = 'block';
}, delay*1000)
}
var elements = document.getElementById("elementsInThis").childNodes;
var onlydivs = Object.keys(elements).forEach(function(index, element){
if (elements[element].nodeType !== Node.TEXT_NODE)
animate(elements[element], delay++);
});
CSS
.K{
display: none;
background: red;
border: solid 2px black;
animation-name: appear;
animation-duration: 4s;
animation-fill-mode: forwards;
}
#keyframes appear{from{left:-300px;opacity:0} to{left:0;opacity:1}}
Here you can see it in action:
js fiddle
Modify animation and delay to your liking, also bind to your own parent and make a better selecor of children if you have more complex ones. This is just a demo but principle is the same you do the following:
You wanna leverage CSS to make proper (or find someone else's) animation and set default display of element to none (might wanna use visibility instead if your HTML breaks apart)
make a delay function with fixed delay step (i used step 1 * 1000 ms)
leverage childNodes forEach() and Object.keys() to avoid manually binding your CSS class with animation to elements
you can have rest of the style in different CSS class if you like
While I cannot give you an exact answer as I'm about to go home. What you can do is dedicate a separate function for your animation feature. Then in your script, you will each assign a setTimeout event for each element, giving each of them a specific delay before showing. Then you can add a transition or animation property on your element.
CSS
.elements {
//css here
}
JS
//delay = time in ms before show, element = element to show.
function letAnimate(delay, element){
window.setTimeout(function(){
element.style.display = 'block';
}, delay);
}
function startAnimate(){
letAnimate(1000, el1); //your first element which will show 1s after function call
letAnimate(2000, el2); //2nd element, will show after 2s
letAnimate(3000, el3); //3rd, 3s, so forth so on
}
window.onload = function(){ startAnimate(); };
//make this jquery on() or addEventListener.
//You don't want this function to override window.onload event.

Click on edit jquery

I am a newbie so my question is pretty simple and straight forward.
I have a simple html text. When I click on that html text, the text should change to input field with the value retained and when the user clicks outside the text box, the input text field now should change to html text.
<div class="myText"> Hellow World </div>
Can somebody do this in jquery/Meteor. I am actually building a meteor project
You can do that with the contenteditable attribute
<div class="myText" contenteditable="true"> Hellow World </div>
<!-- Your div is now editable -->
Updated DEMO jsFiddle
$(document).ready(function() {
$('.editable').on('click', function() {
var that = $(this);
if (that.find('input').length > 0) {
return;
}
var currentText = that.text();
var $input = $('<input>').val(currentText)
.css({
'position': 'absolute',
top: '0px',
left: '0px',
width: that.width(),
height: that.height(),
opacity: 0.9,
padding: '10px'
});
$(this).append($input);
// Handle outside click
$(document).click(function(event) {
if(!$(event.target).closest('.editable').length) {
if ($input.val()) {
that.text($input.val());
}
that.find('input').remove();
}
});
});
});
In my solution you need to add class="editable" to all editable divs.
You also need to set position: relative to these divs. May be you can update my code and edit the css:
.editable {
position: relative;
}
To correctly align the input inside the div, you need to remove the border or set the .css({}) of the input to left: -1px and top: -1px. The border actually pushes the input 1px left and 1px form the top.
Try this:
$(function() {
$('div.myText').on('click', function() {
var div = $(this);
var tb = div.find('input:text');//get textbox, if exist
if (tb.length) {//text box already exist
div.text(tb.val());//remove text box & put its current value as text to the div
} else {
tb = $('<input>').prop({
'type': 'text',
'value': div.text()//set text box value from div current text
});
div.empty().append(tb);//add new text box
tb.focus();//put text box on focus
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="myText">Hello world</div>
<div class="myText">This is second</div>
Try this:
$(document).click(function() {
$('.myText').html("Hello World");
});
$(".myText").click(function(event) {
$('.myText').html("<input type='text' id='test' value='Hello World'/>");
$('#test').focus();
event.stopPropagation();
});
FIDDLE.
To do it very easily and understandable you can also make two elements instead of changing.
Working fiddle: http://jsfiddle.net/45utpzhx/
It does an onClick event and onBlur.
html
<div>
<span class="myText">Hello World</span>
<input class="myInput" />
</div>
jQuery
$(document).ready(function() {
$(".myText").click(function() {
$(this).hide();
var t = $('.myText').html();
$('.myInput').val(t);
$('.myInput').show();
});
$(".myInput").blur(function() {
$(this).hide();
var t = $('.myInput').val();
$('.myText').html(t);
$('.myText').show();
});
});
Replace the clicked element with an input with value equal to the clicked element's text
$(document).on('click', '.myText', function() {
var that = $(this);
var text = that.text();
that.wrap('<div id="wrp" />');
$('#wrp').html('<input type="text" value="' + text + '" />');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="myText"> Hellow World </div>
You can try this solution :
$('.myText').click(function(){
var m = $(this).text();
$(this).html('');
$('<input/>',{
value : m
}).appendTo(this).focus();
});
$(document).on('blur','input',function(){
var m = $(this).val();
$(this).parent().find('input').remove().end().html(m);
});
working DEMO
$('#text').on('click', function() {
$("#text").hide();
if ($("#text").text()=="Add New text"){
$('#in_text').val("");
}else{
$('#in_text').val($("#text").text());
}
$("#in_text").show();
});
// Handle outside click
$(document).click(function(event) {
if(!$(event.target).closest('.editable').length) {
if($("#text").css('display') == 'none'){
$("#in_text").hide();
if ($("#in_text").val()=="" ){
$('#text').text("Add New text");
$('#text').addClass("asd");
}else{
$('#text').removeClass("asd");
$('#text').text($("#in_text").val());
}
$("#text").show();
}
}
});
#in_text{
display:none;
}
.editable{
width:50%;
}
.asd{
border-bottom : 1px dashed #333;
}
#text{
display: inline;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="editable">
<div id="text" >Text in div</div>
<input type="text" placeholder="Add New Text" id="in_text"/></div>

tooltip construction and deletion on nested div's

In a HTML document containing nested div's I want to create a tooltip triggerd when entering one of the div. The tooltip text value is made by concatenation of a data taken from the current element's parents. The example script below is almost doing what I want but :
- the tooltip is always shown at the left,
- some tooltips stay on the screen and are not properly deleted
- the tooltip doesn't follow the mouse pointer, although the track: true property
- it is not fluid.
Can someone help ? Many thanks !
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<style>
.c1 {
margin-left: 10%;
border-left:solid;
border-width:1px;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
</head>
<body>
<div class="c1" data-rank="hello">This is div 1
<div class="c1" data-rank="world">This is div 2
<div class="c1" data-rank="how">This is div 3
<div class="c1" data-rank="are">This is div 4
<div class="c1" data-rank="you ?">This is div 5<br/><br/><br/>
</div>
</div>
</div>
</div>
</div>
<script style="text/javascript">
$("[data-rank]").mouseenter(
function showRank(event){
// delete previous tooltips
var tips = $('.ui-tooltip');
if (tips) {
$tips = null;;
};
// create the text
var lineage = $(this).attr('data-rank');
$(this).parents().each(
function(i,e) {
var rk = $(e).attr('data-rank');
if (rk) {
lineage = rk + "; " + lineage;
}
}
);
// create the tooltip
$(this).tooltip({
track: true,
content: lineage,
items: "[data-rank]"
})
}
)
</script>
</body>
</html>
Ok so in your function showRank() make some changes as below and remove the part
var tips = $('.ui-tooltip');
if (tips) {
$tips = null;;
}; //Remove this part
$("[data-rank]").mouseenter(
function showRank(event){
// delete previous tooltips
$( ".ui-tooltip" ).tooltip( "destroy" );
// create the text
var lineage = $(this).attr('data-rank');
$(this).parents().each(
function(i,e) {
var rk = $(e).attr('data-rank');
if (rk) {
lineage = rk + "; " + lineage;
}
}
);
// create the tooltip
$(this).tooltip({
track: true,
content: lineage,
items: "[data-rank]"
})
});
Let me know if any issues
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<style>
.c1 {
margin-left: 10%;
border-left:solid;
border-width:1px;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
</head>
<body>
<div id="1" class="c1" data-rank="hello">This is div 1
<div id="2" class="c1" data-rank="world">This is div 2
<div id="3" class="c1" data-rank="how">This is div 3
<div id="4" class="c1" data-rank="are">This is div 4
<div id="5" class="c1" data-rank="you ?">This is div 5<br/><br/><br/>
</div>
</div>
</div>
</div>
</div>
<script style="text/javascript">
$("[data-rank]").mouseenter(
function showRank(event){
// delete previous tooltips
var tips = $('.ui-tooltip');
if (tips) {
$('.ui-tooltip').remove();
};
// create the text
var lineage = $(this).attr('data-rank');
$(this).parents().each(
function(i,e) {
var rk = $(e).attr('data-rank');
if (rk) {
lineage = rk + "; " + lineage;
}
}
);
$('.ui-tooltip').remove();
// create the tooltip
var idTag = $(this).attr('id');
$(this).tooltip({
track: true,
content: lineage,
items: "[data-rank]",
position: {
using: function( position, feedback ) {
$( this ).css( 'margin-left', idTag + '0%');
}
},
})
}
)
</script>
</body>
</html>
Thank you for your help which solves part of the problems !
A friend send me (although I strongly suggest him to subscribe to StackOverflow !!) a very elegant solution :
https://jsfiddle.net/n4yax3ga/5/
The main point is to use the tooltip fuctionalities :
$(document).ready(
function() {
$(document).tooltip({
items: '[data-rank]',
content: function(){
var lineage = $(this).data('rank');
$(this).parents().each(
function(i,e) {
var rk = $(e).data('rank');
if (rk) {
lineage = rk + "; " + lineage;
}
}
);
return lineage;
},
track: true
});
}
);
The tooltip CSS should be changed also :
.ui-tooltip {
position: absolute;
top: 100px; left:100px;
}

Show more/less text in a table automatically according to text length

I have a table with two columns, the second one sometimes contains big text so I want to show only the first 100 characters and put a show more link to display the remaining text. You can see here what Table I am working on http://jsfiddle.net/j11mj21x/.
For that I am using a code provided in this link (http://viralpatel.net/blogs/dynamically-shortened-text-show-more-link-jquery/), I put it in a file show_less_more.js :
(function($) {
$.fn.shorten = function (settings) {
var config = {
showChars: 100,
ellipsesText: "...",
moreText: "more",
lessText: "less"
};
if (settings) {
$.extend(config, settings);
}
$(document).off("click", '.morelink');
$(document).on({click: function () {
var $this = $(this);
if ($this.hasClass('less')) {
$this.removeClass('less');
$this.html(config.moreText);
} else {
$this.addClass('less');
$this.html(config.lessText);
}
$this.parent().prev().toggle();
$this.prev().toggle();
return false;
}
}, '.morelink');
return this.each(function () {
var $this = $(this);
if($this.hasClass("shortened")) return;
$this.addClass("shortened");
var content = $this.html();
if (content.length > config.showChars) {
var c = content.substr(0, config.showChars);
var h = content.substr(config.showChars, content.length - config.showChars);
var html = c + '<span class="moreellipses">' + config.ellipsesText + ' </span><span class="morecontent"><span>' + h + '</span> ' + config.moreText + '</span>';
$this.html(html);
$(".morecontent span").hide();
}
});
};
})(jQuery);
$(document).ready(function(){$(".descriptionText").shorten();});
I am using it like this:
<script src="show_less_more.js"></script>"
The HTML is like this for every row:
<tr>
<th>
course1
</th>
<td> <div class="descriptionText">Description of the course</div></td>
</tr>
I have also added the CSS for the more and less links:
a {
color: #0254EB
}
a:visited {
color: #0254EB
}
a.morelink {
text-decoration:none;
outline: none;
}
.morecontent span {
display: none;
}
When I do this in sfiddle it works pretty good as you can see here http://jsfiddle.net/j11mj21x/2/
However, I get nothing when rendering my table with python.
I think the problem is that I don't succeed to load my JS page into the html page, because when I click on it it give nothing.
Here is what is rendered in my html page:
....
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script><!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css"><!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap-theme.min.css"><!-- Latest compiled and minified JavaScript --><script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js">
</script><script src="showLessMore.js"></script>
....
Can anyone tell me what could be the problem behind this because I have the "show_less_more.js" in the same folder as the file generator which in python?
Thank you in advance !
Here's a simple example of doing this relying more on CSS.
$(function() {
$('a').click(function() {
$('div').removeClass('ellipsis');
});
});
div {
border: solid 1px orange;
width: 200px;
overflow: hidden;
}
.ellipsis {
white-space: nowrap;
text-overflow: ellipsis;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class='ellipsis'>Some really really long text that just is way too long so we must use ellipses to shorten it until the user wants to see it all.</div>
<br>
<a href='#'>Show All</a>

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