Highlight.js and Showdown.js not work together - javascript

I am trying to be able to use highlight.js when my preview is enabled
Unable to get the highlightjs to work with my preview using showdown.js
Question: How to get the highlight.js to work with showdown.js
Codepen Demo Note all the .js files and css files are loaded in the codepen settings
I have tried using
$(document).ready(function() {
$('pre code').each(function(i, block) {
hljs.highlightBlock(block);
});
});
$("#message").on('keyup paste cut', function() {
var text = document.getElementById('message').value,
target = document.getElementById('showdown'),
converter = new showdown.Converter({
parseImgDimensions: true
}),
html = converter.makeHtml(text);
target.innerHTML = html;
});
Full Script
$(document).ready(function() {
$('pre code').each(function(i, block) {
hljs.highlightBlock(block);
});
})
$('#button-link').on('click', function() {
$('#myLink').modal('show');
});
$('#button-image').on('click', function() {
$('#myImage').modal('show');
});
$('#button-smile').on('click', function() {
$('#mySmile').modal('show');
});
$('#myLink').on('shown.bs.modal', function() {
var textarea = document.getElementById("message");
var len = textarea.value.length;
var start = textarea.selectionStart;
var end = textarea.selectionEnd;
var selectedText = textarea.value.substring(start, end);
$('#link_title').val(selectedText);
$('#link_url').val('http://');
});
$('#myImage').on('shown.bs.modal', function() {
$("#image_url").attr("placeholder", "http://www.example.com/image.png");
});
$("#save-image").on('click', function(e) {
var textarea = document.getElementById("message");
var len = textarea.value.length;
var start = textarea.selectionStart;
var end = textarea.selectionEnd;
var selectedText = textarea.value.substring(start, end);
var counter = findAvailableNumber(textarea);
var replace_word = '![enter image description here]' + '[' + counter + ']';
if (counter == 1) {
if ($('input#image_width').val().length > 0) {
var add_link = '\n\n' + ' [' + counter + ']: ' + $('#image_url').val() + ' =' + $('input#image_width').val() + 'x' + $('input#image_height').val();
} else {
var add_link = '\n\n' + ' [' + counter + ']: ' + $('#image_url').val();
}
} else {
var add_link = '\n' + ' [' + counter + ']: ' + $('#image_url').val();
}
textarea.value = textarea.value.substring(0, start) + replace_word + textarea.value.substring(end, len) + add_link;
$("#message").trigger('change');
});
$("#save-link").on('click', function(e) {
var textarea = document.getElementById("message");
var len = textarea.value.length;
var start = textarea.selectionStart;
var end = textarea.selectionEnd;
var selectedText = textarea.value.substring(start, end);
var counter = findAvailableNumber(textarea);
if ($('#link_title').val().length > 0) {
var replace_word = '[' + $('#link_title').val() + ']' + '[' + counter + ']';
} else {
var replace_word = '[enter link description here]' + '[' + counter + ']';
}
if (counter == 1) {
var add_link = '\n\n' + ' [' + counter + ']: ' + $('#link_url').val();
} else {
var add_link = '\n' + ' [' + counter + ']: ' + $('#link_url').val();
}
textarea.value = textarea.value.substring(0, start) + replace_word + textarea.value.substring(end, len) + add_link;
$("#message").trigger('change');
});
// Editor Buttons
$('#bold').on('click', function(e) {
text_wrap("message", "**", "**", 'strong text');
});
$('#italic').on('click', function(e) {
text_wrap("message", "*", "*", 'emphasized text');
});
$('#quote').on('click', function(e) {
text_wrap("message", "> ", "", 'Blockquote');
});
$('#code').on('click', function(e) {
code_wrap("message", "", "", 'enter code here');
});
function text_wrap(elementID, openTag, closeTag, message) {
var textArea = $('#' + elementID);
var len = textArea.val().length;
var start = textArea[0].selectionStart;
var end = textArea[0].selectionEnd;
var selectedText = textArea.val().substring(start, end);
if (selectedText.length > 0) {
replacement = openTag + selectedText + closeTag;
} else {
replacement = openTag + message + closeTag;
}
textArea.val(textArea.val().substring(0, start) + replacement + textArea.val().substring(end, len));
}
function code_wrap(elementID, openTag, closeTag, message) {
var textArea = $('#' + elementID);
var len = textArea.val().length;
var start = textArea[0].selectionStart;
var end = textArea[0].selectionEnd;
var selectedText = textArea.val().substring(start, end);
var multiLineReplace = '\n' + openTag;
if (selectedText.length > 0) {
//using regex to replace all instances of `\n` with `\n` + your indent spaces.
replacement = ' ' + openTag + selectedText.replace(/\n/g, multiLineReplace) + closeTag;
} else {
replacement = ' ' + openTag + message + closeTag;
}
textArea.val(textArea.val().substring(0, start) + replacement + textArea.val().substring(end, len));
}
function findAvailableNumber(textarea) {
var number = 1;
var a = textarea.value;
if (a.indexOf('[1]') > -1) {
//Find lines with links
var matches = a.match(/(^|\n)\s*\[\d+\]:/g);
//Find corresponding numbers
var usedNumbers = matches.map(function(match) {
return parseInt(match.match(/\d+/)[0]);
});
//Find first unused number
var number = 1;
while (true) {
if (usedNumbers.indexOf(number) === -1) {
//Found unused number
return number;
}
number++;
}
}
return number;
}
$("#message").on('keyup paste cut', function() {
var text = document.getElementById('message').value,
target = document.getElementById('showdown'),
converter = new showdown.Converter({
parseImgDimensions: true
}),
html = converter.makeHtml(text);
target.innerHTML = html;
});
$(function() {
$('[data-toggle="tooltip"]').tooltip()
});

