jScrollPane doesn't scroll to bottom after content update - javascript

I have a chat window with a jScrollPane. The problem is that when I submit a message it doesn't scroll down to the last word/line I wrote, it's always a line behind.
$('body').delegate('#private-form', 'submit', function() {
var sendMessage = $(this).find('input.private-message').val();
if (!empty(sendMessage)) {
socket.emit('send private message', {
'message': sendMessage,
'username': $(this).find('input.send-to').val()
});
$(this).find('input.private-message').val('');
var data = '' +
'<div class="person">' +
'<img src="img/avatar.png" alt="">' +
'<div class="details">' +
'<div class="chat">' +
'<p>' + sendMessage + '</p>' +
'</div>' +
'<div class="chat-view">' +
'<p>10 min ago</p>' +
'</div>' +
'</div>' +
'</div>';
var settings = {
showArrows: false,
autoReinitialise: true,
};
var pane = $('.chat-single');
pane.jScrollPane(settings);
var contentPane = pane.data('jsp').getContentPane();
contentPane.append(
data
);
pane.data('jsp').scrollToBottom();
}
return false;
});
Markup:
<div class="chatters">
<div class="chat-single">
</div>
</div>
Styles:
.chatters {
padding: 10px 0;
height: 75%;
width: auto;
max-width: 390px;
}
.chat-single{
height:100%
}

After appending the data, call reinitialise on pane.data('jsp') before scrolling to the bottom.
contentPane.append(
data
);
pane.data('jsp').reinitialise();
pane.data('jsp').scrollToBottom();
Also, if you're using autoReinitialise be sure to provide a reasonable autoReinitialiseDelay since by default it does this re-initialisation twice per sencond (every 500ms).

Related

Add Item Dynamically In Option

I Have Select2 And Here is My Code:
var like = "";
var dissLike = "";
#foreach (var d in Model.CustomerProblems)
{
#:like=#d.Like;
#:dissLike=#d.DissLike;
#:$("#CustomerDescId").val("#d.Id");
#:$("#CusLike").val(#d.Like);
#:$("#CusDissLike").val(#d.DissLike);
}
Here Get Item From Model With Js
function formatState(state) {
if (!state.id) {
return state.classList;
}
var $state = $(
'<span contenteditable="false"><img style="width: 30px; display: inline-block;" src="/images/Like.jpg" />' + like + '<img style="width: 30px; display: inline-block;" src="/images/dissLike.jpg" />' + dissLike + state.text + '</span>'
);
return $state;
}
I need Dynamically Add Like In Model Send To Item
Please Help Me!!

How to append a dialog into a main div on your page on button click

