Duplicate item appearing in DIV - javascript

I have a problem with my code. I am pushing items into a new array and displaying two of them in a DIV. For some reason its showing the same item twice rather than showing two separate items. Hoping someone can help me out with this. I just need a way to prevent the same recipe from being able to show twice in the DIV.
var categoryItems = [];
var recipeTitle = $('#recipeTitle').text();
$.each(recipe_data, function(i, item){
if (item.recipeCategory == "4" && recipeTitle !== item.recipeName) { categoryItems.push(item); }
});
var similarRecipe = '';
var randomRecipe = {};
randomRecipe = categoryItems[Math.floor(Math.random()*categoryItems.length)];
for(var i = 0; i < categoryItems.length; i += 2) {
similarRecipe = [ '<div class="col-md-6 col-sm-6 img-margin">' + ' <div class="addthis_inline_share_toolbox" data-url="' + randomRecipe.recipePageURL +'" data-title="' + randomRecipe.recipeName + '"></div>'
+ '' + '<img class="img-responsive" src="' + randomRecipe.recipeImageCategoryURL + '">' + ''
+ '' + '<h3 class="recipeSubCategoryImgCaption">' + randomRecipe.recipeName + '</h3>' + '' + '</div>' ];
$('#recipeSimilar').append(similarRecipe);
}
Edit: Please take a look at this fiddle for an example. It should not show the same recipe twice when refreshing, rather show two different recipes from the category. My problem is that is is sometimes it is showing the same one twice when you refresh. https://jsfiddle.net/wn4fmm5r/

you are generating one random Recipe and displaying same twice into your for loop
randomRecipe = categoryItems[Math.floor(Math.random()*categoryItems.length)];
for(var i = 0; i < categoryItems.length; i += 2) {
similarRecipe = [ '<div class="col-md-6 col-sm-6 img-margin">' + ' <div class="addthis_inline_share_toolbox" data-url="' + randomRecipe.recipePageURL +'" data-title="' + randomRecipe.recipeName + '"></div>'
+ '' + '<img class="img-responsive" src="' + randomRecipe.recipeImageCategoryURL + '">' + ''
+ '' + '<h3 class="recipeSubCategoryImgCaption">' + randomRecipe.recipeName + '</h3>' + '' + '</div>' ];
$('#recipeSimilar').append(similarRecipe);
}
try including your statement for generating random recipe inside loop.
for(var i = 0; i < categoryItems.length; i += 2) {
randomRecipe = categoryItems[Math.floor(Math.random()*categoryItems.length)];
similarRecipe = [ '<div class="col-md-6 col-sm-6 img-margin">' + ' <div class="addthis_inline_share_toolbox" data-url="' + randomRecipe.recipePageURL +'" data-title="' + randomRecipe.recipeName + '"></div>'
+ '' + '<img class="img-responsive" src="' + randomRecipe.recipeImageCategoryURL + '">' + ''
+ '' + '<h3 class="recipeSubCategoryImgCaption">' + randomRecipe.recipeName + '</h3>' + '' + '</div>' ];
$('#recipeSimilar').append(similarRecipe);
}
Edit for no repeating ----
var counter;
for (var i = 0; i < categoryItems.length; i += 2) {
var item = Math.floor(Math.random() * categoryItems.length);
if (!counter) {
counter = item;
} else {
if (counter == item) {
item = Math.floor(Math.random() * categoryItems.length);
counter = item;
}
}
randomRecipe = categoryItems[item];
similarRecipe = ['<div class="col-md-6 col-sm-6 img-margin">' + ' <div class="addthis_inline_share_toolbox" data-url="' + randomRecipe.recipePageURL + '" data-title="' + randomRecipe.recipeName + '"></div>'
+ '' + '<img class="img-responsive" src="' + randomRecipe.recipeImageCategoryURL + '">' + ''
+ '' + '<h3 class="recipeSubCategoryImgCaption">' + randomRecipe.recipeName + '</h3>' + '' + '</div>'];
$('#recipeSimilar').append(similarRecipe);
}

Related

How do I append an Image in the DOM from a list using EncodedAbsUrl