Related

How to process large jquery each loop without crashing browser(mainly firefox)

I made a javascript code to create some html element in parent iframe based on user selection from an iframe in a popup.
My code is given below.
The each loop may contain 50 to 150 iteration. Sometimes when I call function AddProcedures the Mozilla crashes during iteration, Is there any way to fix this issue or to reduce the browser load. I tried to put setTimeout after some code blocks but it didn't help.
I have also changed the for loop to jquery each, just to try if that helps.
var tot_codes = 0;
function doAddProcedure(thisVal,resolve){
var enc_id = $("#cpt_encounter").val();
var rowId = window.parent.$("[data-encounterBilled='"+ enc_id +"']").closest('tr').attr('id'); // table row ID
var recalc = parseInt(rowId.substring(rowId.indexOf('id-')+3));
var countval = $("#last_id").val();
//Load issue Fix
//Old code
//for (i = 0; i < document.cpt.elements.length; i++) {
//if (document.cpt.elements[i].type == "checkbox") {
//if (document.cpt.elements[i].checked == true) {
$('#cpt input:checkbox:checked').each(function(){
setTimeout(function() { }, 100);
var currentCodeMod = $(this).attr("data-codemod");
var currentCodeTypid = $(this).attr("data-codeTypeid");
if (currentCodeMod == null)
return;
tot_codes++;
var nextcntval = parseInt(countval) + 1;
var code_no = $(this).attr("id").replace("cpt_chkbx", "");
var Code = $("#codeVal" + code_no).val();
var just = $("#codeType" + code_no).val();
var categoryId = $("#codeType" + code_no).data("categoryid"); //Added to get category //Bug Fix
var Name = $("#cpttext" + code_no).val();
var codedisp = Code + ':' + Name;
var Modifier = '';
//if($("#modifier_setngs").val() == 1){
var Modifier1 = $("#modcpt1"+code_no).val() != '' ? $("#modcpt1"+code_no).val() + ":" : '';
var Modifier2 = $("#modcpt2"+code_no).val() != '' ? $("#modcpt2"+code_no).val() + ":" : '';
var Modifier3 = $("#modcpt3"+code_no).val() != '' ? $("#modcpt3"+code_no).val() + ":" : '';
var Modifier4 = $("#modcpt4"+code_no).val() != '' ? $("#modcpt4"+code_no).val() + ":" : '';
Modifier = Modifier1 + Modifier2 + Modifier3 + Modifier4;
//}
var codetableid = $("#code_tab_id" + code_no).val();
var j = countval; /* lineitem wise uniqid */
//var encounter = window.parent.$('#codetype-' + j).closest('tr.charge-entry-row').find('.expand-actions').attr('data-encounterid');
var encounter = enc_id;
var codeforarr = encounter + ':' + just + ':' + Code + '::' + Modifier;
window.parent.pushToArray(codeforarr);
var f = 0;
$(window.parent.$("#codetype-" + countval).parents().find('.inner-table .charge-entry-row')).each(function() {
//console.log($(this).find('.inputStringHidden').val() + '/' + codeforarr);
if ($(this).find('.inputStringHidden').val() == codeforarr) {
var exis_row_id = $(this).find('.inputStringHidden').attr('id').split('inputStringHidden-');
j = exis_row_id[1].toString();
f = 1;
$(this).find('.front_pay_codes_display').trigger('click');
}
});
if (f == 0) {
if (window.parent.document.getElementById('inputStringHidden-' + countval).value != '') {
window.parent.$("#codetype-" + countval).children().parent().parent().parent().siblings().find('.addnew-row').attr('data-rowadd', 'fromdb').trigger("click");
countval = parseInt(countval) + 1;
j = countval.toString();
}
window.parent.$("#add-" + countval).trigger("click");
window.parent.$("#codetype-" + (countval)).val(currentCodeTypid);
window.parent.$("#codetype-" + countval).trigger("change");
}
window.parent.document.getElementById('inputString' + j).value = codedisp;
window.parent.document.getElementById('category-' + j).value = categoryId; //Added to set category //Bug Fix
window.parent.document.getElementById('string_id' + j).value = Code;
window.parent.document.getElementById('string_value' + j).value = Name;
window.parent.document.getElementById('inputStringHidden-' + j).value = codeforarr;
window.parent.document.getElementById('codetableid-' + j).value = codetableid;
window.parent.$("#inputString" + j).closest('tr.charge-entry-row').find('.val-change-bit').val(1);
setTimeout(function() {}, 100);
window.parent.$("#suggestions" + j).hide();
window.parent.$("#inputString" + j).focus();
var uniqidHidden = window.parent.$("#inputString" + j).closest('tr.charge-entry-row').find('.uniqid-hidden').val();
window.parent.$('#add-modifier' + j).parent().find('.displaymode-elem').text(Modifier);
//if($("#modifier_setngs").val() == 1){
if (f == 0) {
window.parent.$('#add-modifier' + j).parent().find('.displaymode-elem').addClass('area-hide');
}else{
window.parent.$('#add-modifier' + j).parent().find('.displaymode-elem').removeClass('area-hide');
}
window.parent.$('#modifiers' + uniqidHidden).val(Modifier);
arr = Modifier.split(':');
window.parent.$('#modifier-' + uniqidHidden + '-1').val(arr[0]);
window.parent.$('#modifier-' + uniqidHidden + '-2').val(arr[1]);
window.parent.$('#modifier-' + uniqidHidden + '-3').val(arr[2]);
window.parent.$('#modifier-' + uniqidHidden + '-4').val(arr[3]);
//}
var eclaimPlanActive = window.parent.$('#eclaimPlanActive').val();
var price = $("#cpt_price" + code_no).val();
var price_level = $("#pricelevelhidden" + code_no).val();
if (price == 0 || price == null)
price = 0;
window.parent.$('#price-' + j).val(price);
window.parent.$('#bill-pricelevel-' + j).val(price_level);
/** Charge Total **/
var chargeTotal = window.parent.$('#charge-total').text().replace(/[\s\,]/g, '').trim();
if (chargeTotal == '')
chargeTotal = parseFloat(0);
var tempChargeTotal = parseFloat(chargeTotal) + parseFloat(price);
window.parent.$('#charge-total span').html(tempChargeTotal);
/** End **/
var units = $("#cpt_units" + code_no).val(); //data[0]['units']
if (units == 0 || units == null)
units = 1;
window.parent.$('#qty-' + j).val(units);
var tax = 0;
var disc = 0;
setTimeout(function() { }, 100);
if (window.parent.$('#tax-' + j).length > 0)
tax = window.parent.$('#tax-' + j).val().replace(/[\s\,]/g, '');
if (window.parent.$('#discount-' + j).length > 0)
disc = window.parent.$('#discount-' + j).val().replace(/[\s\,]/g, '');
var amount = price * units;
amount = amount + ((amount * tax) / 100);
if (disc > 0) {
var p = price * units;
var dc = ((p * disc) / 100);
amount = amount - dc;
}
/** Discount Total **/
var disTotal = window.parent.$('#discount-total').text().replace(/[\s\,]/g, '').trim();
if (disTotal == '')
disTotal = parseFloat(0);
var tempDisTotal = parseFloat(disTotal) + parseFloat(dc);
if (isNaN(tempDisTotal) == true) {
tempDisTotal = '0.00';
}
window.parent.$('#discount-total').html(tempDisTotal);
/** End **/
if (!parseFloat(window.parent.$('#lineitempaid-' + j).val()))
window.parent.$('#lineitempaid-' + j).val('0.00');
window.parent.$('#total-' + j).val(amount);
window.parent.$('#remainder-' + j).val(amount);
window.parent.$('#hidremainder-' + j).val(amount);
//insurance and patient_share
if (eclaimPlanActive == '1') {
var codetableid = window.parent.$('#codetableid-' + j).val();
var parentRowVal = parseInt(window.parent.$('#codetableid-' + j).closest('tr').find('.row_value').attr('data-rowvalue')) - 1;
var insData1 = window.parent.$('tr#row-id-' + parentRowVal + ' .encounter').attr('data-insdata1');
window.parent.getBenefitCategoryOfCode(j, codetableid, insData1);
if (window.parent.$('#have-benefit').val() == '0') {
var insData2 = window.parent.$('tr#row-id-' + parentRowVal + ' .encounter').attr('data-insdata2');
window.parent.getBenefitCategoryOfCode(j, codetableid, insData2);
}
}
var passParams = '';
window.parent.calculate('qty-' + j, passParams);
//Updating the title
window.parent.$("#inputString" + j).closest('tr.charge-entry-row').find('.fi-searchitems').attr('data-original-title', codedisp);
if (f == 0) {
//Display DIv :: Relace with new values
var cloneLabel = window.parent.$("#inputString" + j).closest('tr.charge-entry-row').find('.show_label').clone();
//In Edit Mode
if (cloneLabel.find('.displaymode-elem').length > 0) {
var $max_length = 16;
var trucncateCode = Name;
if (trucncateCode.length > $max_length)
trucncateCode = trucncateCode.substring(0, $max_length) + '...';
cloneLabel.find('.front_pay_codetype').text(just + ":");
cloneLabel.find('.front_pay_code').text(trucncateCode);
cloneLabel.find('.displaymode-elem').removeClass('area-hide');
cloneLabel.removeClass('area-hide');
cloneLabel.find("input[name='code_type']").val(just).attr('id', 'code_type-' + j);
cloneLabel.find("input[name='string_id']").val(Code).attr('id', 'string_id-' + j);
cloneLabel.find("input[name='string_value']").val(Name);
var dataType = $("#inputString" + j).closest('tr.charge-entry-row').find('.data_type').val();
if (dataType == "lab") {
var lab = $("select[name='lab_type']").find('option:selected').val();
if (cloneLabel.find("input[name='lab_type']").length > 0) {
cloneLabel.find("input[name='lab_type']").val(lab);
} else {
cloneLabel.append('<input type="hidden" name="lab_type" class="lab_type" value="' + lab + '">');
}
} else {
cloneLabel.find("input[name='lab_type']").remove();
}
setTimeout(function() { }, 100);
//Making the view
cloneLabel.removeClass('area-hide');
window.parent.$("#inputString" + j).closest('tr.charge-entry-row').find('.front_pay_codes_editelem').removeClass('area-show').addClass('area-hide');
window.parent.$("#inputString" + j).closest('tr.charge-entry-row').find('.show_label').replaceWith(cloneLabel);
window.parent.$("#inputString" + j).closest('tr.charge-entry-row').find('.show_autosuggest').html('');
}
window.parent.$("#codetype-" + countval).children().parent().parent().parent().siblings().find('.addnew-row').attr('data-rowadd', 'fromdb').trigger("click");
countval = nextcntval.toString();
}
else {
window.parent.$("#suggestions" + j).hide();
countval = countval.toString();
}
setTimeout(function() { }, 150);
});
window.parent.reCalculatePlanEncounterWise(recalc);
resolve("Success!");
}
function doAddPromise(thisVal){
return new Promise(function(resolve){
doAddProcedure(thisVal,resolve);
});
}
function AddProcedures(thisval)
{
$('#procedureSaveButton').text('Processing....');
// $('.fa-spinner').removeClass('hide');
top.ShowAjaxLoader('Loading..');
setTimeout(function(){
}, 2000);
//top.ShowAjaxLoader('Loading..');
setTimeout(function(){
$.when(doAddPromise(thisval)).done(function(){
if (tot_codes > 0) {
window.parent.phFrntpayClosePopup();
top.notification('Successfully added the procedures.');
//top.HideAjaxLoader('Loading..');
top.HideAjaxLoader();
$('body').removeClass('modal-open');
} else {
top.notification('Please select atleast one procedure.');
$('#procedureSaveButton').text('Add Procedures');
//$('.fa-spinner').addClass('hide');
top.HideAjaxLoader();
}
});
}, 10);
}