I have a log in button that when a user clicks on it a terms and condition dialog pops up and overlaps the contents on a page as follows
TermsSuccess: function (result, context) {
var topTerms = findSetByInArray(result.Data, 'ParentId', 0);
var termsHTML = '<div id="terms"><ul class="termsList">';
for (var i = 0; i < topTerms.length; i++) {
var cls = (topTerms[i].isNew) ? 'newTerm' : 'Term';
termsHTML += '<li id=' + topTerms[i].ID + ' class=' + cls + '>'
termsHTML += topTerms[i].PageIndex + '. ' + topTerms[i].Detail;
termsHTML += getChildrenTerms(result.Data, topTerms[i].ID, topTerms[i].PageIndex + '. ');
termsHTML += '</li>';
}
termsHTML += '</ul></div>';
$(termsHTML).dialog({
modal: true,
resizable: false,
width: 400,
height: 600,
closeOnEscape: false,
open: function (event, ui) {
$(this).parent().children().children('.ui-dialog-titlebar-close').hide();
},
title: "Terms & Conditions",
buttons: [{
text: "Decline",
"class": 'btnDialog',
click: function () {
$(this).dialog("close");
}
},
{
text: "Accept",
"class": 'btnDialog',
click: function () {
betEvents.btnAccept_onClick();
$(this).dialog("close");
}
}]
});
}
I want this dialog to be appended to the following div on the page instead of it poping up over all the contents
<div id="mainarea"></div>
i tried to do something as the following but it doesnt work
function onClick(){
if $("#btnLogin").click(function(){
$('termsHTML').append('#mainarea');
});
}
your guidance will be appreciated.
Change this line:
$('termsHTML').append('#mainarea');
to
$(#mainarea).append(termsHTML);
and try again.
Explanation: $('termsHTML').append('#mainarea'); // here your selector is wrong

Javascript: Different background color for different div's

I have some troubles with javascript app to manage meetings. I have three levels of importance: 'Important', 'Medium', 'No important' and I want change background-color for them. 'Important' - red color, 'Medium' - yellow and 'No important'-green. I try to hold in content variable string from html and then compare this value with if,else if statement, but it still doesn't work. Do you have some advices?
main.js
function fetchMeetings(){
var meetings = JSON.parse(localStorage.getItem('meetings'));
var meetingsResults = document.getElementById('meetingsResults');
// Build output
meetingsResults.innerHTML = '';
for(var i = 0; i < meetings.length; i++){
var date = meetings[i].date;
var person = meetings[i].person;
var purpose = meetings[i].purpose;
var warning = meetings[i].warning;
meetingsResults.innerHTML += '<div class="mettingDiv">'+
'<h3>'+date+'</h3>'+
'<h3>'+person+'</h3>' +
'<h3>'+purpose+'</h3>'+
'<h3 class="importance">'+warning+'</h3>'+
' <a onclick="deleteMeeting(\''+purpose+'\')" class="btn btn-danger" href="#">Delete</a> ' +
'</div>';
}
var content= document.getElementsByClassName("importance").innerHTML;
if(content == 'Important'){
$('.mettingDiv').css('background-color', '#c00100');
}
else if(content == 'Medium'){
$('.mettingDiv').css('background-color', '#fbff30');
}
else if(content == 'No important'){
$('.mettingDiv').css('background-color', '#85ff63');
}
}
github
live app
Ok, I tried to add additional class name to div element, but class name is still the same, code:
meetingsResults.innerHTML += '<div id="div1" class="mettingDiv">'+
'<h3>'+date+'</h3>'+
'<h3>'+person+'</h3>' +
'<h3>'+purpose+'</h3>'+
'<h3 class="importance">'+warning+'</h3>'+
' <a onclick="deleteMeeting(\''+purpose+'\')" class="btn btn-danger" href="#">Delete</a> ' +
'</div>';
}
var content= document.getElementsByClassName("importance").innerHTML;
var d = document.getElementById("div1");
if(content == 'Important'){
d.className += " important";
}
Try this
meetingsResults.innerHTML += '<div class="mettingDiv ' + warning + '">'+ ...
this will result in <div class="mettingDiv Important"..., <div class="mettingDiv No important" ... and then add CSS
.Important { background-color: #c00100; }
.Medium { background-color: #fbff30; }
.No.important { background-color: #85ff63; }

.replacewith not working when called a second time

I have the following markup:
<fieldset>
<legend>Headline Events...</legend>
<div style="width:100%; margin-top:10px;">
<div style="width:100%; float:none;" class="clear-fix">
<div style="width:400px; float:left; margin-bottom:8px;">
<div style="width:150px; float:left; text-align:right; padding-top:7px;">
Team Filter:
</div>
<div style="width:250px; float:left;">
<input id="teamFilter" style="width: 100%" />
</div>
</div>
<div style="width:400px; float:left; margin-bottom:8px;">
<div style="width:150px; float:left; text-align:right; padding-top:7px;">
Type Filter:
</div>
<div style="width:250px; float:left;">
<input id="typeFilter" style="width: 100%" />
</div>
</div>
</div>
</div>
<div id="diaryTable" name="diaryTable" class="clear-fix">
Getting latest Headlines...
</div>
</fieldset>
I also have the following scripts
<script>
function teamFilterChange(e) {
//alert(this.value());
setCookie('c_team', this.value(), 90);
$c1 = getCookie('c_team');
$c2 = getCookie('c_type');
var param = "true|" + $c1 + "|" + $c2;
outputHLDiaryEntries(param);
}
function typeFilterChange(e) {
//alert(this.value());
setCookie('c_type', this.value(), 90);
$c1 = getCookie('c_team');
$c2 = getCookie('c_type');
var param = "true|" + $c1 + "|" + $c2;
outputHLDiaryEntries(param);
}
// This optional function html-encodes messages for display in the page.
function htmlEncode(value) {
var encodedValue = $('<div />').text(value).html();
return encodedValue;
}
function outputHLDiaryEntries(param) {
var url = "Home/DiaryEntries/";
var data = "id=" + param;
$.post(url, data, function (json) {
var n = json.length;
alert(n + ' ' + json);
if(n == 0){
//json is 0 length this happens when there were no errors and there were no results
$('#diaryTable').replaceWith("<span style='color:#e00;'><strong>Sorry: </strong> There are no headline events found. Check your filters.</span>");
} else {
//json has a length so it may be results or an error message
//if jsom[0].dID is undefined then this mean that json contains the error message from an exception
if (typeof json[0].dID != 'undefined') {
//json[0].dDI has a value so we
//output the json formatted results
var out = "";
var i;
var a = "N" //used to change the class for Normal and Alternate rows
for (i = 0; i < json.length; i++) {
out += '<div class="dOuter' + a + '">';
out += '<div class="dInner">' + json[i].dDate + '</div>';
out += '<div class="dInner">' + json[i].dRef + '</div>';
out += '<div class="dInner">' + json[i].dTeam + '</div>';
out += '<div class="dInner">' + json[i].dCreatedBy + '</div>';
out += '<div class="dType ' + json[i].dType + '">' + json[i].dType + '</div>';
out += '<div class="dServer">' + json[i].dServer + '</div>';
out += '<div class="dComment">' + htmlEncode(json[i].dComment) + '</div></div>';
//toggle for normal - alternate rows
if (a == "N") {
a = "A";
} else {
a = "N";
}
}
//output our formated data to the diaryTable div
$('#diaryTable').replaceWith(out);
} else {
//error so output json string
$('#diaryTable').replaceWith(json);
}
}
}, 'json');
}
$(document).ready(function () {
//Set User Preferences
//First check cookies and if null or empty set to default values
var $c1 = getCookie('c_team');
if ($c1 == "") {
//team cookie does not exists or has expired
setCookie('c_team', 'ALL', 90);
$c1 = "ALL";
}
var $c2 = getCookie('c_type');
if ($c2 == "") {
//type cookie does not exists or has expired
setCookie('c_type', "ALL", 90);
$c2 = "ALL";
}
// create DropDownList from input HTML element
//teamFilter
$("#teamFilter").kendoDropDownList({
dataTextField: "SupportTeamText",
dataValueField: "SupportTeamValue",
dataSource: {
transport: {
read: {
dataType: "json",
url: "Home/SupportTeams?i=1",
}
}
}
});
var teamFilter = $("#teamFilter").data("kendoDropDownList");
teamFilter.bind("change", teamFilterChange);
teamFilter.value($c1);
//typeFilter
$("#typeFilter").kendoDropDownList({
dataTextField: "dTypeText",
dataValueField: "dTypeValue",
dataSource: {
transport: {
read: {
dataType: "json",
url: "Home/DiaryTypes?i=1",
}
}
}
});
var typeFilter = $("#typeFilter").data("kendoDropDownList");
typeFilter.bind("change", typeFilterChange);
typeFilter.value($c2);
// Save the reference to the SignalR hub
var dHub = $.connection.DiaryHub;
// Invoke the function to be called back from the server
// when changes are detected
// Create a function that the hub can call back to display new diary HiLights.
dHub.client.addNewDiaryHiLiteToPage = function (name, message) {
// Add the message to the page.
$('#discussion').append('<li><strong>' + htmlEncode(name)
+ '</strong>: ' + htmlEncode(message) + '</li>');
};
// Start the SignalR client-side listener
$.connection.hub.start().done(function () {
// Do here any initialization work you may need
var param = "true|" + $c1 + "|" + $c2;
outputHLDiaryEntries(param)
});
});
</script>
On initial page load the outputHLDiaryEntries function is called when the signalR hub is started. If I then change any of the dropdownlists this calls the outputHLDiaryEntries but the $('#diaryTable').replaceWith(); does not work. If I refresh the page the correct data is displayed.
UPDATE!
Based on A.Wolff's comments I fixed the issue by wrapping the content I needed with the same element I was replacing... by adding the following line at the beginning of the outputHLDiartEntries function...
var outStart = '<div id="diaryTable" name="diaryTable" class="clear-fix">';
var outEnd = '</div>';
and then changing each of the replaceWith so that they included the wrappers e.g.
$('#diaryTable').replaceWith(outStart + out + outEnd);
replaceWith() replaces element itself, so then on any next call to $('#diaryTable') will return empty matched set.
You best bet is to replace element's content instead, e.g:
$('#diaryTable').html("<span>New content</span>");
I had the same problem with replaceWith() not working when called a second time.
This answer helped me figure out what I was doing wrong.
The change I made was assigning the same id to the new table I was creating.
Then when I would call my update function again, it would create a new table, assign it the same id, grab the previous table by the id, and replace it.
let newTable = document.createElement('table');
newTable.id = "sameId";
//do the work to create the table here
let oldTable = document.getElementById('sameId');
oldTable.replaceWith(newTable);

Masonry sometimes lays out in one column straight line

I have masonry initialized on some "tiles" that include an image. Most of the time I am not having issues but sometimes the tiles lay out in one column when there should be 3 columns. Do you have any idea what the issue might be?
On ready initialization:
$(document).ready(function() {
var $container = $('#news');
$container.masonry({
itemSelector: '.pageNewsItem',
transitionDuration: 0
});
$container.masonry( 'on', 'layoutComplete', function( msnryInstance, laidOutItems ) {debounced = true;} )
});
Dynamically append tiles:
var count = 0;
function placeNewsTiles(news){ //places news tiles
var length = (news.data.length > 20) ? 20 : news.data.length;
var elems ="";
for(var i = 0; i < length; i++){
elems += '<div class="pageNewsItem inactive" id="'+ count + i + '">\
<div class="outerTextWrap">\
<div class="textWrap">\
<a href="' + news.data[i]._url + '">\
<strong>' + news.data[i]._title + '</strong>\
</a>\
<span class="source">' + news.data[i]._source + '</span>\
</div>\
</div>\
<div class="imageWrap"></div>\
<div class="thumbsOverlay" style="display:none">\
<div class="thumbs">\
<div>\
\
\
</div>\
</div>\
<div class="title">\
<div>\
<a href="' + news.data[i]._url + '">\
<div class="theTitle">Read Article</div>\
</a>\
</div>\
</div>\
</div>\
</div>';
getTileImage({total: news.count, i:count + "" + i, url:news.data[i]._url});
}
elems = $(elems);
$('#news').append(elems).imagesLoaded(function(){
//for(var i = 0; i < length; i++) $('.pageNewsItem').removeClass('inactive'); //$('.pageNewsItem').show(1000);
$('#news').masonry( 'appended', elems);
});
newsPage = 0;
count++;
hoverTiles();
}
getTileImage function is called to conduct an ajax call to obtain the tile image. Masonry layout happens on complete:
var cnt = 0;
function getTileImage(args){
var _t = localStorage.getItem("token"),
url = args.url,
i = args.i;
$.ajax({
type: "GET",
url: apiHost+'/api/tileImg?url=' + url + '&token='+_t,
dataType: "json",
success: function(data) {
var img = (data && data.image.src) ? data.img.src : (data && data.image) ? data.image: "";
if(img.indexOf("spacer") > -1|| img.indexOf("blank") > -1 || img === ""){ $('.pageNewsItem#' + i).hide(); }
else $('.pageNewsItem#' + i).find('.imageWrap').append('<img src="' + img + '" />');
},
error: function(e) {
if (e.status == 404) {
//need to get a new token
getToken(getTileImage, url);
}
}, complete: function(){
cnt++;
if ((cnt ==20) || cnt == args.total) {
var $container = $('#news');
$container.imagesLoaded( function() {
$container.masonry( 'layout' );
$('.pageNewsItem').removeClass('inactive');
//$('.pageNewsItem').show();
});
cnt = 0;
}
/*$('#news').imagesLoaded( function() {
$('.pageNewsItem#' + i + ' .thumbs').height($('.pageNewsItem#' + i).outerHeight() - $('.pageNewsItem#' + i + ' .title').height() - 5);
//$('.pageNewsItem').show();
});*/
}
});//end ajax call
}
CSS:
.pageNewsItem {
width: 33.333%;
padding: 10px;
min-height: 150px;
opacity: 1;
transition: opacity 1s ease;
}
#news {
margin-right: 20px;
margin-top: 25px;
}
Try using the console and manually initialize masonry:
$('#news').masonry();
If it is not working, masonry might be already initialized and therefore it's not repositioning the elements. In that case you have to remove masonry from the div and reinitialize it:
$('#news').masonry('destroy');
$('#news').masonry();

Categories

Resources