How to add panel before and after panel - javascript

Report designer layout contains Bootstrap 3 panels.
Detail panel has Add group button which should add new panels before and after it.
This is implemented in onclick event handler using jquery prepend and append:
var $this = $(this),
$parentpanel = $this.parents(".designer-panel").get(0);
$parentpanel.prepend('<div class="panel designer-panel">' +
'<div class="panel-body designer-panel-body" style="height:1px">' +
'</div>' +
'<div class="bg-warning">' +
'<div class="panel-footer"><i class="glyphicon glyphicon-chevron-up">' +
'</i> Group heade {0}: <span id="band{0}_expr" contenteditable="true">"group expression"</span>' +
'</div></div></div>');
$parentpanel.append('<div class="panel designer-panel">' +
'<div class="panel-body designer-panel-body" style="height:1px">' +
'</div>' +
'<div class="bg-warning">' +
'<div class="panel-footer"><i class="glyphicon glyphicon-chevron-up">' +
'</i> Group footer {0}' +
'</div></div></div>');
});
If clicked in Add band button html appears instead of panel.
It looks like jquery preoend and append does not add dom objects work for unknown reason.
How to fix this so that new panels appear before and after detail panel ?
$(function() {
var startpos,
selected = $([]),
offset = { top: 0, left: 0 };
$('#designer-detail-addband').on('click', function () {
var $this = $(this),
$parentpanel = $this.parents(".designer-panel").get(0);
$parentpanel.prepend('<div class="panel designer-panel">' +
'<div class="panel-body designer-panel-body" style="height:1px">' +
'</div>' +
'<div class="bg-warning">' +
'<div class="panel-footer"><i class="glyphicon glyphicon-chevron-up">' +
'</i> Group heade {0}: <span id="band{0}_expr" contenteditable="true">"groupexpression"</span>' +
'</div></div></div>');
$parentpanel.append('<div class="panel designer-panel">' +
'<div class="panel-body designer-panel-body" style="height:1px"></div>' +
'<div class="bg-warning">' +
'<div class="panel-footer"><i class="glyphicon glyphicon-chevron-up">' +
'</i> Group footer {0}' +
'</div></div></div>');
});
$(".designer-panel-body").droppable({
accept: ".designer-field"
});
$(".designer-field").draggable({
start: function (event, ui) {
var $this = $(this);
if ($this.hasClass("ui-selected")) {
selected = $(".ui-selected").each(function () {
var el = $(this);
el.data("offset", el.offset());
});
} else {
selected = $([]);
$(".designer-field").removeClass("ui-selected");
}
offset = $this.offset();
},
drag: function (event, ui) {
// drag all selected elements simultaneously
var dt = ui.position.top - offset.top, dl = ui.position.left - offset.left;
selected.not(this).each(function () {
var $this = $(this);
var elOffset = $this.data("offset");
$this.css({ top: elOffset.top + dt, left: elOffset.left + dl });
});
}
});
$(".panel-resizable").resizable({
minWidth: "100%",
maxWidth: "100%",
minHeight: 1
});
});
.panel-resizable {
min-height: 1px;
overflow: hidden;
margin: 0;
padding: 0;
}
.designer-field {
border: 1px solid lightgray;
white-space: pre;
overflow: hidden;
position: absolute;
}
.designer-panel-body {
min-height: 1px;
overflow: hidden;
margin: 0;
padding: 0;
}
.panel-footer {
padding: 0;
}
.designer-panel, .panel-body {
margin: 0;
padding: 0;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
</head>
<body>
<div class='panel designer-panel'>
<div class='panel-body designer-panel-body panel-resizable' style='height:2cm'>
<div class='designer-field' style='left:5px;top:6px;width:180px'>field 1 in group 1 header</div>
<div class='designer-field' style='left:54px;top :36px;width:160px'>field 2 in group 1 header</div>
</div>
<div class='panel-footer'>Group 1 Header</div>
</div>
<div class='panel designer-panel'>
<div class='panel-body panel-resizable' style='height:1cm'>
<div class='designer-field' style='left:24px;top:2px;width:140px'>field in detail group </div>
</div>
<div class='panel-footer panel-primary'>Detail <a role="button" id="designer-detail-addband"> Add group</a></div>
</div>
<div class='panel'>
<div class='panel-body panel-resizable' style='height:1cm'>
<div class='designer-field' style='left:44px;top:2px;width:140px'>field in group 1 footer</div></div>
<div class='panel-footer panel-warning'>Group 1 Footer</div>
</div>

I think your issue is here:
$parentpanel = $this.parent(".designer-panel");
jQuery parent only goes one level up the DOM, and looking at your HTML the first div with .designer-panel is several levels up from your anchor. If you change it to the code below then you should hopefully get the element you want.
$parentpanel = $this.parents(".designer-panel").get(0);

Related

How to make dynamically created elements draggable with gridstack?

In my project I'm using this drag and drop library called gridstack. You can see their documentation on github here. When you hardcode elements inside the dom and initialize the gridstack, those elements are draggable. But when the elements are created dynamically with a forloop, they are not draggable even if they have the proper draggable classes. How can I make this work?
//initialize grid stack
var grid = GridStack.init({
minRow: 5, // don't collapse when empty
cellHeight: 70,
acceptWidgets: true,// acceptWidgets - accept widgets dragged from other grids or from outside (default: false).
dragIn: '.newWidget', // class that can be dragged from outside
dragInOptions: { revert: 'invalid', scroll: false, appendTo: 'body', helper:'clone' }, // clone or can be your function
removable: '#trash', // drag-out delete class
});
//gridstack on change
grid.on('added removed change', function(e, items) {
let str = '';
items.forEach(function(item) { str += ' (x,y)=' + item.x + ',' + item.y; });
console.log(e.type + ' ' + items.length + ' items:' + str );
});
//dynamic elemenets
const arr = ["Bruh cant drag me!", "Nope me neither", "Me too mouhahaha"];
//loop
for (let i = 0; i < arr.length; i++) {
var div = document.createElement('div');
var el = "<div class='newWidget grid-stack-item ui-draggable ui-resizable ui-resizable-autohide'> <div class='grid-stack-item-content' style='padding: 5px;'> "+arr[i]+"</div></div>";
div.innerHTML = el;
$('.dynamic').append(div);
}
.grid-stack-item-removing {
opacity: 0.8;
filter: blur(5px);
}
#trash {
background: rgba(255, 0, 0, 0.4);
padding: 5px;
text-align: center;
}
.grid-stack-item{
background: whitesmoke;
width: 50%;
border: 1px dashed grey;
}
.grid-stack {
background : #F0FFC0;
}
<!-- jquery -->
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<!-- gridstack-->
<link rel="stylesheet" href="https://gridstackjs.com/node_modules/gridstack/dist/gridstack-extra.min.css"/>
<script src="https://gridstackjs.com/node_modules/gridstack/dist/gridstack-h5.js"></script>
<!-- body-->
<body>
<div id="trash"><span>drop here to remove</span> </div>
<br>
<div class="dynamic"></div>
<div class="newWidget grid-stack-item ui-draggable ui-resizable ui-resizable-autohide">
<div class="grid-stack-item-content" style="padding: 5px;">
<div>
</div>
<div>
<span>I'm original domster! Drag and drop me!</span>
</div>
</div>
</div>
<br>
<div class="grid-stack"></div>
</body>
This issue was raised here. The grid does not automatically track external changes so the grid needs to be re-initialize for the dragIn option to notice the new dynamic widgets
GridStack.setupDragIn()
Full code
//initialize grid stack
var grid = GridStack.init({
minRow: 5, // don't collapse when empty
cellHeight: 70,
acceptWidgets: true,// acceptWidgets - accept widgets dragged from other grids or from outside (default: false).
dragIn: '.newWidget', // class that can be dragged from outside
dragInOptions: { revert: 'invalid', scroll: false, appendTo: 'body', helper:'clone' }, // clone or can be your function
removable: '#trash', // drag-out delete class
});
//gridstack on change
grid.on('added removed change', function(e, items) {
let str = '';
items.forEach(function(item) { str += ' (x,y)=' + item.x + ',' + item.y; });
console.log(e.type + ' ' + items.length + ' items:' + str );
});
//dynamic elemenets
const arr = ["Bruh cant drag me!", "Nope me neither", "Me too mouhahaha"];
//loop
for (let i = 0; i < arr.length; i++) {
var div = document.createElement('div');
var el = "<div class='newWidget grid-stack-item ui-draggable ui-resizable ui-resizable-autohide'> <div class='grid-stack-item-content' style='padding: 5px;'> "+arr[i]+"</div></div>";
div.innerHTML = el;
$('.dynamic').append(div);
}
GridStack.setupDragIn(
'.newWidget',
);
.grid-stack-item-removing {
opacity: 0.8;
filter: blur(5px);
}
#trash {
background: rgba(255, 0, 0, 0.4);
padding: 5px;
text-align: center;
}
.grid-stack-item{
background: whitesmoke;
width: 50%;
border: 1px dashed grey;
}
.grid-stack {
background : #F0FFC0;
}
<!-- jquery -->
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<!-- gridstack-->
<link rel="stylesheet" href="https://gridstackjs.com/node_modules/gridstack/dist/gridstack-extra.min.css"/>
<script src="https://gridstackjs.com/node_modules/gridstack/dist/gridstack-h5.js"></script>
<!-- body-->
<body>
<div id="trash"><span>drop here to remove</span> </div>
<br>
<div class="dynamic"></div>
<div class="newWidget grid-stack-item ui-draggable ui-resizable ui-resizable-autohide">
<div class="grid-stack-item-content" style="padding: 5px;">
<div>
</div>
<div>
<span>I'm original domster! Drag and drop me!</span>
</div>
</div>
</div>
<br>
<div class="grid-stack"></div>
</body>