Removing new line under link in textarea

When I create a new link for my textarea it creates a new line like
[enter link description here][1] and [enter link description here][2]
[1]: http://
[2]: http://
As you can see above there is a gap between the bottom two links I don't want the gap there
It should look like
[enter link description here][1] and [enter link description here][2]
[1]: http://
[2]: http://
Question how to make it so when create new link that there are no gaps
for the bottom links.
Here is a codepen demo has been updated with working code
<script type="text/javascript">
$('#myLink').on('shown.bs.modal', function() {
var textarea = document.getElementById("message");
var len = textarea.value.length;
var start = textarea.selectionStart;
var end = textarea.selectionEnd;
var selectedText = textarea.value.substring(start, end);
$('#title').val(selectedText);
$('#url').val('http://');
});
$('#save').on('click', function(e) {
var textarea = document.getElementById("message");
var len = textarea.value.length;
var start = textarea.selectionStart;
var end = textarea.selectionEnd;
var selectedText = textarea.value.substring(start, end);
var counter = findAvailableNumber(textarea);
if ($.trim($('#title').val()).length == 0){
var replace_word = '[enter link description here]' + '[' + counter + ']';
} else {
var replace_word = '[' + $(this).val() + ']' + '[' + counter + ']';
}
var add_link = '\n\n' + ' [' + counter + ']: ' + $('#url').val();
textarea.value = textarea.value.substring(0, start) + replace_word + textarea.value.substring(end,len) + add_link;
});
function findAvailableNumber(textarea){
var number = 1;
var a = textarea.value;
if(a.indexOf('[1]') > -1){
//Find lines with links
var matches = a.match(/(^|\n)\s*\[\d+\]:/g);
//Find corresponding numbers
var usedNumbers = matches.map(function(match){
return parseInt(match.match(/\d+/)[0]); }
);
//Find first unused number
var number = 1;
while(true){
if(usedNumbers.indexOf(number) === -1){
//Found unused number
return number;
}
number++;
}
}
return number;
}
</script>
I think your code at:
var add_link = '\n\n' + ' [' + counter + ']: ' + $('#url').val();
should instead be
if (counter == 1)
var add_link = '\n\n' + ' [' + counter + ']: ' + $('#url').val();
else
var add_link = '\n' + ' [' + counter + ']: ' + $('#url').val();
so that there is no gap between links, except between the text and link. Since the links should be next to each other (see assumption below), only the first link should have a gap
ASSUMPTION: I'm assuming there shouldn't be any text after the links.

