auto resize div after ajax content call completes - javascript

I have an api call that grabs data just fine. Its setup to use a button to open up a collapsible div. If you have it open already, you'll see the first line or 2 come up once the data is fetched, and you have to close/reopen the div to see all the data. been stuck on this for a bit, tried a bunch of stuff already. heres the JS
$(document).ready(function() {
function myFunction(val) {}
var coll = document.getElementsByClassName("collapsible");
var i;
for (i = 0; i < coll.length; i++) {
coll[i].addEventListener("click", function() {
this.classList.toggle("active");
var hidden_content = this.nextElementSibling;
if (hidden_content.style.maxHeight) {
hidden_content.style.maxHeight = null;
} else {
hidden_content.style.maxHeight = hidden_content.scrollHeight + "px";
}
});
}
document.getElementById('collapsible').click();
$.ajax({
type:"GET",
url:"pages/splunk_bf_data",
dataType:"json",
success:function(data){
var html = '<p>' + data + '</p>'
$('.data-container').html(html);
}
})})

cheezed it with clicking it twice through an after completion function.
if there is a better/more legit way of doing this, please post it..I prefer best practices.
but heres what i did
$(document).ready(function() {
function myFunction(val) {}
var coll = document.getElementsByClassName("collapsible");
var i;
for (i = 0; i < coll.length; i++) {
coll[i].addEventListener("click", function() {
this.classList.toggle("active");
var hidden_content = this.nextElementSibling;
if (hidden_content.style.maxHeight) {
hidden_content.style.maxHeight = null;
} else {
hidden_content.style.maxHeight = hidden_content.scrollHeight + "px";
}
});
}
function changeSizeByClicking() {
document.getElementById('collapsible2').click();
document.getElementById('collapsible2').click();
}
document.getElementById('collapsible').click();
$.ajax({
type:"GET",
url:"pages/splunk_bf_data",
dataType:"json",
beforeSend:function(){
var html = '<p>' + 'Fetching data from Splunk..' + '<br>' + 'please wait...'+ '</p>'
$('.data-container').html(html);
},
success:function(data){
var html = '<p>' + data + '</p>'
$('.data-container').html(html);
},
complete:function(data){
changeSizeByClicking();
}
})})

Related

Image source shows up as undefined in IE but works in Chrome

