How to display HTMLpropertiescollection (toString/object property) - javascript

I'm writing a remote/in-browser logging tool (basically an in browser console so I can remote debug mobile devices and whatnot) and I am having trouble printing/accessing some raw DOM elements and objects (They appear to be objects when I log them to the console). When call bronsole (don't judge me) on the event object some of the DOM objects are not being looped through as if the for loop doesn't recognise it as an object. One of the objects in question is the HTMLpropertiescollection. I don't have any particular need for this oject specifically but I am logging touch events and it would be nice to be able to read all of the properties of the event object.
(function ($) {
$('body').prepend('<div id="eoenuitn345n34ntdhiu45dnth" style="position: fixed; top:0; left: 0; width: 100%; height: 100px; background-color: rgba(0,0,0,0.5); z-index: 1000000; overflow-y: auto; padding-top: 40px;"><div id="seouihtoeuitnei98e797etuiST" style="position:absolute; top: 5px; right: 5px; background-color: #C0504D; height: 20px; width: 20px;"></div></div>');
$('#eoenuitn345n34ntdhiu45dnth').click(function(e){
if($(this).height() <= 150){
$(this).animate({height: '100%'});
}else{
$(this).animate({height: '150px'});
}
});
$('#seouihtoeuitnei98e797etuiST').click(function(e){
e.stopPropagation();
if($(this).parent().height() <= 30){
$(this).parent().animate({height: '100%'});
}else{
$(this).parent().animate({height: '0px'});
}
});
$('#eoenuitn345n34ntdhiu45dnth').on('click','.oseu098oaeuno7e089',function(e){
e.stopPropagation();
if($(this).height() > 15){
$(this).css('height', '15px');
$.each($(this).children('.oseu098oaeuno7e089'), function(){
$(this).css('height', '15px');
});
}else{
$(this).css('height', 'auto');
}
if($('#eoenuitn345n34ntdhiu45dnth').height() <= 100){
$('#eoenuitn345n34ntdhiu45dnth').animate({height: '100%'});
}
});
$('#eoenuitn345n34ntdhiu45dnth').on('click','.oeusn0eui0HTDRh98oeui',function(e){
e.stopPropagation();
});
window.uonteuho8o6e8ued68uou8Color = ['#6BC3FF','#FF494F','#00D3D3','#77FF6B','#DBD300','#D470FF'];
var entityMap = {
"&": "&",
"<": "<",
">": ">",
'"': '"',
"'": ''',
"/": '/'
};
function escapeHtml(string) {
return String(string).replace(/[&<>"'\/]/g, function (s) {
return entityMap[s];
});
}
function htmlConsole(param){
var obj = (typeof param.NTDNTH8oe8uidu98NT != 'undefined') ? param.NTDNTH8oe8uidu98NT : param;
var index = (typeof param.sjtnhxsSTHxsnheu9isTH != 'undefined') ? param.sjtnhxsSTHxsnheu9isTH : null;
var preKey = (typeof param.sntuhinegdukx0euetkhe989 != 'undefined') ? '[' + param.sntuhinegdukx0euetkhe989 + ']: ' : '';
var spaceAdd = (typeof param.sNDGHBn788rnFI9 != 'undefined') ? param.sNDGHBn788rnFI9 + '____' : '';
var depth = (typeof param.netnuxie0xbenuihtdNT09 != 'undefined') ? param.netnuxie0xbenuihtdNT09 + 1 : '0';
var element = '';
if(typeof obj != null){
if(typeof obj == 'string' || typeof obj == 'number' || typeof obj == 'boolean'){
element += ('<p class="oeusn0eui0HTDRh98oeui" style="color: white; padding:2px;margin:2px; background-color: orange;"><span style="visibility:hidden">' + spaceAdd + '</span>' + preKey + escapeHtml(String(obj)) + '</p>');
}else{
var end = ('<p style="color: white; padding:2px;margin:2px;"><span style="visibility:hidden">' + spaceAdd + '</span>' + ')</p></div>');
element += ('<div id="oestniSTHSseti897e_' + depth + '" class="oseu098oaeuno7e089" style="color: white; padding:2px;margin:2px; height: 15px; overflow:hidden; cursor: pointer; background-color: ' + window.uonteuho8o6e8ued68uou8Color[depth%6] + '"><span style="visibility:hidden">' + spaceAdd + '</span>' + preKey + Object.prototype.toString.call( obj ) + '(<br>');
if(Object.prototype.toString.call( obj ) == '[object Function]'){
element += ('<p class="oeusn0eui0HTDRh98oeui" style="color: white; padding:2px;margin:2px; background-color: orange;"><span style="visibility:hidden">' + spaceAdd + '___' + '</span>' + escapeHtml(String(obj)) + '</p>');
}
if(depth < 10){ // this is because I fudge up the script with "too much recursion" on big objects. I'm in the middle of solving this, hence the redundant properties
for(var key in obj){
element += htmlConsole({NTDNTH8oe8uidu98NT: obj[key], sNDGHBn788rnFI9: spaceAdd, sntuhinegdukx0euetkhe989: key,netnuxie0xbenuihtdNT09: depth,sjtnhxsSTHxsnheu9isTH: index}).element;
}
}else{
element += end;
return {element: element, obj:obj};
}
element += end;
}
}
return {element: element};
}
$.bronsole = function(obj){
$('#eoenuitn345n34ntdhiu45dnth').prepend(htmlConsole(obj).element);
};
$.fn.bronsole = function(text){
var _this = this;
if(typeof text != 'undefined'){
$('#eoenuitn345n34ntdhiu45dnth').prepend(htmlConsole(text).element);
}
$('#eoenuitn345n34ntdhiu45dnth').prepend(htmlConsole(_this).element);
return this;
};
}( jQuery ));

Related

How can I add a bubble chat icon on my website?

I'm having trouble customizing this code to have a bubble chat icon that stays within my website when I scroll down. Anyone with an idea of how I can improve it?
Here is my code so far:
<!-- Add this script tag without any modification to the target webpage -->
<script type="application/javascript">
var ciscoBubbleChat = (function() {
var smHost = 'socialminer.uonbi.ac.ke';
var widgetId = '1';
var msgMustAcceptCert = 'Certificate must be accepted to start the conversation.';
var msgAcceptCertButtonLabel = 'Accept Certificate';
var msgCloseButtonLabel = 'Close';
var msgWaitingCertAcceptance = 'Waiting for certificate acceptance.';
var msgConnectivityIssues = 'We are experiencing connectivity issues. Try later.';
var appId = 'cisco_bubble_chat';
var appMargin = 15;
var appUrl = 'https://' + smHost + '/ccp/ui/BubbleChat.html?host=' + smHost + '&wid=' + widgetId;
var connectivityCheckUrl = 'https://' + smHost + '/ccp/ui/ConnectivityCheck.html';
var messageEventListener;
var addNoCacheQueryParam;
return {
showChatWindow: function(injectedData) {
var logPrefix = 'CISCO_BUBBLE_CHAT: ';
if (document.getElementById(appId)) {
console.log(logPrefix + 'Not loading BubbleChat as it is already loaded');
return;
}
var validateInjectedData = function(formData) {
// browser compatible way to check whether it is an object with 10 fields and all the values are strings
var result = true;
if (formData && typeof formData === 'object' && formData.constructor === Object) {
var counter = 0;
for (var key in formData) {
if (!(typeof formData[key] === 'string' || formData[key] instanceof String)) {
result = false;
break;
}
counter++;
if (counter > 10) {
result = false;
break;
}
}
} else {
result = false;
}
return result;
};
if (injectedData) {
if (validateInjectedData(injectedData.formData)) {
appUrl += '&injectedFormData=' + encodeURIComponent(JSON.stringify(injectedData.formData));
} else {
if (typeof injectedData.validationErrorCallback === 'function') {
injectedData.validationErrorCallback();
} else {
console.log(logPrefix + 'Could not invoke validationErrorCallback as it is not a function');
}
}
}
var iframe = document.createElement('iframe');
iframe.setAttribute('sandbox', 'allow-scripts allow-same-origin allow-forms allow-popups');
iframe.setAttribute('id', appId);
iframe.setAttribute('style', 'position: fixed; width: 312px; height: 410px; border: none; bottom: 0px; right: 0; z-index:999;');
document.body.appendChild(iframe);
var frameWindow = iframe.contentWindow ? iframe.contentWindow : iframe;
var frameDoc = frameWindow.document;
// Trigger a page load for iframe inline content loading to work in Firefox
frameDoc.open();
frameDoc.close();
frameDoc.body.innerHTML = '<div id="secure-connectivity-check-container" style="position: fixed; width: 300px; height: 395px; ' +
'bottom: 10px; right: 10px; font-family: Helvetica; font-size: 14px; color: #4F5051;' +
'box-shadow: 0 0 3px #000; background: #fff; display: flex; flex-direction: column; display: none;">' +
'<div style="height: 25%;"></div>' +
'<div style="height: 25%; display: flex; align-items: flex-start; justify-content: center; text-align: center;">' +
'<div style="padding: 0 15% 0 15%;">' +
'<div id="secure-connectivity-check-msg"></div>' +
'<a id="accept-cert-button" style="display:none; padding-top: 10px" href="#" onclick="acceptCertificate(); return void(0);">' +
msgAcceptCertButtonLabel +
'</a>' +
'</div>' +
'</div>' +
'<div style="height: 25%; display: flex; align-items: flex-end; justify-content: center; text-align: center;">' +
'<div style="padding: 0 15% 0 15%;">' +
'<a href="#" onclick="window.parent.postMessage({messageType: \'unmount\'}, \'*\'); return void(0);">' +
msgCloseButtonLabel +
'</a>' +
'</div>' +
'</div>' +
'<div style="height: 25%;"></div>' +
'</div>';
frameWindow.acceptCertificate = function() {
frameDoc.getElementById('secure-connectivity-check-msg').innerHTML = msgWaitingCertAcceptance;
frameDoc.getElementById('accept-cert-button').style.display = 'none';
window.open(addNoCacheQueryParam(connectivityCheckUrl), 'SM_CERT_PAGE');
};
if (!addNoCacheQueryParam) {
addNoCacheQueryParam = function(url) {
return url + (url.indexOf("?") === -1 ? '?' : '&') + 'nocache=' + new Date().getTime();
}
}
if (!messageEventListener) {
messageEventListener = function(event) {
console.log(logPrefix + 'Received event from origin: ' + event.origin);
console.log(logPrefix + 'Received event data: ' + JSON.stringify(event.data));
switch (event.data.messageType) {
case 'resize':
document.getElementById(appId).style.height = event.data.height + appMargin + 'px';
console.log(logPrefix + 'Successfully resized');
break;
case 'unmount':
document.body.removeChild(document.getElementById(appId));
window.removeEventListener('message', messageEventListener);
console.log(logPrefix + 'Successfully unmounted BubbleChat and removed event listener for message');
break;
case 'bubblechat-cert-accepted':
document.getElementById(appId).setAttribute('src', addNoCacheQueryParam(appUrl));
console.log(logPrefix + 'Successfully validated certificate acceptance and loaded BubbleChat');
break;
default:
console.log(logPrefix + 'Unknown message type');
}
};
}
window.addEventListener('message', messageEventListener);
console.log(logPrefix + 'Event listener for message added');
// Check HTTPS connectivity and show appropriate screen
var showConnectivityIssue = function(message, showAcceptCertLink) {
window.postMessage({
messageType: 'resize',
height: 395
}, '*');
frameDoc.getElementById('secure-connectivity-check-container').style.display = 'block';
frameDoc.getElementById('secure-connectivity-check-msg').innerHTML = message;
frameDoc.getElementById('accept-cert-button').style.display = showAcceptCertLink ? 'block' : 'none';
};
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState === 4) {
console.log(logPrefix + 'Connectivity check status: ' + this.status);
switch (this.status) {
case 200:
iframe.setAttribute('src', addNoCacheQueryParam(appUrl));
break;
case 0:
showConnectivityIssue(msgMustAcceptCert, true);
break;
default:
showConnectivityIssue(msgConnectivityIssues, false);
}
}
};
console.log(logPrefix + 'Checking connectivity to: ' + connectivityCheckUrl);
xhr.open('GET', addNoCacheQueryParam(connectivityCheckUrl), true);
xhr.send();
}
};
})();
</script>
<!--
Use the function 'ciscoBubbleChat.showChatWindow() as the event handler for initiating chat.
eg: <button onclick="ciscoBubbleChat.showChatWindow()">Start Chat</button>
Optionally, invisible form data can be submitted, which will be submitted along with the fields customer fills in.
Upto 10 fields can be passed. If more than 10 fields are passed, the invisible form data will not be used and
the provided error callback will be invoked. For injecting form data, an object should be passed to
ciscoBubbleChat.showChatWindow() as an argument. The object should be of the form:
{
formData: {
InjectedField1: 'InjectedValue1',
InjectedField2: 'InjectedValue2'
...
},
validationErrorCallback: function(){console.log('business specific logic goes here');}
}
The form data can have any string as field name and value. The submitted invisible form data values will be
shown in the agent desktop, as well as will be updated in ContextService if the specified fieldset(s) in the widget
contains these field names just like the regular visible chat form fields data.
eg:
<button onclick="ciscoBubbleChat.showChatWindow({
formData: {
AnyFieldName1: 'AnyFieldValue1',
AnyFieldName2: 'AnyFieldValue2',
AnyFieldName3: 'AnyFieldValue3',
AnyFieldName4: 'AnyFieldValue4',
AnyFieldName5: 'AnyFieldValue5',
AnyFieldName6: 'AnyFieldValue6',
AnyFieldName7: 'AnyFieldValue7',
AnyFieldName8: 'AnyFieldValue8',
AnyFieldName9: 'AnyFieldValue9',
AnyFieldName10: 'AnyFieldValue10'
},
validationErrorCallback: function(){console.log('error in validating injected data');}
})">Click to chat</button>
-->
<html>
<body>
<button class onclick="ciscoBubbleChat.showChatWindow()">Start Chat</button>
</body>
</html>
I want to customize it so that it can have a better look, and find a way to keep it within my website. Does anyone have any ideas?
The best solution would be to add position: fixed; on the button, for example: <button style="position: fixed; bottom: 0; right: 0;" onclick="ciscoBubbleChat.showChatWindow()">Start Chat</button> That would force the button to stay on the lower right side of screen at all times. And for the icon, just add an <img> tag.
Demo:
.chatBtn {
position: fixed;
bottom: 20px;
right: 20px;
z-index: 2;
}
.chatBtn img {
width: 40px; /* Change this to what you want. */
height: 40px; /* Change this to what you want. */
}
<button class="chatBtn" onclick="ciscoBubbleChat.showChatWindow()"><img src="https://icon-library.com/images/talk-bubble-icon-png/talk-bubble-icon-png-2.jpg"> <!-- You can put your own image here. -->
</button>
<!-- Add this script tag without any modification to the target webpage -->
<script type="application/javascript">
var ciscoBubbleChat = (function () {
var smHost = 'socialminer.uonbi.ac.ke';
var widgetId = '1';
var msgMustAcceptCert = 'Certificate must be accepted to start the conversation.';
var msgAcceptCertButtonLabel = 'Accept Certificate';
var msgCloseButtonLabel = 'Close';
var msgWaitingCertAcceptance = 'Waiting for certificate acceptance.';
var msgConnectivityIssues = 'We are experiencing connectivity issues. Try later.';
var appId = 'cisco_bubble_chat';
var appMargin = 15;
var appUrl = 'https://' + smHost + '/ccp/ui/BubbleChat.html?host=' + smHost + '&wid=' + widgetId;
var connectivityCheckUrl = 'https://' + smHost + '/ccp/ui/ConnectivityCheck.html';
var messageEventListener;
var addNoCacheQueryParam;
return {
showChatWindow: function (injectedData) {
var logPrefix = 'CISCO_BUBBLE_CHAT: ';
if (document.getElementById(appId)) {
console.log(logPrefix + 'Not loading BubbleChat as it is already loaded');
return;
}
var validateInjectedData = function(formData) {
// browser compatible way to check whether it is an object with 10 fields and all the values are strings
var result = true;
if (formData && typeof formData === 'object' && formData.constructor === Object){
var counter = 0;
for (var key in formData) {
if (!(typeof formData[key] === 'string' || formData[key] instanceof String)) {
result = false;
break;
}
counter++;
if (counter > 10) {
result = false;
break;
}
}
} else {
result = false;
}
return result;
};
if (injectedData) {
if (validateInjectedData(injectedData.formData)) {
appUrl += '&injectedFormData=' + encodeURIComponent(JSON.stringify(injectedData.formData));
} else {
if (typeof injectedData.validationErrorCallback === 'function') {
injectedData.validationErrorCallback();
} else {
console.log(logPrefix + 'Could not invoke validationErrorCallback as it is not a function');
}
}
}
var iframe = document.createElement('iframe');
iframe.setAttribute('sandbox', 'allow-scripts allow-same-origin allow-forms allow-popups');
iframe.setAttribute('id', appId);
iframe.setAttribute('style', 'position: fixed; width: 312px; height: 410px; border: none; bottom: 0px; right: 0; z-index:999;');
document.body.appendChild(iframe);
var frameWindow = iframe.contentWindow ? iframe.contentWindow : iframe;
var frameDoc = frameWindow.document;
// Trigger a page load for iframe inline content loading to work in Firefox
frameDoc.open();
frameDoc.close();
frameDoc.body.innerHTML = '<div id="secure-connectivity-check-container" style="position: fixed; width: 300px; height: 395px; ' +
'bottom: 10px; right: 10px; font-family: Helvetica; font-size: 14px; color: #4F5051;' +
'box-shadow: 0 0 3px #000; background: #fff; display: flex; flex-direction: column; display: none;">' +
'<div style="height: 25%;"></div>' +
'<div style="height: 25%; display: flex; align-items: flex-start; justify-content: center; text-align: center;">' +
'<div style="padding: 0 15% 0 15%;">' +
'<div id="secure-connectivity-check-msg"></div>' +
'<a id="accept-cert-button" style="display:none; padding-top: 10px" href="#" onclick="acceptCertificate(); return void(0);">' +
msgAcceptCertButtonLabel +
'</a>' +
'</div>' +
'</div>' +
'<div style="height: 25%; display: flex; align-items: flex-end; justify-content: center; text-align: center;">' +
'<div style="padding: 0 15% 0 15%;">' +
'<a href="#" onclick="window.parent.postMessage({messageType: \'unmount\'}, \'*\'); return void(0);">' +
msgCloseButtonLabel +
'</a>' +
'</div>' +
'</div>' +
'<div style="height: 25%;"></div>' +
'</div>';
frameWindow.acceptCertificate = function () {
frameDoc.getElementById('secure-connectivity-check-msg').innerHTML = msgWaitingCertAcceptance;
frameDoc.getElementById('accept-cert-button').style.display = 'none';
window.open(addNoCacheQueryParam(connectivityCheckUrl), 'SM_CERT_PAGE');
};
if (!addNoCacheQueryParam){
addNoCacheQueryParam = function (url) {
return url + (url.indexOf("?") === -1 ? '?' : '&') + 'nocache=' + new Date().getTime();
}
}
if (!messageEventListener) {
messageEventListener = function (event) {
console.log(logPrefix + 'Received event from origin: ' + event.origin);
console.log(logPrefix + 'Received event data: ' + JSON.stringify(event.data));
switch (event.data.messageType) {
case 'resize':
document.getElementById(appId).style.height = event.data.height + appMargin + 'px';
console.log(logPrefix + 'Successfully resized');
break;
case 'unmount':
document.body.removeChild(document.getElementById(appId));
window.removeEventListener('message', messageEventListener);
console.log(logPrefix + 'Successfully unmounted BubbleChat and removed event listener for message');
break;
case 'bubblechat-cert-accepted':
document.getElementById(appId).setAttribute('src', addNoCacheQueryParam(appUrl));
console.log(logPrefix + 'Successfully validated certificate acceptance and loaded BubbleChat');
break;
default:
console.log(logPrefix + 'Unknown message type');
}
};
}
window.addEventListener('message', messageEventListener);
console.log(logPrefix + 'Event listener for message added');
// Check HTTPS connectivity and show appropriate screen
var showConnectivityIssue = function (message, showAcceptCertLink) {
window.postMessage({ messageType: 'resize', height: 395 }, '*');
frameDoc.getElementById('secure-connectivity-check-container').style.display = 'block';
frameDoc.getElementById('secure-connectivity-check-msg').innerHTML = message;
frameDoc.getElementById('accept-cert-button').style.display = showAcceptCertLink ? 'block' : 'none';
};
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (this.readyState === 4) {
console.log(logPrefix + 'Connectivity check status: ' + this.status);
switch (this.status) {
case 200:
iframe.setAttribute('src', addNoCacheQueryParam(appUrl));
break;
case 0:
showConnectivityIssue(msgMustAcceptCert, true);
break;
default:
showConnectivityIssue(msgConnectivityIssues, false);
}
}
};
console.log(logPrefix + 'Checking connectivity to: ' + connectivityCheckUrl);
xhr.open('GET', addNoCacheQueryParam(connectivityCheckUrl), true);
xhr.send();
}
};
})();
</script>
<!--
Use the function 'ciscoBubbleChat.showChatWindow() as the event handler for initiating chat.
eg: <button onclick="ciscoBubbleChat.showChatWindow()">Start Chat</button>
Optionally, invisible form data can be submitted, which will be submitted along with the fields customer fills in.
Upto 10 fields can be passed. If more than 10 fields are passed, the invisible form data will not be used and
the provided error callback will be invoked. For injecting form data, an object should be passed to
ciscoBubbleChat.showChatWindow() as an argument. The object should be of the form:
{
formData: {
InjectedField1: 'InjectedValue1',
InjectedField2: 'InjectedValue2'
...
},
validationErrorCallback: function(){console.log('business specific logic goes here');}
}
The form data can have any string as field name and value. The submitted invisible form data values will be
shown in the agent desktop, as well as will be updated in ContextService if the specified fieldset(s) in the widget
contains these field names just like the regular visible chat form fields data.
eg:
<button onclick="ciscoBubbleChat.showChatWindow({
formData: {
AnyFieldName1: 'AnyFieldValue1',
AnyFieldName2: 'AnyFieldValue2',
AnyFieldName3: 'AnyFieldValue3',
AnyFieldName4: 'AnyFieldValue4',
AnyFieldName5: 'AnyFieldValue5',
AnyFieldName6: 'AnyFieldValue6',
AnyFieldName7: 'AnyFieldValue7',
AnyFieldName8: 'AnyFieldValue8',
AnyFieldName9: 'AnyFieldValue9',
AnyFieldName10: 'AnyFieldValue10'
},
validationErrorCallback: function(){console.log('error in validating injected data');}
})">Click to chat</button>
-->
EDIT:
A chat bubble icon has been added.

Tweak code to expand web parts in Sharepoint

I'm trying to tweak some code I found online to create an expand button beside a web part in a Sharepoint site. The issue with this code is that the default is that all web parts are already expanded, and you would have to click to collapse it. I would only like to have my FAQ (WebPartWPQ7) web part already collapsed, and users can expand it with a click. The other web parts do not need an expand/collapse button.
<script type="text/javascript">
//
// Expand/Collapse Buttons
//
function WPToggle(thisId, ImageId) {
if (document.getElementById(thisId).style.display == "none") {
document.getElementById(thisId).style.display = "";
document.getElementById(ImageId).src = "/_layouts/images/minus.gif";
} else {
document.getElementById(thisId).style.display = "none";
document.getElementById(ImageId).src = "/_layouts/images/plus.gif";
}
}
function ExpandCollapseBody() {
var i = 1;
var WPid = "WebPartWPQ1";
var WPtitleid = "WebPartTitleWPQ1";
var Toggleid = "ToggleImage1";
do {
try {
document.getElementById(WPtitleid).innerHTML = '<IMG id="' + Toggleid + '" onClick="WPToggle(\'' + WPid + '\',\'' + Toggleid + '\')" alt="Expand/Collapse" style="margin:6px 5px 0px 2px; float:left; cursor:pointer;" src="/_layouts/images/minus.gif" />' + document.getElementById(WPtitleid).innerHTML;
if (document.getElementById(WPid).style.display == "none") {
document.getElementById(Toggleid).src = "/_layouts/images/plus.gif";
}
} catch (err) {}
i = i + 1;
WPid = "WebPartWPQ" + i;
WPtitleid = "WebPartTitleWPQ" + i;
Toggleid = "ToggleImage" + i;
} while (document.getElementById(WPid))
}
_spBodyOnLoadFunctionNames.push("ExpandCollapseBody()");
</script>
If you would like to hide the 7th web part, just add a if (i == 7) WPToggle(WPid, ToggleId); to the initialization function. Slightly adapted your code with jquery as you tagged your question as such I assume you can use it:
function WPToggle(thisId, ImageId) {
var isVisible = $('#' + thisId).is(':visible');
$('#' + thisId).toggle(!isVisible);
var img = isVisible ? 'plus' : 'minus';
$('#' + ImageId).attr('src', '/_layouts/images/' + img + '.gif');
}
function ExpandCollapseBody() {
var i = 1;
do {
var WPid = 'WebPartWPQ' + i;
var WPtitleid = 'WebPartTitleWPQ' + i;
var Toggleid = 'ToggleImage' + i;
var htmlImg = '<img id="' + Toggleid + '" alt="Expand/Collapse" style="margin:6px 5px 0px 2px; float:left; cursor:pointer;" src="/_layouts/images/minus.gif" />';
var wpTitle = $('#' + WPtitleid).data('idx', i);
wpTitle
.html(htmlImg + wpTitle.html())
.click(function() {
var idx = $(this).data('idx');
WPToggle('WebPartWPQ' + idx, 'ToggleImage' + idx);
});
if (i == 7) WPToggle(WPid, Toggleid);
i++;
} while ($('#WebPartWPQ' + i).length == 1)
}
_spBodyOnLoadFunctionNames.push("ExpandCollapseBody()");

JSON parsing response slowly

https://jsfiddle.net/jeeyi345/uchhjz7L/3/
I want to connect a JSP web service I built and return parsed elements, as follows, but the result return slowly.
When I parsed only 1 element the page response a lot faster, but I don't know why when I parsed them all, maybe like a few minutes or longer.
There is only a line of JSON array from the JSP page, like the following:
[{"UID":11,"UrlDate":"2016-10-24","UrlTime":"15:00:00","Drug":2,"AttLevel":43.2864439246683,"AttLevel_Lab":"普通","Allpoint":5,"PVTRuleBase":2,"MemLevel":87}]
Is there something wrong with my code? Thanks in adavance.
// https://jsfiddle.net/vobmzdgr/7/
function json_decode(json) {
return $.parseJSON(json);
}
function json_format(json) {
return JSON.stringify(json_decode(json), null, 2);
}
function json_highlight(json) {
/*
pre {outline: 1px solid #ccc; padding: 5px; margin: 5px; }
.string { color: green; }
.number { color: darkorange; }
.boolean { color: blue; }
.null { color: magenta; }
.key { color: red; }
*/
if (typeof json != 'string') {
json = JSON.stringify(json, undefined, 2);
}
json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function(match) {
var cls = 'number';
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = 'color: red;'; //key
} else {
cls = 'color: green;'; //string
}
} else if (/true|false/.test(match)) {
cls = 'color: blue;'; //boolean
} else if (/null/.test(match)) {
cls = 'color: magenta;'; //null
}
return '<span style="' + cls + '">' + match + '</span>';
});
}
function json_AttLevel(json) {
var obj = json_decode(json);
return obj[0].AttLevel;
}
function json_AttLevel_Lab(json) {
var obj = json_decode(json);
return obj[0].AttLevel_Lab;
}
function json_PVTRuleBase(json) {
var obj = json_decode(json);
return obj[0].PVTRuleBase;
}
function json_Drug(json) {
var obj = json_decode(json);
return obj[0].Drug;
}
function json_Allpoint(json) {
var obj = json_decode(json);
return obj[0].Allpoint;
}
$(document).ready(function() {
// var URL="http://140.138.77.151:8080/personalAssementNEW";
var URL = "http://140.138.77.151:8080/FallRiskAPI/getInputData.jsp?ID=11&DATEINFO=2016-10-24&TIMEINFO=15:00:00";
$.ajaxPrefilter(function(options) {
if (options.crossDomain && jQuery.support.cors) {
var http = (window.location.protocol === 'http:' ? 'http:' : 'https:');
options.url = http + '//cors-anywhere.herokuapp.com/' + options.url;
}
});
setInterval(function() {
$.get(URL, function(response) {
//原內容
$("#output").text(response);
var bodydata = response;
bodydata = $("<p>" + bodydata + "</p>").text();
var jdata = json_format(bodydata);
$("#output_data").html("<pre>" + json_highlight(jdata) + "</pre>");
$("#output_AttLevel").html("<pre>" + json_AttLevel(jdata) + "</pre>");
$("#output_AttLevel_Lab").html("<pre>" + json_AttLevel_Lab(jdata) + "</pre>");
$("#output_PVTRuleBase").html("<pre>" + json_PVTRuleBase(jdata) + "</pre>");
$("#output_Drug").html("<pre>" + json_Drug(jdata) + "</pre>");
$("#output_Allpoint").html("<pre>" + json_Allpoint(jdata) + "</pre>");
});
// alert("reloaded");
}, 1500);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- https://jsfiddle.net/vobmzdgr/7/ -->
<script language="javascript" src="http://3wa.tw/inc/javascript/jquery/jquery-1.11.3.min.js"></script>
收到的內容:<br>
<div id="output"></div>
<hr>
解算的內容:<br>
<div id="output_data"></div>
專注力等級:<div id="output_AttLevel_Lab"></div>
專注力測驗等級:<div id="output_PVTRuleBase"></div>
用藥分數:<div id="output_Drug"></div>
整體分數:<div id="output_Allpoint"></div>

How to add loading bar in Jquery autocomplete span tag?

In this coding I showed progress bar on the text box. but i need loading indicator in span tag when searching for something. I added two images to better understand about it. please answer me the question.
this is flat progress in text box:
but i need the progress on span
CSS:
<style type="text/css">
.loader
{
background: url(resources/images/loader.gif);
background-repeat: no-repeat;
background-position: right;
}
</style>
JS:
try {
console.log('connections url ' , urlHolder.getconnectedusersByName);
$("#auto-complete-tag").autocomplete({
source: function(request, respond) {
$("#auto-complete-tag").addClass('loader');
var givenUserName = $("#auto-complete-tag").val();
$.post(urlHolder.getconnectedusersByName, {
userId : signedUserId,
username : givenUserName
}, function(response) {
$('#auto-complete-tag').removeClass('loader');
if(!response){
respond([]);
length = 0;
}
this.connectionsList = new Array();
for (var counter = 0; counter < response.users.length; counter++) {
var getConnectedUsers = new Object();
getConnectedUsers = {
value : response.users[counter].name,
//profileId : "onclick=return false",
image : response.users[counter].defaultImageFileName,
id:response.users[counter].id
}
this.connectionsList.push(getConnectedUsers);
}
respond (this.connectionsList);
});
},
delay: 0 ,
search: function (e, u) {
},
select : function(event, ui) {
return false;
},
response: function(event, ui) {
length = ui.content.length;
console.log('length',length );
if(length === 0) {
var noResult = {label:"No results found for you" };
ui.content.push(noResult);
}
},
}) .data('ui-autocomplete')._renderItem = function(ul, item) {
if(length !== 0){
return $('<li>')
.data( "ui-autocomplete-item", item)
.append(
'<a style="background-color: #E0F0EF; color:#0d78a3; margin-bottom: 3px; margin-top: 3px; margin-left: 3px; margin-right: 3px; font-weight: bold;">' +
'<span style="color:#86BBC9; font-weight: normal;">' +
item.label + '</span>' + '<br>'+'<span>Text message</span>'+
'<button style="margin-bottom:14px; margin-right:5px;" class=\"yellow-btn apply-btn\" id=\"apply-user-' + item.id + '\" onclick=\"openDFAChatWithUser(\'' + item.id + '\')\">Chat</button>'
+ '<span class="ui-autocomplete-icon pull-right"></span>' +
'</a>'
)
.appendTo(ul);}else{
return $('<li>')
.data( "ui-autocomplete-item", item)
.append('<a>' +
'<span class="ui-autocomplete-user">' +
item.label + '</span>' +
'<span class="ui-autocomplete-divider"></span>' +
'<span class="ui-autocomplete-icon pull-right"></span>' +
'</a>')
.appendTo(ul);
}
};
//console.log(' this.connectionsList >>> ', this.connectionsList);
} catch (e) {
console.log('getAllConnections error >>> ', e);
}

Issue editing class style properties using js - issue is with IE

I have a function to edit the style properties of a class
Unfortunately IE does not seem to like it but it does not give me an error.
Does anyone know what the issue is?
Thanks in advance
function myRemoveElement(id) {
var Node = document.getElementById(id);
Node.parentNode.removeChild(Node);
}
function boolyChangeFoo(width1, width2, width3, width4) {
if(typeof style == 'undefined') {
var append = true;
myStyle = document.createElement('style');
} else {
while (myStyle.hasChildNodes()) {
myStyle.removeChild(myStyle.firstChild);
}
}
if (document.getElementById('my_custom_styles'))
{
myRemoveElement('my_custom_styles');
}
var head = document.getElementById('myltd_popup_1');
var rules = document.createTextNode('.my_price_comp_inner { width: ' + width1 + '}' +
'.merch_coupons_summary { width: ' + width2 + '}' +
'.merch_coupons_data { width: ' + width3 + '}' +
'.my_coupon_prod_item { width: ' + width4 + '}'
);
myStyle.setAttribute('type','text/css');
myStyle.setAttribute('id', 'my_custom_styles');
if(myStyle.styleSheet) {
myStyle.styleSheet.cssText = rules.nodeValue;
} else {
myStyle.appendChild(rules);
}
//alert(myStyle);
if(append === true) head.appendChild(myStyle);
}
#Pointy - I didn't really need the top part
function myRemoveElement(id) {
var Node = document.getElementById(id);
Node.parentNode.removeChild(Node);
}
function boolyChangeFoo(width1, width2, width3, width4) {
var append = true;
myStyle = document.createElement('style');
if (document.getElementById('my_custom_styles'))
{
myRemoveElement('my_custom_styles');
}
var head = document.getElementById('myltd_popup_1');
var rules = document.createTextNode('.my_price_comp_inner { width: ' + width1 + '}' +
'.merch_coupons_summary { width: ' + width2 + '}' +
'.merch_coupons_data { width: ' + width3 + '}' +
'.my_coupon_prod_item { width: ' + width4 + '}'
);
myStyle.setAttribute('type','text/css');
myStyle.setAttribute('id', 'my_custom_styles');
if(myStyle.styleSheet) {
myStyle.styleSheet.cssText = rules.nodeValue;
} else {
myStyle.appendChild(rules);
}
//alert(myStyle);
if(append === true) head.appendChild(myStyle);
}

Categories

Resources