InnerHTML Append Item instead of Replace

I'm trying to make a palindrome script and it's actually "working".
I want to make a improvement. I want the input value append on my "output" div.
here are my fiddle http://jsfiddle.net/vitorboccio/8yh1u0t7/
any hints ? I dont want to use Jquery ! Thanks!
(function () {
"use strict";
var output = document.getElementById("output"),
statusLine = document.getElementById("status"),
phrase = document.getElementById('phrase'),
testButton = document.getElementById("testButton"),
//palindromeText = document.getElementById("palindrome"),
characterCheck = document.getElementById("characterCheck"),
ignoreSpecialCharacters = false,
ignoreSpaces = false;
function setMessage(palindrome) {
if (palindrome) {
output.innerHTML = phrase.value + ' ' + "é palindroma";
} else {
output.innerHTML = phrase.value + ' ' + "não é a palindroma";
}
}
function checkForPalindrome(string) {
var palindrome = true,
right = string.length - 1,
left = 0;
if (!string || string.length < 1) {
// 0 characters
return false;
}
while (left < right && palindrome) {
palindrome = string.charAt(left) === string.charAt(right);
left++;
right--;
}
return palindrome;
}
function executeTest() {
var string = phrase.value,
cleanString;
cleanString = string;
if (ignoreSpaces) {
//ignores whitespaces only;
cleanString = string.replace(/\s+/g, '');
}
if (ignoreSpecialCharacters) {
//ignores punctuation and white space (controversial).
cleanString = string.replace(/[A-Z0-9]/ig, '');
}
if (checkForPalindrome(cleanString)) {
setMessage(true);
palindromeText.innerHTML = '"' + string + '"';
} else {
setMessage(false);
}
}
function executeOnEnter(e) {
if (e.keyCode === 13) {
executeTest();
// phrase.blur();
}
}
//resets the form to state 1
function resetForm() {
output.innerHTML = "";
//statusLine.innerHTML = "Waiting";
statusLine.style.color = "green";
phrase.value = "";
}
function charIgnoreChanged(e) {
ignoreSpecialCharacters = e.target.checked;
}
function spaceIgnoreChanged(e) {
ignoreSpaces = e.target.checked;
}
phrase.addEventListener('keydown', executeOnEnter);
testButton.addEventListener('click', executeTest);
characterCheck.addEventListener('change', charIgnoreChanged);
spaceCheck.addEventListener('change', spaceIgnoreChanged);
}());
You just need to modify setMessage
function setMessage(palindrome) {
if (palindrome) {
output.innerHTML += phrase.value + ' ' + "é palindroma<br />";
} else {
output.innerHTML += phrase.value + ' ' + "não é a palindroma<br />";
}
// for user convenience, clear the textbox and give it focus
phrase.value = '';
phrase.focus();
}
Fiddle
You can append to the div by keeping the original innerHTML like this:
output.innerHTML = output.innerHTML + "<br />" + phrase.value + ' ' + "é palindroma";
or shorter:
output.innerHTML += "<br />" + phrase.value + ' ' + "é palindroma";