I have 2 lists with 5 columns; one has Title, Question, Attorneys, ID, and attorneyPic. This last one is looking into an image list. I created a webpart for this so the the actual webpart looks like this.
<script type="text/javascript">
apiUrl = "/Legal/Attorneys/_api/web/lists/GetByTitle('attorneysBio')/items$select=*,EncodedAbsUrl,attorneysPic/Title&$expand=attorneysPic/Id";
topicsTitle = '';
title = 'TITLE HERE';
</script>
The javascript code looks like this
var buildCards = function () {
if (filterTopic.length !== 0) {
for (i = 0; i < filterTopic.length; i++) {
var accID2 = accID.replace(/\s/g, '');
var faqItems = filterTopic[i]
var headerID = "heading" + faqItems.ID
var cardBodyID = "collapse" + faqItems.ID
var cardTitle = faqItems.Title
var cardBody = faqItems.Question
var attorneyPics = faqItems.attorneysPic.EncodedAbsUrl
console.log(attorneyPics)
var cardBuild = '<div class="card">' +
'<div class="card-header pb-1 pl-0" role="tab" id="' + headerID + '">' +
'<a class="collapsed" data-toggle="collapse" data-parent="#' + accID2 + '" href="#' + cardBodyID + '" aria-expanded="false" aria-controls="' + cardBodyID + '">' +
'<h5 class="mb-0 font-thin">' + cardTitle + '<span class="rotate"></span></h5>' +
'</a>' +
'</div>' +
'<div id="' + cardBodyID + '" class="collapse" role="tabpanel" aria-labelledby="' + headerID + '" data-parent="#' + accID + '">' +
'<div class="row"><div class="col-md-3"><img src="'+attorneyPics+'" class="img-responsive"></div>' +
'<div class="col-md-9"><div class="card-body py-1 pl-0"><p>' + cardBody + '</p></div></div></div>' +
'</div>' +
'</div>'
$(".accordion").append(cardBuild);
};
} else {
var cardBuild = '<h4>There are no results matching your search.</div>'
$(".accordion").append(cardBuild);
}
What is happening is that the url given is the one from the actual list and not from the list items "https://browardauthor/Legal/Attorneys/Lists/attorneysBio/1_.000"

How to use numeral.JS in this situation?

I am trying to use numeral.js to format my listener variable so numbers could be easily readable. But after I tried to use numeral.js the way it is, my function stops working. Can anyone please advise on what's wrong?
Trackster.renderTracks = function(tracks) {
var $trackList = $("#track-list");
$trackList.empty();
for (var trackIndex = 0; trackIndex < tracks.length; trackIndex++) {
var track = tracks[trackIndex];
var mediumAlbumArt = track.image[1]["#text"];
var formatListeners = numeral(track.listeners).format('0,0');
var htmlTrackRow =
'<div class="row track">' +
' <div class="col-xs-1 col-xs-offset-1 play-button">' +
' <a href="'+ track.url + '" target="_blank">' +
' <i class="fa fa-play-circle-o fa-2x"></i>' +
' </a>' +
' </div>' +
' <div class="col-xs-4">' + track.name + '</div>' +
' <div class="col-xs-2">' + track.artist + '</div>' +
' <div class="col-xs-2"><img src="' + mediumAlbumArt + '"/></div>' +
' <div class="col-xs-2">' + formatListeners + '</div>' +
'</div>';
$trackList.append(htmlTrackRow);
}
};
Full Github Code is https://github.com/tfan1210/Trackster
Thanks!

If else statement into a variable

I am trying to insert the statement If else with a for condition into a variable. I don't really know how to handle it.
Here is my original function:
var fontsList = '<div class="list">' + Object.keys(families).map(function(familyName) {
chaine = families[familyName].map(function(variants) {
return '<div class="all-sub-fonts" style="font-family:'+ variants.postscriptName +';" onclick=\'fontUsed("' + variants.postscriptName + '", this)\'><div class="variants-font">' + familyName + ' ' + variants.style + '</div></div>'
})
return '<div class="font-box-name" style="font-family:'+ familyName +';" onclick=\'fontUsed("' + familyName + '", this)\'>' + familyName + '</div><div class="btn-accordion"></div><div class="box-sub-fonts">'+ chaine.join('') +'</div>';
}).join('') + '</div>';
I'd like the chain to return when there are more than 1 variant in the font family. What I tried goes directly with else. Here is the code:
var fontsList = '<div class="list">' + Object.keys(families).map(function(familyName) {
if(families.length > 1){
chaine = families[familyName].map(function(variants) {
return '<div class="all-sub-fonts" style="font-family:'+ variants.postscriptName +';" onclick=\'fontUsed("' + variants.postscriptName + '", this)\'><div class="variants-font">' + familyName + ' ' + variants.style + '</div></div>'
})
return '<div class="font-box-name" style="font-family:'+ familyName +';" onclick=\'fontUsed("' + familyName + '", this)\'>' + familyName + '</div><div class="btn-accordion"></div><div class="box-sub-fonts">'+ chaine.join('') +'</div>';
} else {
return '<div class="font-box-name" style="font-family:'+ familyName +';" onclick=\'fontUsed("' + familyName + '", this)\'>' + familyName + '</div>';
}
}).join('') + '</div>';
This code access to the font family having 1 variant only.
for(var k in families) if(families[k].length === 1)

bootstrap collapsible not collapsing after expanded

Collapsible did not collapse after being expanded. It is dynamically created in popover.
Here is my jsFiddle:
$('.tooltiphelp').tooltip();
$('[data-toggle="tooltip"]').tooltip();
$('[data-toggle="popover"]').popover();
$('[data-toggle="collapse"]').collapse();
jQuery('document').ready(function() {
jQuery('#accordionRank').on('show hide', function() {
jQuery(this).css('height', 'auto');
});
jQuery('#accordionRank').collapse({ parent: true, toggle: true });
});
var popover = $("#noteListDiv").find('.positive').popover({
trigger: 'click',
placement: 'bottom',
content: function () {
return func_getRank($(this).closest('tr').prop('id'));
}
});
var func_getRank = function (ID) {
var Rankdata = {"Rank":[{"ID": "114077", "NL": "1 of 25", "OF": "1 of 30", "MLB": "1 of 240"}]};
var cshtml;
cshtml = '<div>'
+ '<div class="accordion" id="accordionRank">'
+ '<div class="accordion-group">'
+ '<div class="accordion-heading">'
+ '<a class="accordion-toggle" data-toggle="collapse" data-parent="#accordionRank" href="#collapseNL">'
+ 'NL Rank: ' + Rankdata.Rank[0].NL
+ '</a>'
+ '</div>'
+ '<div id="collapseNL" class="accordion-body collapse">'
+ '<div class="accordion-inner">'
+ 'Anim pariatur cliche...'
+ '</div>'
+ '</div>'
+ '</div>'
+ '<div class="accordion-group">'
+ '<div class="accordion-heading">'
+ '<a class="accordion-toggle" data-toggle="collapse" data-parent="#accordionRank" href="#collapseOF">'
+ 'OF Rank: ' + Rankdata.Rank[0].OF
+ '</a>'
+ '</div>'
+ '<div id="collapseOF" class="accordion-body collapse">'
+ '<div class="accordion-inner">'
+ 'Anim pariatur cliche...'
+ '</div>'
+ '</div>'
+ '</div>'
+ '<div class="accordion-group">'
+ '<div class="accordion-heading">'
+ '<a class="accordion-toggle" data-toggle="collapse" data-parent="#accordionRank" href="#collapseMLB">'
+ 'MLB Rank: ' + Rankdata.Rank[0].MLB
+ '</a>'
+ '</div>'
+ '<div id="collapseMLB" class="accordion-body collapse">'
+ '<div class="accordion-inner">'
+ '<table id="MiniLeaderboard">'
+ '<thead><tr>'
+ '<th>Rank</th>'
+ '<th>Hitter</th>'
+ '<th>BAVG</th>'
+ '<th>Hits/AB</th>'
+ '</tr></thead>'
+ '<tbody><tr>'
+ '<td>1</td>'
+ '<td>Christian Yelich</td>'
+ '<td>.470</td>'
+ '<td>39-for-83</td>'
+ '</tr>'
+ '<tr>'
+ '<td>2</td>'
+ '<td>Ryan Braun</td>'
+ '<td>.397</td>'
+ '<td>27-for-68</td>'
+ '</tr>'
+ '<tr>'
+ '<td>3</td>'
+ '<td>Adam Eaton</td>'
+ '<td>.370</td>'
+ '<td>37-for-100</td>'
+ '</tr>'
+ '<tr>'
+ '<td>4</td>'
+ '<td>Joey Votto</td>'
+ '<td>.369</td>'
+ '<td>31-for-84</td>'
+ '</tr>'
+ '<tr>'
+ '<td>5</td>'
+ '<td>Edwin Encarnation</td>'
+ '<td>.364</td>'
+ '<td>28-for-77</td>'
+ '</tr></tbody>'
+ '</table>'
+ '</div>'
+ '</div>'
+ '</div>'
+ '</div>'
+ '</div>'
;
return $(cshtml).html();
};
Data text should come from JSON.
Here is the issue, please watch this screen cast.
Please help! Thanks in forward for your help.
I've updated my jsFiddle and it's now working. Maybe not a good idea but looks good for now.
$(document).on('click', '.accordion-toggle', function(e) {
$(e.target).css('text-decoration','none');
var $_this = $(e.target).parent().next("div");
var $_inner = $_this.find('div:first-child');
if($_inner.hasClass('in')){
$_inner.removeClass("in");
$_this.removeClass("in");
}
else {
$_inner.addClass("in");
$_this.addClass("in");
}
func_accordionToggle(e.target);
});
var func_accordionToggle = function (e) {
var $_this = $(e).parent().parent();
var id = $(e).parent().next("div").attr('id');
switch(id) {
case 'collapseNL':
$('#collapseOF').removeClass("in");
$('#collapseMLB').removeClass("in");
$('#collapseOF').find('div:first-child').removeClass("in");
$('#collapseMLB').find('div:first-child').removeClass("in");
break;
case 'collapseOF':
$('#collapseNL').removeClass("in");
$('#collapseMLB').removeClass("in");
$('#collapseNL').find('div:first-child').removeClass("in");
$('#collapseMLB').find('div:first-child').removeClass("in");
break;
case 'collapseMLB':
$('#collapseNL').removeClass("in");
$('#collapseOF').removeClass("in");
$('#collapseNL').find('div:first-child').removeClass("in");
$('#collapseOF').find('div:first-child').removeClass("in");
break;
};
}
Thanks for all the help Guys.

JavaScript error with XML when trying to read empty node

I am trying to render a catalog from an XML document and everything works, although when trying to show a default image if there is no image present in the XML node, it disables the parent node therefore forcing it not to show any of it and it reads me an error in my console saying:
Uncaught TypeError: Cannot read property 'getElementsByTagName' of
undefined
Which is pointing to this part of the code:
if (records[i].getElementsByTagName("IMAGE")[0].childNodes.length > 0)
{
So my question is where in my code below is my error causing it to not load the XML node?
PS: If anybody needs more of my code please let me know, and I would be happy to post it.
for (var i = fromItem; i < nextMaxItem; i++) {
if (records[i].getElementsByTagName("IMAGE")[0].childNodes.length > 0) {
xmlContent += '<article class="post all ' + records[i].getElementsByTagName("CATEGORY")[0].childNodes[0].nodeValue + '" id="">'
+ '<div class="col-sm-4 col-lg-4 col-md-4"><div class="thumbnail img-hover">'
+ '<a class="fancybox" rel="group" href="' + records[i].getElementsByTagName("BIGIMAGE")[0].childNodes[0].nodeValue + '" title="'+ records[i].getElementsByTagName("SHORTDESCRIPTION")[0].childNodes[0].nodeValue +'">'
+ '<img class="product-image" src="' + records[i].getElementsByTagName("IMAGE")[0].childNodes[0].nodeValue + '" alt="' + records[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue + '" />'
+ '<div class="caption">'
+ '<h4>' + records[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue + '</h4>'
+ '<p>' + records[i].getElementsByTagName("SHORTDESCRIPTION")[0].childNodes[0].nodeValue + '</p>'
+ '</div>'
+ "</a></div></div></article>";
} else {
xmlContent += '<article class="post all ' + records[i].getElementsByTagName("CATEGORY")[0].childNodes[0].nodeValue + '" id="">'
+ '<div class="col-sm-4 col-lg-4 col-md-4"><div class="thumbnail img-hover">'
+ '<a class="fancybox" rel="group" href="' + records[i].getElementsByTagName("BIGIMAGE")[0].childNodes[0].nodeValue + '" title="'+ records[i].getElementsByTagName("SHORTDESCRIPTION")[0].childNodes[0].nodeValue +'">'
+ '<img class="product-image" src="/images/Products/no-preview.jpg" alt="No Preview Available" />'
+ '<div class="caption">'
+ '<h4>' + records[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue + '</h4>'
+ '<p>' + records[i].getElementsByTagName("SHORTDESCRIPTION")[0].childNodes[0].nodeValue + '</p>'
+ '</div>'
+ "</a></div></div></article>";
}
}
Here is the whole JavaScript code:
var page = 1, perPage = 12, content = document.getElementById('content'),
pagination = document.getElementById('pagination'), records;
function paganation(page) {
var nextMaxItem = perPage * page,
fromItem = (page - 1) * perPage,
maxPages = Math.ceil(records.length / perPage);
var xmlContent = '<div class="row">';
for (var i = fromItem; i < nextMaxItem; i++) {
if (records[i].getElementsByTagName("IMAGE")[0].childNodes.length > 0) {
xmlContent += '<article class="post all ' + records[i].getElementsByTagName("CATEGORY")[0].childNodes[0].nodeValue + '" id="">'
+ '<div class="col-sm-4 col-lg-4 col-md-4"><div class="thumbnail img-hover">'
+ '<a class="fancybox" rel="group" href="' + records[i].getElementsByTagName("BIGIMAGE")[0].childNodes[0].nodeValue + '" title="' + records[i].getElementsByTagName("SHORTDESCRIPTION")[0].childNodes[0].nodeValue + '">'
+ '<img class="product-image" src="' + records[i].getElementsByTagName("IMAGE")[0].childNodes[0].nodeValue + '" alt="' + records[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue + '" />'
+ '<div class="caption">'
+ '<h4>' + records[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue + '</h4>'
+ '<p>' + records[i].getElementsByTagName("SHORTDESCRIPTION")[0].childNodes[0].nodeValue + '</p>'
+ '</div>'
+ "</a></div></div></article>";
} else {
xmlContent += '<article class="post all ' + records[i].getElementsByTagName("CATEGORY")[0].childNodes[0].nodeValue + '" id="">'
+ '<div class="col-sm-4 col-lg-4 col-md-4"><div class="thumbnail img-hover">'
+ '<a class="fancybox" rel="group" href="' + records[i].getElementsByTagName("BIGIMAGE")[0].childNodes[0].nodeValue + '" title="' + records[i].getElementsByTagName("SHORTDESCRIPTION")[0].childNodes[0].nodeValue + '">'
+ '<img class="product-image" src="/images/Products/no-preview.jpg" alt="No Preview Available" />'
+ '<div class="caption">'
+ '<h4>' + records[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue + '</h4>'
+ '<p>' + records[i].getElementsByTagName("SHORTDESCRIPTION")[0].childNodes[0].nodeValue + '</p>'
+ '</div>'
+ "</a></div></div></article>";
}
}
xmlContent += "</div>";
content.innerHTML = xmlContent;
var paginationContent = '<nav><ul class="pagination">';
if (page > 1) {
paginationContent += '<li>';
paginationContent += '<span aria-hidden="true">«</span>';
paginationContent += '</li>';
} else {
paginationContent += '<li class="disabled">';
paginationContent += '<span aria-hidden="true">«</span>';
paginationContent += '</li>'
}
var prevPosition = page - 3;
var nextPosition = page + 3;
for (var i = 1; i <= maxPages; i++) {
if (i != page) {
if (i >= prevPosition && i <= nextPosition) {
var linkToPage = i == prevPosition ? 1 : i == nextPosition ? maxPages : i;
var linkText = i == prevPosition ? "..." : i == nextPosition ? "..." : i;
paginationContent += "<li>";
paginationContent += '' + linkText + '';
paginationContent += "</li>";
}
} else {
paginationContent += "<li class='active'>";
paginationContent += '' + i + '';
paginationContent += "</li>";
}
}
var next = page + 1;
if (next <= maxPages) {
paginationContent += '<li>';
paginationContent += '<span aria-hidden="true">»</span>';
paginationContent += '</li>';
} else {
paginationContent += '<li class="disabled">';
paginationContent += '<span aria-hidden="true">»</span>';
paginationContent += '</li>';
}
paginationContent += '</ul></nav>';
pagination.innerHTML = paginationContent;
}
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", xmlUrl, false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
records = xmlDoc.getElementsByTagName(xmlNode);
records = Array.prototype.slice.call(records).sort(function () {
return Math.random() > 0.5 ? 1 : -1
});
paganation(1);
If we imagine that records was of length 18, then for the second page, you would have:
fromItem - 12
nextMaxItem - 24
You are iterating i from fromItem to nextMaxItem, but as soon as you go past i = 18, you've gone past the end of records. You need to make sure that doesn't happen. You need to ensure that you don't iterate past the end of your array:
var max = Math.min(nextMaxItem, records.length);
for (var i = fromItem; i < max; i++) {
....
}

Categories

Resources