I am retrieving items from a list and want only 4 to show on my page

I am retrieving items from a list, which has 5 items, but I only want 4 to show and every time I add a new item I want the new item to show first and then the other 3 items to follow and the fifth item must not show.
I have tried .last(), hide() but none of them help me accomplish what I want
<div id="phishing" class="row">
<!--Injected content-->
</div>
$.ajax({
url: "/cyberSecurity/_api/web/lists/GetByTitle('phishingExamples')/items",
method: 'GET',
headers: {
'Accept': 'application/json; odata=verbose'
},
success: function(data) {
var items = data.d.results;
var phishing = $('#phishing');
var phishingCards;
for (var i = 0; i <4; i++) {
phishingCards = '<div class="col-sm-6 col-md-6 col-lg-3 mb-3">' +
'<div style="background-color: #004685; height: 340px; position: relative;" class="card backImg2 ">' +
'<div style="color: #fff;" class="card-body ">' +
'<h5 style="color: #ffe01a;" class="card-title ">' + items[i].Title + '</h5>' +
'<p style="margin-bottom: -5px;" class="card-text ">' + items[i].Description + '</p>' +
'<div style="width: 100%; margin: 0 auto; position: absolute; bottom: 0;right: 0" class="row "><a style=" background-color: #ffe01a!important; color: black!important; border: none; width: 100%;" href= "'+ items[i].Image.Url +'"class="btn btn-primary btn-sm" target=_blank>More Info</a></div>' +
'</div>' +
'</div>' +
'</div>';
phishing.prepend(phishingCards);
}
},
error: function(data) {
console.log('Error: ' + data);
}
}); // End Service Icons //End Service Icons
I expect to show only 4 items on the page even if there is more than 4 items. I also want the new item to show first.
I actually get the new items first when I changed the loop to items.length but I only want to show 4 items.
enter image description here
The array has the newest item last, but you're skipping that because you only show the first 4 items. Instead of starting from 0, subtract 4 from the length, and make sure it's at least 0.
let start = Math.max(0, items.length-4);
for (let i = start; i < items.length; i++) {
Here I changed prepend() to append()
$.ajax({
url: "/cyberSecurity/_api/web/lists/GetByTitle('phishingExamples')/items",
method: 'GET',
headers: {
'Accept': 'application/json; odata=verbose'
},
success: function(data) {
var items = data.d.results;
var phishing = $('#phishing');
var phishingCards;
for (var i = 0; i <4; i++) {
phishingCards = '<div class="col-sm-6 col-md-6 col-lg-3 mb-3">' +
'<div style="background-color: #004685; height: 340px; position: relative;" class="card backImg2 ">' +
'<div style="color: #fff;" class="card-body ">' +
'<h5 style="color: #ffe01a;" class="card-title ">' + items[i].Title + '</h5>' +
'<p style="margin-bottom: -5px;" class="card-text ">' + items[i].Description + '</p>' +
'<div style="width: 100%; margin: 0 auto; position: absolute; bottom: 0;right: 0" class="row "><a style=" background-color: #ffe01a!important; color: black!important; border: none; width: 100%;" href= "'+ items[i].Image.Url +'"class="btn btn-primary btn-sm" target=_blank>More Info</a></div>' +
'</div>' +
'</div>' +
'</div>';
phishing.append(phishingCards);
}
},
error: function(data) {
console.log('Error: ' + data);
}
}); // End Service Icons //End Service Icons
or this, where I changed your for loop to run in reverse order, while retaining prepend().
$.ajax({
url: "/cyberSecurity/_api/web/lists/GetByTitle('phishingExamples')/items",
method: 'GET',
headers: {
'Accept': 'application/json; odata=verbose'
},
success: function(data) {
var items = data.d.results;
var phishing = $('#phishing');
var phishingCards;
for (var i = 4; i < -1; i--) {
phishingCards = '<div class="col-sm-6 col-md-6 col-lg-3 mb-3">' +
'<div style="background-color: #004685; height: 340px; position: relative;" class="card backImg2 ">' +
'<div style="color: #fff;" class="card-body ">' +
'<h5 style="color: #ffe01a;" class="card-title ">' + items[i].Title + '</h5>' +
'<p style="margin-bottom: -5px;" class="card-text ">' + items[i].Description + '</p>' +
'<div style="width: 100%; margin: 0 auto; position: absolute; bottom: 0;right: 0" class="row "><a style=" background-color: #ffe01a!important; color: black!important; border: none; width: 100%;" href= "'+ items[i].Image.Url +'"class="btn btn-primary btn-sm" target=_blank>More Info</a></div>' +
'</div>' +
'</div>' +
'</div>';
phishing.prepend(phishingCards);
}
},
error: function(data) {
console.log('Error: ' + data);
}
}); // End Service Icons //End Service Icons
Either one of these should reverse the order of the items in your array as they are printed to the dom. This is assuming that your existing code correctly prints only 4 items, I didn't see where you specified that it was printing more than 4 items except where you set items.length as the conditional in the for loop, which I'm not doing in these examples.
Also, I don't know what the structure of your items array is, but if the objects in that array have a date or timestamp property, then you can sort the array by that property first before running your for loop, that way you can be certain of the order of your items. However this answer is running on the assumption that you only have Title, Description and Image as object properties because thats all I can see in your code.
Let me know how this goes!

Unable to append modal using JavaScript

I'm unable to append a certain div to a modal when pulling in data using pnp and JavaScript.
The whole process explained:
Function DomyApiCalls - WORKS (Pulls in all the boxes with the titles)
Function filtering - WORKS (Filters the names in alphabetical order)
Function getModal - Doesn't work (I want it when a user clicks on a box, that the modal shows and just appends all the filesHtml to the .Modalbody class.
This is pulling in the page title, I need the folderName from below instead.
$(document).ready(function(){
DoMyApiCalls("boxWrap");
var current_title = $(document).attr('title'); //CURRENT_TITLE is supposed to be the "FolderName".
if(current_title == 'Acuvue') {
getModal("Acuvue");
}
});
function DoMyApiCalls(elementId) {
$.ajax({
url: "/bdm/business-development/_api/web/lists/GetByTitle('CompletedSubmissionTiles')/Items?$select=EncodedAbsUrl,Title,Line1,Line2,Hyperlink,TargetWindow,DescriptionHTMLOption,Line1,TileOrder&$orderby=Title asc",
type: "GET",
headers: {
"accept": "application/json; odata=verbose"
},
success: function (data) {
if (data.d.results) {
var object = data.d.results;
var Line1var;
for(var i = 0; i < object.length; i++)
{
if(object[i].Line1 != null) { // Covers 'undefined' as well
Line1var = "<div class='Line1'>" + object[i].Line1 + "</div>";
} else {
Line1var = "";
}
$('#' + elementId).append("<div class='col-md-4 box' data-toggle='modal' data-target='#modal"+object[i].TileOrder+"' id='TileBox"+object[i].TileOrder+"'><div id='titleBox' class='titleBox'><h1>" + object[i].Title + "</h1><div style='width:250px; height: 130px;background-color: white; border: 1px solid lightgrey;'><img style='width: auto; height: inherit; margin-left: auto; margin-right: auto; display: block;' src='" + object[i].EncodedAbsUrl + "' alt='" + object[i].Title +"'/></div></div></div>");
filtering(object[i].Title);
}
}
}
});
};
function filtering(title) {
var filter = "Name eq '" + title + "'";
$pnp.setup({
baseUrl: "/bdm/business-development/"
});
$pnp.sp.web.folders.getByName('Completed Submissions').folders.filter(filter).expand("Files").get().then(function(data){
});
}
function getModal(folderName) {
$pnp.setup({
baseUrl: "/bdm/business-development/Completed%20Submissions/"
});
$pnp.sp.web.getFolderByServerRelativeUrl("/bdm/business-development/Completed%20Submissions/" + folderName).files.orderBy("Name").get().then(function(f) {
var files = '';
$.each(f, function(index, value){
var filesHtml = "<div class='file'>" +
"<a target='_blank' href='" + value.ServerRelativeUrl + "?web=1'><img src='//PublishingImages/wordThumbSmall.png'/></a>" +
"<a target='_blank' href='" + value.ServerRelativeUrl + "?web=1'><p id='fileTitle'>" + value.Title + "</p></a>" +
"</div>";
files = files + filesHtml;
});
$(".Modalbody").append(files);
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="modal" class="modal fade" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><div id="x">×</div></button>
<h4 class="modal-title">
</h4>
</div>
<div class="modal-body">
<div class="FT-main-category" style="margin-top:0px;">
<div class="FT-main-header ms-WPBody"><strong><span style="color: white;">Files</span></strong></div>
<div class="Modalbody">
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>

How to add new panels before and after clicked panel

Report designer detail band contains Add band button which shoud add new panels immediately before and after detail panel.
$parentpanel = $this.parents(".designer-panel:first");
is used to find parent panel and .prepend() / append() to add new panels.
Panels are added as Detail panel child elements.
How to add panels before and after Detail panel in same DOM level like group header and footer panels in sample html.
Elements should probably added to $parentpanel.parent() element list before and after $parentpanel element.
Is there some selector or append command in jQuery for this ?
$(function() {
var startpos,
selected = $([]),
offset = {
top: 0,
left: 0
};
$('#designer-detail-addband').on('click', function() {
var $this = $(this),
$parentpanel = $this.parents(".designer-panel:first");
$parentpanel.prepend('<div class="panel designer-panel">' +
'<div class="panel-body designer-panel-body" style="height:1px">' +
'</div>' +
'<div class="bg-warning">' +
'<div class="panel-footer"><i class="glyphicon glyphicon-chevron-up">' +
'</i> Group heade {0}: <span id="band{0}_expr" contenteditable="true">"groupexpression"</span>' +
'</div></div></div>');
$parentpanel.append('<div class="panel designer-panel">' +
'<div class="panel-body designer-panel-body" style="height:1px"></div>' +
'<div class="bg-warning">' +
'<div class="panel-footer"><i class="glyphicon glyphicon-chevron-up">' +
'</i> Group footer {0}' +
'</div></div></div>');
});
$(".designer-panel-body").droppable({
accept: ".designer-field"
});
$(".designer-field").draggable({
start: function(event, ui) {
var $this = $(this);
if ($this.hasClass("ui-selected")) {
selected = $(".ui-selected").each(function() {
var el = $(this);
el.data("offset", el.offset());
});
} else {
selected = $([]);
$(".designer-field").removeClass("ui-selected");
}
offset = $this.offset();
},
drag: function(event, ui) {
// drag all selected elements simultaneously
var dt = ui.position.top - offset.top,
dl = ui.position.left - offset.left;
selected.not(this).each(function() {
var $this = $(this);
var elOffset = $this.data("offset");
$this.css({
top: elOffset.top + dt,
left: elOffset.left + dl
});
});
}
});
$(".panel-resizable").resizable({
minWidth: "100%",
maxWidth: "100%",
minHeight: 1
});
})
.panel-resizable {
min-height: 1px;
overflow: hidden;
margin: 0;
padding: 0;
}
.designer-field {
border: 1px solid lightgray;
white-space: pre;
overflow: hidden;
position: absolute;
}
.designer-panel-body {
min-height: 1px;
overflow: hidden;
margin: 0;
padding: 0;
}
.panel-footer {
padding: 0;
}
.designer-panel,
.panel-body {
margin: 0;
padding: 0;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
</head>
<body>
<div class='panel designer-panel'>
<div class='panel-body designer-panel-body panel-resizable' style='height:2cm'>
<div class='designer-field' style='left:5px;top:6px;width:180px'>field 1 in group 1 header</div>
<div class='designer-field' style='left:54px;top :36px;width:160px'>field 2 in group 1 header</div>
</div>
<div class='panel-footer'>Group 1 Header</div>
</div>
<div class='panel designer-panel'>
<div class='panel-body panel-resizable' style='height:1cm'>
<div class='designer-field' style='left:24px;top:2px;width:140px'>field in detail group</div>
</div>
<div class='panel-footer panel-primary'>Detail <a role="button" id="designer-detail-addband"> Add group</a>
</div>
</div>
<div class='panel'>
<div class='panel-body panel-resizable' style='height:1cm'>
<div class='designer-field' style='left:44px;top:2px;width:140px'>field in group 1 footer</div>
</div>
<div class='panel-footer panel-warning'>Group 1 Footer</div>
</div>
Try jQuery's before, after functions. Or insertBefore, insertAfter
Also you can use
$this.closest(".designer-panel");
instead of
$this.parents(".designer-panel:first");
See closest

can't get the right index result with an ajax call

I was trying to iterate the 'streamers' array by the variable showindex but failed,it just shows the first element "monstercat" and last element "amazhs" of the array, using debug in chrome and showindex in the displayResult function always is 0 and 9, can't figure out why. Any ideas?
var streamers = ['monstercat', 'sivhd', 'cryaotic', 'nightblue3', 'picoca_lol', 'freecodecamp', 'trick2g', 'riotgamesbrazil', 'riotgames', 'amazhs'];
$(document).ready(function() {
var logo = "";
var channelName = "";
var showindex = 0;
streamers.forEach(function(streamer, index) {
showindex = index;
$.ajax({
type: 'GET',
jsonp: "callback",
url: 'https://api.twitch.tv/kraken/streams/' + streamer,
headers: {
'Client-ID': 'd50b88uvtwlhdfrqi3vj3k1hm3izkyx'
},
success: displayResult
});
});
function displayResult(data) {
var outstring = "";
if (data.stream !== null) {
channelName = data.stream.channel.display_name;
logo = data.stream.channel.logo;
} else {
logo = "https://placeholdit.imgix.net/~text?txtsize=6&txt=50%C3%9750&w=50&h=50";
channelName = streamers[showindex];
}
outstring +=
"<li class='streamer'>" +
"<img class='streamer-icon' src='" + logo + "'/>" +
"<p class='streamer-name'>" +
"<a href='http://twitch.tv/" + channelName + "' target='_blank'>" + channelName + "</a></p>" +
"<span class='streamer-status'>" +
"<i class='fa fa-exclamation'></i></span></li>"
$("#showBox").append(outstring);
}
});
ul {
padding: 0;
margin: 0;
}
.tab-content {
border: 1px solid #ddd;
border-top: none;
}
.streamer {
list-style-type: none;
padding: 10px;
}
.streamer-icon {
width: 50px;
}
.streamer-name {
display: inline-block;
margin-left: 10px;
}
.streamer-status {
float: right;
padding-top: 15px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<div class="container">
<div class="row col-md-4 col-md-offset-4">
<ul class="nav nav-tabs" role="tablist">
<li class="active">all
</li>
<li>online
</li>
<li>offline
</li>
</ul>
<div class="tab-content">
<div class="tab-pane active" id="all">
<ul id="showBox">
</ul>
</div>
<div class="tab-pane" id="online">
<ul></ul>
</div>
<div class="tab-pane" id="offline">
<ul></ul>
</div>
</div>
</div>
</div>
It's because the calls are all happening at the same time so instantly showindex = 9 a way around this would be to do the incrementation in displayResult though it could still go wrong (but it's less likely).
You probably could change your code entirely to make it use promises which would be a lot safer.
var streamers = ['monstercat', 'sivhd', 'cryaotic', 'nightblue3', 'picoca_lol', 'freecodecamp', 'trick2g', 'riotgamesbrazil', 'riotgames', 'amazhs'];
$(document).ready(function() {
var logo = "";
var channelName = "";
var showindex = 0;
streamers.forEach(function(streamer, index) {
$.ajax({
type: 'GET',
jsonp: "callback",
url: 'https://api.twitch.tv/kraken/streams/' + streamer,
headers: {
'Client-ID': 'd50b88uvtwlhdfrqi3vj3k1hm3izkyx'
},
success: displayResult
});
});
function displayResult(data) {
var outstring = "";
if (data.stream !== null) {
channelName = data.stream.channel.display_name;
logo = data.stream.channel.logo;
} else {
logo = "https://placeholdit.imgix.net/~text?txtsize=6&txt=50%C3%9750&w=50&h=50";
channelName = streamers[showindex];
}
outstring +=
"<li class='streamer'>" +
"<img class='streamer-icon' src='" + logo + "'/>" +
"<p class='streamer-name'>" +
"<a href='http://twitch.tv/" + channelName + "' target='_blank'>" + channelName + "</a></p>" +
"<span class='streamer-status'>" +
"<i class='fa fa-exclamation'></i></span></li>"
$("#showBox").append(outstring);
showindex++;
}
});
ul {
padding: 0;
margin: 0;
}
.tab-content {
border: 1px solid #ddd;
border-top: none;
}
.streamer {
list-style-type: none;
padding: 10px;
}
.streamer-icon {
width: 50px;
}
.streamer-name {
display: inline-block;
margin-left: 10px;
}
.streamer-status {
float: right;
padding-top: 15px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<div class="container">
<div class="row col-md-4 col-md-offset-4">
<ul class="nav nav-tabs" role="tablist">
<li class="active">all
</li>
<li>online
</li>
<li>offline
</li>
</ul>
<div class="tab-content">
<div class="tab-pane active" id="all">
<ul id="showBox">
</ul>
</div>
<div class="tab-pane" id="online">
<ul></ul>
</div>
<div class="tab-pane" id="offline">
<ul></ul>
</div>
</div>
</div>
</div>
Here's another way to do it, it doesn't use foreach but iterates through the array another way. This way is a bit slower but means it doesn't get ahead of itself (you can actually see each one pop in)
var streamers = ['monstercat', 'sivhd', 'cryaotic', 'nightblue3', 'picoca_lol', 'freecodecamp', 'trick2g', 'riotgamesbrazil', 'riotgames', 'amazhs'];
$(document).ready(function() {
var logo = "";
var channelName = "";
var showindex = 0;
//Work out if there are any streamers left in the array
function calcStreamers() {
if (showindex < (streamers.length - 1)) {
//if there are add 1 and go get it
showindex++;
streamersGet();
} else {
//if not just stop
return false
}
};
//The get function
function streamersGet() {
$.ajax({
type: 'GET',
jsonp: "callback",
url: 'https://api.twitch.tv/kraken/streams/' + streamers[showindex],
headers: {
'Client-ID': 'd50b88uvtwlhdfrqi3vj3k1hm3izkyx'
},
success: displayResult
});
};
function displayResult(data) {
var outstring = "";
if (data.stream !== null) {
channelName = data.stream.channel.display_name;
logo = data.stream.channel.logo;
} else {
logo = "https://placeholdit.imgix.net/~text?txtsize=6&txt=50%C3%9750&w=50&h=50";
channelName = streamers[showindex];
}
outstring +=
"<li class='streamer'>" +
"<img class='streamer-icon' src='" + logo + "'/>" +
"<p class='streamer-name'>" +
"<a href='http://twitch.tv/" + channelName + "' target='_blank'>" + channelName + "</a></p>" +
"<span class='streamer-status'>" +
"<i class='fa fa-exclamation'></i></span></li>"
$("#showBox").append(outstring);
//Once the data has been added to the page go and check if there are more to add
calcStreamers();
}
//Initally start by getting the first result
streamersGet();
});
ul {
padding: 0;
margin: 0;
}
.tab-content {
border: 1px solid #ddd;
border-top: none;
}
.streamer {
list-style-type: none;
padding: 10px;
}
.streamer-icon {
width: 50px;
}
.streamer-name {
display: inline-block;
margin-left: 10px;
}
.streamer-status {
float: right;
padding-top: 15px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<div class="container">
<div class="row col-md-4 col-md-offset-4">
<ul class="nav nav-tabs" role="tablist">
<li class="active">all
</li>
<li>online
</li>
<li>offline
</li>
</ul>
<div class="tab-content">
<div class="tab-pane active" id="all">
<ul id="showBox">
</ul>
</div>
<div class="tab-pane" id="online">
<ul></ul>
</div>
<div class="tab-pane" id="offline">
<ul></ul>
</div>
</div>
</div>
</div>
You wanted to iterate through the array correct?
var streamers = ['monstercat', 'sivhd', 'cryaotic', 'nightblue3', 'picoca_lol', 'freecodecamp', 'trick2g', 'riotgamesbrazil', 'riotgames', 'amazhs'];
$(document).ready(function() {
$(streamers).each(function(index, streamer){
console.log(streamer+" "+index);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Categories