"Page Unresponsive" Error in Chrome when trying to GET files > 500kb

I am trying to get Log files in my application, and am using Ajax to do so.
The problem is that while using Chrome I constantly get 'Page Unresponsive' Errors when I try to load the files.
My application is working fine in Firefox, so I'm guessing this is a webkit issue.
I removed xhr because I heard chrome has a problem with it.
This is my code -
$.ajax(
{
type: 'GET',
url: "Logs/GetLogFile?option=" + logFile,
data: {},
success: function (data) {
var fileData = data;
cleanUp();
currentlyViewedFile = logFile;
var fileLines = fileData.split('\n');
var htmlString = '';
var lineCount = 0;
for (var i = 0; i < fileLines.length; i++) {
lineCount = lineCount + 1;
if (i == (highlightLine - 1)) {
htmlString += '<span id="highLoc" style="display:block"><font size="4" color="red">' + lineCount + '. ' + fileLines[i] + '</font></span>';
}
else {
htmlString += '<span class="spanClass">' + lineCount + '. ' + fileLines[i];
}
var combinedLine = fileLines[i];
var isNewLogLine = false;
var newLogLineCount = 0;
while (((i + newLogLineCount + 1) < fileLines.length) && (isNewLogLine == false)) {
var NextlogLine = fileLines[i + newLogLineCount + 1].split(' ');
isNewLogLine = isLogLine(NextlogLine[0]);
if (isNewLogLine == true) {
break;
}
htmlString += fileLines[i + newLogLineCount + 1];
combinedLine += fileLines[i + newLogLineCount + 1];
newLogLineCount = newLogLineCount + 1
}
i = i + newLogLineCount;
var logLine = combinedLine.split(' ');
var logMsgStartIndex = combinedLine.indexOf(logLine[5]);
var logMsg = combinedLine.substring(logMsgStartIndex);
var obj = {
lineNos: lineCount,
date: logLine[0],
time: logLine[1],
severity: logLine[2],
logClassName: logLine[4],
logMessage: logMsg
};
fileArray.push(obj);
if ((i % 1000) == 0) {
$("#textPlace").append(htmlString);
htmlString = '';
window.scrollTo(0, 2);
}
}
fileLines = null;
$("#fetchProgress").hide();
$("#textPlace").append(htmlString);
//highlight error location
var scrollX = $("#highLoc");
if (scrollX) {
if (!scrollX[0]) return;
var scrollDistance = '{ scrollTop: ' + scrollX[0].offsetTop + '}';
var distanceInJson = eval("(" + scrollDistance + ")");
$("#mainContentBox").animate(distanceInJson, 1);
}
},
///success function end
fail: function (jqXHR, textStatus) {
alert("Request failed: " + textStatus);
}
});
If anyone has any ideas on how to deal with this issue, please let me know.