I am trying to display several images(PrinurlonPage) that are contained in an array and also position them on the page randomly. I have two issues,
The first and most important is that I cant get the images to display on IE when I look the source attribute on developer tools I just see undefined whereas in chrome I get the full URL that was passed. I was wondering if there was something wrong with the order in which the script was being run that was causing the problem.
The second question is about positioning the images randomly on the page and also prevent overlapping, I would like to know how can I achieve this, what I have implemented at the moment in some iterations the pictures overlap.
I would appreciate any suggestion on this
var getIndividualPersonDetails = function(GetPictureUrl, printurlonPage, getRandom) {
listName = 'TeamInfo';
var PeopleCompleteList = [];
var personName, userName, UserTitle, UserphoneNumber, UserEmail, Id, myuserPicture;
// execute AJAX request
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items?$select=Name/Title,Name/Name,Name/Id,Name/EMail,Name/WorkPhone&$expand=Name/Id",
type: "GET",
headers: {
"ACCEPT": "application/json;odata=verbose"
},
success: function(data) {
for (i = 0; i < data.d.results.length; i++) {
//check if the user exists if he does store the following properties name,title,workphone,email and picture url
if (data.d.results[i]['Name'] != null) {
personName = data.d.results[i]['Name'].Name.split('|')[2];
userName = data.d.results[i]['Name']['Name'];
UserTitle = data.d.results[i]['Name']['Title'];
UserphoneNumber = data.d.results[i]['Name']['WorkPhone'];
UserEmail = data.d.results[i]['Name']['EMail'];
Id = data.d.results[i]['Name']['Id'];
myuserPicture = GetPictureUrl(userName);
PeopleCompleteList.push(PersonConstructor(personName, UserTitle, UserphoneNumber, UserEmail, myuserPicture, Id));
}
}
PeopleObject = PeopleCompleteList;
PrinturlonPage(PeopleCompleteList, getRandom);
},
error: function() {
alert("Failed to get details");
}
});
}
//print all the image links in the peopleCompleteList array and then position them randomly on the page
var PrinturlonPage = function(PeopleCompleteList, getRandom) {
var imageList = [];
for (i = 0; i < PeopleCompleteList.length; i++) {
var top = getRandom(0, 400);
var left = getRandom(0, 400);
var right = getRandom(0, 400);
imageList.push('<img style="top:' + top + ';right:' + right + '" id="image' + PeopleCompleteList[i]['UserId'] + '" alt="' + PeopleCompleteList[i]['Title'] + '"class="imgCircle" src="' + PeopleCompleteList[i]['Picture'] + '"/>');
//imageList +='<img class="img-circle" src="'+PeopleCompleteList[i]['Picture']+ '"/>'
}
var imagesString = imageList.join().replace(/,/g, "");
$('#imageList').append(imagesString);
}
//funtion retrieves the picture
function GetPictureUrl(user) {
var userPicture="";
var imageurls="";
var requestUri = _spPageContextInfo.webAbsoluteUrl +
"/_api/SP.UserProfiles.PeopleManager/GetPropertiesFor(accountName=#v)?#v='"+encodeURIComponent(user)+"'";
$.ajax({
url: requestUri,
type: "GET",
async:false,
headers: { "ACCEPT": "application/json;odata=verbose" },
success: function (data) {
console.log(data);
var loginName = data.d.AccountName.split('|')[2];
console.log(loginName);
var PictureDetails = data.d.PictureUrl != null ? data.d.PictureUrl : 'https://xxxcompany/User%20Photos/Profile%20Pictures/zac_MThumb.jpg?t=63591736810';
imageurls = data.d.PersonalSiteHostUrl+'_layouts/15/userphoto.aspx?accountname='+ loginName+ '&size=M&url=' + data.d.PictureUrl;
userPicture1=imageurls;
}
});
return userPicture1;
}
var getRandom = function(x, y) {
return Math.floor(Math.random() * (y - x)) + x + 'px';
};
$(function() {
getIndividualPersonDetails(GetPictureUrl, PrinturlonPage, getRandom);
$(document).on('click', '.imgCircle', function() {
var theName = jQuery(this).attr('Id');
pullUserObject(theName);
//console.log(theId);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="imageList"></div>

Pulling a Usable Link out of a JSON Object

I need to figure out how to have a link that I pull from a JSON object an ACTUAL link that the user can click and follow to the site instead of just text. I feel like it's gotta be a quick fix, but I can't seem to figure it out! Thanks for the help!!
function sqoot(URL) {
$.ajax({
url: URL,
method: "GET"
}).done(function(response) {
var deals = response.deals
var untrackedURL = $("#untrackedURL");
var couponInfo = $("#info");
for (i = 0; i < deals.length; i++) {
var newUntrackedURL = $("<a href='deals[i].deal.untracked_url'>" + deals[i].deal.untracked_url + "</a>");
couponInfo.append(newUntrackedURL)
}
})
};
Assuming your fetched data is correctly used, here's why your link doesn't work : the href is actually deals[i].deal.untracked_url instead of its content.
try this instead :
function sqoot(URL) {
$.ajax({
url: URL,
method: "GET"
}).done(function (response) {
var deals = response.deals
var untrackedURL = $("#untrackedURL");
var couponInfo = $("#info");
for (i = 0; i < deals.length; i++) {
var newUntrackedURL = $('' + deals[i].deal.untracked_url + "");
couponInfo.append(newUntrackedURL)
}
})
};
Without the generated JSON, I can't help you further if this solution doesn't helps.
Look like maybe you had a typo:
'deals[i].deal.untracked_url' should be 'deals["+ i +"].deal.untracked_url'
function sqoot(URL) {
$.ajax({
url: URL,
method: "GET"
}).done(function (response) {
var deals = response.deals
var untrackedURL = $("#untrackedURL");
var couponInfo = $("#info");
for (i = 0; i < deals.length; i++) {
var newUntrackedURL = $("<a href='deals["+ i +"].deal.untracked_url'>" +
deals[i].deal.untracked_url + "</a>");
couponInfo.append(newUntrackedURL)
}
});
Scratch that - you want it to pull the value not write out "deals[i].deal.untracked_url." To do that you do the below.
function sqoot(URL) {
$.ajax({
url: URL,
method: "GET"
}).done(function (response) {
var deals = response.deals
var untrackedURL = $("#untrackedURL");
var couponInfo = $("#info");
for (i = 0; i < deals.length; i++) {
var newUntrackedURL = $("<a href='"+deals[i].deal.untracked_url+"'>" +
deals[i].deal.untracked_url + "</a>");
couponInfo.append(newUntrackedURL)
}
});

CSS to style javascript dynamically created table

I'm needing to style a table that's dynamically created by javascript. I know how to style it if it were just a static HTML table but this is different and I'm not too familiar with javascript. Here is the javascript code:
[var aryPortalList = \[\];
function getPortalList() {
var wP = window.location.protocol;
var wH = window.location.host;
var wPath = "ibi_apps/rs/ibfs/BIP/Portals?IBIRS_action=get";
//http://webfocusclidev:8080/ibi_apps/rs/ibfs/BIP/Portals?IBIRS_action=get;
var webfocusAPI = wP + "//" + wH + "/" + wPath;
$.ajax({
type: "GET",
async: false,
url: webfocusAPI,
dataType: 'xml',
success: function(xml) {
$(xml).find('children').children().each(function() {
var portal = { Name: $(this).attr('bipName'),
Link: "/ibi_apps/bip/portal" + $(this).attr('bipPath'),
IconLink: "/ibi_apps/WFServlet.ibfs?IBFS1_action=RUNFEX&IBFS_path=" + $(this).attr('bipIconPath')
}; //var portal
console.log("portal.name=" + portal.Name);
if (portal.Name != "GlobalBI") aryPortalList.push(portal);
}); //each
console.log("Portals in List = " + aryPortalList.length);
} //success function
}); //ajax
}
function displayPortalList_Icon() {
if (aryPortalList.length == 0) {
var hTxt = "<p>You do not have access to any portals</p>";
$("#portallist").append(hTxt);
} else {
var bRowAdded = false;
var hTbl=$("<table id='tbl_portallist'></table>");
var row = $('<tr></tr>').addClass('ingrPL_row');
console.log("Portals in List = " + aryPortalList.length);
for(var j=0; j < aryPortalList.length; j++) {
var cell = $("<td align = 'center'></td>");
var hTxt = $("<p>" + aryPortalList\[j\].Name + "</p>");
var hLink = $("<a>").attr({"href": aryPortalList\[j\].Link,
"target": "_blank"});
var img = $("<img>").attr("src", aryPortalList\[j\].IconLink);
img.width("100px");
img.height("100px");
console.log("hTxt=" + hTxt);
hLink.append(img);
cell.append(hTxt);
cell.append(hLink);
row.append(cell);
bRowAdded = false;
if ((j+1) % 4 == 0) {
hTbl.append(row);
bRowAdded = true;
var row = $('<tr></tr>').addClass('ingrPL_row');
}
}
if (!bRowAdded) {
hTbl.append(row);
}
$("#portallist").html(hTbl);
}
}
function displayPortalList_List() {
if (aryPortalList.length == 0) {
var hTxt = "<p>You do not have access to any portals</p>";
$("#portallist").append(hTxt);
} else {
var bRowAdded = false;
var hTbl=$("<table id='tbl_portallist'></table>");
console.log("Portals in List = " + aryPortalList.length);
for(var j=0; j < aryPortalList.length; j++) {
var row = $('<tr></tr>').addClass('ingrPL_row');
var cell = $("<td align = 'center'></td>");
var hTxt = $("<p>" + aryPortalList\[j\].Name + "</p>");
var hLink = $("<a>").attr({"href": aryPortalList\[j\].Link,
"target": "_blank"});
console.log("hTxt=" + hTxt);
hLink.append(hTxt);
cell.append(hLink);
row.append(cell);
hTbl.append(row);
}
$("#portallist").html(hTbl);
console.log("portal.name=" + portal.Name);
}
}][1]
And I've attached a photo of how the 'portal' looks.
What I need to do is space out the icons more and have the title's on the bottom of the icons, to look more like an 'iphone app'
Any help is greatly appreciated.
you can style it in the same way you style static elements
looking at your code I can see the table have an ID and the rows have classes
var hTbl=$("<table id='tbl_portallist'></table>");
var row = $('<tr></tr>').addClass('ingrPL_row');
so you can select those in your CSS file
CSS
#tbl_portallist {
/*table style here */
}
#tbl_portallist th {
/*table head style here*/
}
#tbl_portallist tr {
/*table row style here*/
}
#tbl_portallist td {
/*table data (cell) style here*/
}

How can I wait until all my images are loaded before adding them to html?

I am trying to get multiple images from an ajax source and load the on the page when they have all finished loading. The issue I was having that has caused me to try to find a solution was that some of the images weren't loading even though those images existed on the server.
I have tried to add code that now adds the image to an array
design_images.push({cid:designImg});
... and then when all the images have loaded will add that to the page, but I can't get that to work.
var counter = 0;
$(design_images).load(function() { // many or just one image(w) inside body or any other container
counter += 1;
}).each(function(key, value) {
this.complete && $(this).load();
console.log(value);
});
Nothing is outputted from the .each
This is the output of the array design_images
The value of design_images.length is 0 though.
Here is the complete function:
function matte_design_change_design_type(element)
{
var element_value = null;
var mattes_selected_type = get_mattes_selected_type();
matte_design_widths[mattes_selected_type] = [];
var mattes_selected_design = get_mattes_selected_design();
var count_matte_designs = 0;
var found = false;
$(document).ready(function()
{
$.ajax(
{
type: "GET",
url: SITE_URL + "/system/components/xml/" + mattes_selected_type,
dataType: 'xml',
success: function(xml)
{
var output = [];
var design_images = [];
$('component', xml).each(function(i, el)
{
matte_design_widths[mattes_selected_type][i] = 0;
count_matte_designs++;
var thumb = $("thumb", this).text(),
cid = $("cid", this).first().text(),
name = $("name", this).first().text().replace("Collage - ", ""),
alt = name,
description = $("description", this).first().text(),
if (parseInt(cid, 10) === mattes_selected_design)
{
found = true;
$("#matte_design_name").html(name);
$("#matte_design_description").html(description);
}
var designImg = new Image();
designImg.id = 'cid_' + cid;
designImg.alt = alt;
designImg.onclick = function() {
matte_design_change(cid, mattes_selected_type);
};
designImg.onload = function() {
output.push('<span class="matte_design_image_name" id="design_' + cid + '"><img id="cid_' + cid + '" />');
output.push('<br /><span class="matte_design_name" id="matte_design_name_' + mattes_selected_type + '_' + i + '">' + name + '</span></span>');
matte_design_increase_width(mattes_selected_type, this.width, i);
$('#matte_designs_strip_wrapper').html(output.join(''));
};
designImg.src = 'https://example.com/system/components/compimg/' + thumb + '/flashthumb';
});
var counter = 0;
var size = $('img').length;
$(design_images).load(function() {
counter += 1;
}).each(function(key, value) {
this.complete && $(this).load();
console.log(value);
});
}
});
});
}
I have tried waitForImages and imagesLoaded but I couldn't get them to work for me, but I'm not opposed to using either one.
Hide all images by default using CSS
img{
display: none;
}
Use Jquery to check if all loaded, then display images
JQuery
$(window).load(function(){
$('img').fadeIn(800); //or $('img').show('slow');
});

How do I scroll down a chatbox (div) automatically?

I've been working on a chat application and now I need to scroll automatically when a message appears.
I've tried different things but they do not work unfortunately.
So this is my main.js code:
var lastTimeID = 0;
$(document).ready(function() {
$('#btnSend').click( function() {
sendChatText();
$('#chatInput').val("");
});
startChat();
});
function startChat(){
setInterval( function() { getChatText(); }, 2000);
}
function getChatText() {
$.ajax({
type: "GET",
url: "/refresh.php?lastTimeID=" + lastTimeID
}).done( function( data )
{
var jsonData = JSON.parse(data);
var jsonLength = jsonData.results.length;
var html = "";
var message = $('#view_ajax');
for (var i = 0; i < jsonLength; i++) {
var result = jsonData.results[i];
html += '<div>(' + result.chattime + ') <b>' + result.usrname +'</b>: ' + result.chattext + '</div>';
lastTimeID = result.id;
}
$('#view_ajax').append(html);
message.html(data);
message.scrollTop(message[0].scrollHeight);
});
}
function sendChatText(){
var chatInput = $('#chatInput').val();
if(chatInput != ""){
$.ajax({
type: "GET",
url: "/submit.php?chattext=" + encodeURIComponent( chatInput )
});
}
}
I've used
var message = $('#view_ajax');
message.html(data);
message.scrollTop(message[0].scrollHeight);
I really have no clue how jQuery works. I've tried a couple of things before this but it didn't work also.
Do you have any suggestion? Any advice?
Do you need any more information? Feel free to ask!
Give each message an ID, as follows:
<div id="msg-1234">
Then you can scroll to this element using this jQuery:
$('html, body').animate({ scrollTop: $('#msg-1234').offset().top }, 'slow');
Alternatively, put a div at the bottom of your chat:
<div id="chat-end"></div>
And scroll to this ID instead.
JSFiddle Demo

Categories