maintaining a sorted jQuery accordion

I have a situation where I receive certain events over time that each have a timestamp associated with them. I am putting it into a Jquery accordion section that is labelled by date. It works except that I wish to maintain the accordion sections in sorted descending order, i.e most recent date at the top and events belonging to that date go into that section. Here is the complete code I have so far, currently I just append a new date to the end. How do I insert so that it is sorted?
$(function() {
$("#accordion").accordion({
collapsible: true
});
});
function getRandInt(max) {
return Math.floor(Math.random() * Math.floor(max))
}
function getRandomTime() {
var t = ['AM', 'PM']
var hr = getRandInt(13);
var mn = getRandInt(60);
var sec = getRandInt(60);
var ampm = t[Math.floor(Math.random() * 2)]
return (hr + ':' + mn + ':' + sec + " " + ampm);
}
function getRandomDate() {
var month = getRandInt(13);
var day = getRandInt(28);
return ('2018-' + month + '-' + day);
}
function getRandomEvent() {
var events = ['General Event', 'Random', 'Splash', 'Car crash', 'Touchdown', 'Rain', 'Snow'];
var rand = events[Math.floor(Math.random() * events.length)];
return rand;
}
function getRandomSection(sections) {
var rand = sections[Math.floor(Math.random() * sections.length)];
return rand;
}
function getPopupDivId(t, e, d) {
var popup_div_str = t + e;
var popup_div_id = popup_div_str.replace(/\s{1,}/g, "");
popup_div_id = popup_div_id.replace(/:/g, "");
return popup_div_id;
}
function getDescriptiveDate(dateStr) {
var d_t = dateStr.split("T");
var timeStr = d_t[0] + " " + d_t[1];
console.log(timeStr);
var date = new Date(timeStr + ' UTC');
return "Event time: " + date.toString()
}
function makeTable(eventDetails) {
var d = getDescriptiveDate("2018-11-07T00:49:05");
var popupStr = d + '<br>' + '<table border="1"><tr><th>Parameter Name</th><th>Value</th></tr>';
var data = JSON.parse(eventDetails);
var startTag = '<tr><td>';
var endTag = '</td>';
var rowEnd = '</tr>'
for (var key in data) {
popupStr += (startTag + key + endTag + '<td>' + data[key] + endTag + rowEnd);
}
return popupStr + '</table>';
}
var currentDialog = '';
function setPopupDiv(t, e, d, popup_div_id) {
var table = makeTable('{"Temp": 24, "WindChill": "14", "Dew point": 10}');
var popup_div = '<div id="dialog' + popup_div_id + '\" ' + 'style="display:none">' + table + '</div>';
console.log("setPopupDiv: popup div: " + popup_div);
$('.' + d).append(popup_div);
$('#' + popup_div_id).click(function() {
$(function() {
if (currentDialog == '') {
currentDialog = "#dialog" + popup_div_id;
} else {
console.log('closing dialog' + currentDialog);
$(currentDialog).dialog('close');
currentDialog = "#dialog" + popup_div_id;
}
$("#dialog" + popup_div_id).dialog();
$("#dialog" + popup_div_id).dialog('open');
});
console.log("dialog link click");
return false;
});
}
/* "Create new accordion" button handler */
function addData() {
var d = getRandomDate();
var e = getRandomEvent();
var t = getRandomTime();
var popup_div_id = getPopupDivId(t, e, d);
var ev = '' + t + ' ' + '' + e;
var section = '<h3>' + d + '</h3>';
var dom_element = section + '<div>' + '<ul class=\"' + d + '\">' + '<li>' + ev + '</li></ul>' + '</div>';
$('#accordion').append(dom_element)
.accordion('destroy').accordion({
collapsible: true
});
setPopupDiv(t, e, d, popup_div_id);
console.log("addData(): " + dom_element);
var e2 = getRandomEvent();
var t2 = getRandomTime();
popup_div_id = getPopupDivId(t2, e2, d);
var ev2 = '<li>' + '' + t2 + ' ' + '' + e2 + '</li>';
$('.' + d).append(ev2);
setPopupDiv(t2, e2, d, popup_div_id);
}
function addDataActual(eventDate, eventTime, eventType) {
var popup_div_id = getPopupDivId(eventTime, eventType, eventDate);
var evt = '' + eventTime + ' ' + '' + eventType;
var section = '<h3>' + eventDate + '</h3>';
var dom_element = section + '<div>' + '<ul class=\"' + eventDate + '\">' + '<li>' + evt + '</li></ul>' + '</div>';
var arrayOfClassNames = $("#accordion *").map(function() {
if ($(this).attr('class')) {
if ($(this)[0].nodeName == 'UL') {
if (this.className == eventDate) {
return this.className;
}
}
}
}).get();
if (arrayOfClassNames.length == 0) {
/* New section */
$('#accordion').append(dom_element)
.accordion('destroy').accordion({
collapsible: true
});
setPopupDiv(eventTime, eventType, eventDate, popup_div_id);
console.log(dom_element);
} else {
/* Exists already*/
d = arrayOfClassNames[0];
popup_div_id = getPopupDivId(eventTime, eventType, d);
var eventToAppend = '<li>' + '' + eventTime + ' ' + '' + eventType + '</li>';
$('.' + d).append(eventToAppend);
setPopupDiv(eventTime, eventType, d, popup_div_id);
}
}
function addDataOrNew() {
var arrayOfClassNames = $("#accordion *").map(function() {
if ($(this).attr('class')) {
if ($(this)[0].nodeName == 'UL') {
return this.className;
}
}
}).get();
var toss = getRandInt(2);
if (toss == 0) {
var d = getRandomSection(arrayOfClassNames);
console.log("toss returned 0, adding to existing section " + d);
console.log("Chosen one to add to:" + d);
var e = getRandomEvent();
var t = getRandomTime();
addDataActual(d, t, e);
} else {
var d = getRandomDate();
console.log("toss returned 1, adding a new section " + d);
var e = getRandomEvent();
var t = getRandomTime();
addDataActual(d, t, e);
}
}
function addDataToRandomSection() {
var e = getRandomEvent();
var t = getRandomTime();
var arrayOfClassNames = $("#accordion *").map(function() {
if ($(this).attr('class')) {
if ($(this)[0].nodeName == 'UL') {
return this.className;
}
}
}).get();
console.log(arrayOfClassNames);
d = getRandomSection(arrayOfClassNames);
console.log("Chosen one:" + d);
var e2 = getRandomEvent();
var t2 = getRandomTime();
var popup_div_id = getPopupDivId(t2, e2, d);
var ev2 = '<li>' + '' + t2 + ' ' + '' + e2 + '</li>'
$('.' + d).append(ev2);
setPopupDiv(t2, e2, d, popup_div_id);
}
function addDataToTopSection() {
var e2 = getRandomEvent();
var t2 = getRandomTime();
var arrayOfClassNames = $("#accordion *").map(function() {
if ($(this).attr('class')) {
if ($(this)[0].nodeName == 'UL') {
return this.className;
}
}
}).get();
d = arrayOfClassNames[0];
var popup_div_id = getPopupDivId(t2, e2, d);
setPopupDiv(t2, e2, d, popup_div_id);
var ev2 = '<li>' + '' + t2 + ' ' + '' + e2 + '</li>'
$('.' + d).append(ev2);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<link href='https://code.jquery.com/ui/1.12.1/themes/cupertino/jquery-ui.css' rel='stylesheet'>
<!doctype html>
<button onclick="addData()" class="regular">Create new Accordion</button>
<button onclick="addDataToRandomSection()" class="regular">Add data to random section</button>
<button onclick="addDataOrNew()" class="regular">Add new section or append to existing</button>
<fieldset id="patient-event-list">
<legend>Event History</legend>
<div id="eventinfo-body">
<button type="button" id="more" onclick="addDataToTopSection()">More history</button>
</div>
<div id="accordion" class="accordion">
</div>
</fieldset>

Categories

Resources