Jquery / Javascript: There is a NaN on my HTML - javascript

I am writing an HTML loop using javascript. It will loop through a series of images and display them with additional information. It appears that there is always a NaN showing on the HTML output as shown here.
Here is the javascript in question:
var caption = '<p></p>';
if($.isEmptyObject(data[i].caption) !== true)
{
caption = '<p class="caption" style="top:'+data[i].height+'px;">'+
data[i].caption +
'</p>';
}
var li = '<li data-uk-modal="{target:#modal-open-image}"'
+ 'class="open"'
+ 'image="'+ data[i].photo +'"'
+ 'caption_height="'+ data[i].height +'"'
+ 'caption="'+ data[i].caption +'">'
+ '<a href="#" class="uk-thumbnail uk-overlay-toggle">'
+ '<div class="uk-overlay">'
+ '<img src="'+ data[i].photo +'" width="250px"/>'
+ caption +
+ '<div class="uk-overlay-caption">'
+ '<p> Sender: ' + data[i].sender + '</p>'
+ '<p> Date: ' + data[i].date + '</p>'
+ '<p> limit: '+ data[i].limit + '</p>'
+ '<p> counter: ' + data[i].counter + '</p>'
+ '</div>'
+ '</div>'
+ '</a>'
+'</li>';
$photo.append(li);
I would think the problem would lie on the caption variable. the data[i] is an array of from a database query.
I need to check if there is something on the data[i].caption. I tried using length, but that doesn't work, so I check if the object exist. Though I am not sure if that works.
My question, is how to display properly check if the caption is empty, and if none it will not add anything on the var li.
Thanks.

You can code it in one line:
( (data && data[i] && data[i].caption) ? " your stuff " : "")
But pay attention that checking 'data[i].caption' in javascript means that: zero is false, empty string is false.
Furthermore if you referring a number you can add a condition using the method isNaN

Please use this one in place of the '+ caption +'
isNaN(data[i].caption) ? '' : data[i].caption
or if(isNaN(data[i].caption)==true){
//do somthing
}else{
//do somthing
}

Thanks for the feedback. I manage to gobble up the solutions you game me and I ended up with this.
var height = (data[i].height == null)?0:data[i].height;
var caption= (data[i].caption== null)?'':data[i].caption;
var li = '<li data-uk-modal="{target:\'#modal-open-image\'}"'
+ 'class="open"'
+ 'image="'+ data[i].photo +'"'
+ 'caption_height="'+ height +'"'
+ 'caption="'+ caption +'">'
+ '<a href="#" class="uk-thumbnail uk-overlay-toggle">'
+ '<div class="uk-overlay">'
+ '<img src="'+ data[i].photo +'" width="250px"/>'
+ '<p class="caption" style="top:' + height +'px;">'
+ caption
+ '</p>'
+ '<div class="uk-thumbnail-caption">'
+ '<p> Sender: ' + data[i].sender + '</p>'
+ '<p> Reciever: '+ data[i].reciever + '</p>'
+ '<p> Date: ' + data[i].date + '</p>'
+ '<p> limit: '+ data[i].limit + '</p>'
+ '</div>'
+ '</div>'
+ '</a>'
+'</li>';

Related

Appending data fetched by an AJAX call to an already existing list in UI & saving the data fetched to the already saved list in localstorage

I have a page in which I have to show list of data in UI through ajax & append the list data in html table save that list data into Local Storage with Jquery, My question is that I want to implement lazy load in UI such that user clicks a button (Click to view more list), and after clicking the button the ajax calls another list with limit & offset to show more list & append the new list below the existing list in UI and also save the data into local storage along with the existing data present.
My Ajax Call for List Data
var sendingData = {
limit: "50000",
offset: "0"
};
$.ajax({
type: 'POST',
url: "/Common/Item/getselleritems?SellerId=" + userid,
data: sendingData ,
crossDomain: true,
success: function (data)
{
localStorage.setItem("productCode", JSON.stringify(data));
},
error()
{
//Do something
}
});
``
My Html design Function
function showProducts()
{
var productsStorage = localStorage.getItem("productCode");
var products = JSON.parse(productsStorage);
var trHTML = '';
$("table tbody").html("");
$.each(products.Data, function (key, value)
{
trHTML += '<tr>'
+ '<td class="d-md-flex align-items-center">' + '<figure style="' + imgStyle + '"><a href="" title="Photo title" data-effect="mfp-zoom-in">' +
'<img src="' + imgSrc + '" alt="thumb" class="lazy"></a></figure>' +
'<div class="flex-md-column">' +
'<h4 class="package_name" id="itemdescription_' + value.Id + '" onclick = "packageDetails(\'' + value.Price + '\',\'' + value.Name + '\',\'' + value.Description
+ '\',\'' + itemTimeSlotType + '\',\'' + value.ServiceName + '\',\'' + value.PreparationTime + '\',\'' + value.Quantity + '\')" >' +
'<i class="icon_box-selected" style="' + style + '; margin-right:3px"></i>' +
value.Name + '</h4>' +
'<p>' + value.Description + '</p>' +
'<em>' + "Available In: " + itemTimeSlotType + '</em>' + '<br>' +
'<span class="stars_sellerItem" style="' + starStyle + '">' + value.FoodtestAvgRating + ' <i class="icon_star"> </i> ' +
'</span>' +
'</div>' +
'</td>' + '<td style="padding: 0.75rem 0 0.75rem 0;">' +
'<strong id="itemprice_' + value.Id + '">' +
'<i class="fa fa-inr" aria-hidden="true"></i>' + value.Price +
'</strong>' +
'</td>' +
'<td class="options">' +
'<div class="dropdown dropdown-options">' +
'<i class="icon_plus_alt2"></i>' +
'<div class="numbers-row number" id="item2_' + value.Id + '" data-id="' + value.Id + '">' +
'<input type="text" value="1" class="form-control" name="quantity" id="itemvalue_' + value.Id + '" onchange="getval(' + itemId + ');" readonly>' +
'<div class="inc button_inc plus">' + '+' + '</div><div class="dec button_inc minus">' + '-' + '</div>' + '</div>' +
'</td>' + '</tr>';
}
$("table tbody").append(trHTML);
}

How can I init accordion in Magento 2 on swatches, on product page

I want to make an accordion for the swatches on the product page.
The switches are built into the file Magento_Swatches/js/swatch-renderer.js
I did a mixin over the _RenderControls function and changed the html structure a bit compared to the original structure.
CODE JS (via mixin)
container.append(
'<div class="' + classes.attributeClass + ' ' + item.code + '" ' +
'attribute-code="' + item.code + '" ' +
'attribute-id="' + item.id + '">' +
label +
'<div class="init-accordion" >' +
'<div data-role="collapsible">' +
'<div class="title-accordion" data-role="trigger">titlu</div>' +
'</div>' +
'<div class="content-accordion" data-role="content">' +
'<div aria-activedescendant="" ' +
'tabindex="0" ' +
'aria-invalid="false" ' +
'aria-required="true" ' +
'role="listbox" ' + listLabel +
'class="' + classes.attributeOptionsWrapper + ' clearfix">' +
options + select +
'</div>' + input +
'</div>' +
'</div>' +
'</div>'
);
I did not put the whole function because it is very long, I only put the part that differs from the original.
I want to initialize an accordion (according to the Magento documentation) on this swatch structure.
The problem is that the accordion does not initialize because the switches are still loaded on the page.
In the template, I would initialize like this
CODE PHTML:
<script>
require(['jquery', 'domReady', 'accordion'], function($, domReady){
domReady(function(){
setTimeout(function(){
$(".init-accordion").accordion({
"active": [1, 2],
"collapsible": true,
"openedState": "active",
"multipleCollapsible": true
});
}, 3000);
});
})
</script>
I used setTimeout and it works, but I want without it.
Do you have any idea how I can do this?
Thank you!

Javascript - How to insert html template and use variables in it

I wonder how can I insert html template into a javascript function and use variables in it, like for example here, where I am creating html and inserting variables to it. I would like to know how can I make it cleaner and have a template in a separate file and then use it in the function.
{
source: autocomplete.sources.hits(videos, { hitsPerPage: 5 }),
displayKey: 'title',
templates: {
header: '<div class="aa-suggestions-category">Videos</div>',
suggestion: function(suggestion) {
return '<span>'
+ '<a href="/player/' + suggestion.id + '">'
+ '<div class="media">'
+ '<div class="media-left">'
+ '<img class="media-object" src="https://s3.eu-central-1.amazonaws.com/myUrl/' + suggestion.video_id + '_1.jpg">'
+ '</div>'
+ '<div class="media-body">'
+ '<p>' + suggestion._highlightResult.title.value + '<small><abbr class="timeago" title="' + suggestion.created_at + '">' + suggestion.created_at + '</abbr></small>' + '</p>'
+ '<small> ' + '</small>'
+ '</div>'
+ '</div>'
+ '</a>'
+'</span>';
}

Lightgallery plugin generating 3 copies of slides

I have a gallery loading images from an API then showing them with the lightgallery plugin.
After calling the lightbox in the correct location (see question here) I noticed the plugin is creating three slides for each photo.
There are 20 photos but it creates 60 slides.
Any thoughts on this? Anyone else run into something similar?
** Edit: Here is a CodePen with the page, error happing there: http://codepen.io/nathan-anderson/pen/GqXbvK
JS:
// ----------------------------------------------------------------//
// ---------------// Unsplash Photos //---------------//
// ----------------------------------------------------------------//
function displayPhotos(data) {
var photoData = '';
$.each(data, function (i, photo) {
photoData += '<a class="tile"' + 'data-sub-html="#' + photo.id + '"'+ 'data-src="' + photo.urls.regular + '">' + '<img alt class="photo" src="' + photo.urls.regular + '">' + '<div class="caption-box" id="' + photo.id + '">' + '<h1 class="photo-title">' + 'Photo By: ' + photo.user.name + '</h1>' + '<p class="photo-description"> Description: Awesome photo by ' + photo.user.name + ' (aka:' + '<a target="_blank" href="' + photo.links.html + '">' + photo.user.username + ')</a>' + ' So far this photo has ' + '<span>' + photo.likes + '</span>' + ' Likes.' + ' You can download this photo if you wish, it has a free <a target="_blank" href="https://unsplash.com/license"> Do whatever you want </a> license. <a target="_blank" href="' + photo.links.download + '"><i class="fa fa-download" aria-hidden="true"></i> </a> </p>' + '</div>' + '</a>';
});
// Putitng into HTML
$('#photoBox').html(photoData);
//--------//
// Calling Lightbox
//--------//
$('#photoBox').lightGallery({
selector: '.tile',
download: false,
counter: false,
zoom: false,
thumbnail: false,
mode: 'lg-fade'
});
} // End Displayphotos function
// Show popular photos on pageload
$.getJSON(unsplashAPI, popularPhotos, displayPhotos);
HTML:
<div class="content" id="photoBox"></div>
The issue was solved by separating the sections of code I wanted to generate within the function.
Here is the updated function code:
function displayPhotos(data) {
var photoData = '';
var photoInfo = '';
$.each(data, function(i, photo) {
photoData += '<a class="tile"' + 'data-sub-html="#' + photo.id + '"' + 'data-src="' + photo.urls.regular + '">' + '<img alt class="photo" src="' + photo.urls.regular + '">';
photoInfo += '<div class="caption-box" id="' + photo.id + '">' + '<h1 class="photo-title">' + 'Photo By: ' + photo.user.name + '</h1>' + '<p class="photo-description"> Description: Awesome photo by ' + photo.user.name + ' (aka:' + '<a target="_blank" href="' + photo.links.html + '">' + photo.user.username + ')</a>' + ' So far this photo has ' + '<span>' + photo.likes + '</span>' + ' Likes.' + ' You can download this photo if you wish, it has a free <a target="_blank" href="https://unsplash.com/license"> Do whatever you want </a> license. <a target="_blank" href="' + photo.links.download + '"><i class="fa fa-download" aria-hidden="true"></i> </a> </p>';
});
// Putitng into HTML
photoData += '</a>';
photoInfo += '</div>';
$('#photoBox').html(photoData + photoInfo);

Ajax JSON data and lightbox conflicts

I have a gallery setup with the lightbox plugin lightGallery
The gallery works perfect with static HTML. The problem arises when I dynamically grab API data and try to have the lightbox working on those items.
I can't seem to get another lightbox to both work with this function and load an HTML block from the page correctly (load the one that's been dynamically generated). This app does the correct HTML grabs, if I can get the conflict resolved.
Any initial thoughts? Anyone else run into anything similar?
JS:
//----------------------------------------------------------------//
//---------------// Calling Lightgallery //---------------//
//----------------------------------------------------------------//
$('#photoBox').lightGallery({
selector: '.tile',
download: false,
counter: false,
zoom: false,
thumbnail: false,
mode: 'lg-fade'
});
// ----------------------------------------------------------------//
// ---------------// Unsplash Photos //---------------//
// ----------------------------------------------------------------//
// Filter Difference based on button click
$('button').click(function () {
$('button').removeClass("active");
$(this).addClass("active");
var unsplashAPI = "#URL";
var order = $(this).text();
var sortOptions = {
order_by: order,
format: "json"
};
function displayPhotos(data) {
var photoData = '';
$.each(data, function (i, photo) {
photoData += '<a class="tile" data-src="' + photo.urls.regular + '">' + '<img alt class="photo" src="' + photo.urls.regular + '">' + '<div class="caption-box" id="' + photo.id + '">' + '<h1 class="photo-title">' + 'Photo By: ' + photo.user.name + '</h1>' + '<p class="photo-description"> Description: Awesome photo by ' + photo.user.name + ' aka: ' + photo.user.username + ' So far this photo has ' + '<span>' + photo.likes + '</span>' + ' Likes' + '</p>' + '</div>' + '</a>';
});
$('#photoBox').html(photoData);
}
$.getJSON(unsplashAPI, sortOptions, displayPhotos);
}); // End button
HTML:
<div class="content" id="photoBox"></div>
-- Thanks
Call the plugin after the data is appended to the page
function displayPhotos(data) {
var photoData = '';
$.each(data, function (i, photo) {
photoData += '<a class="tile" data-src="' + photo.urls.regular + '">' + '<img alt class="photo" src="' + photo.urls.regular + '">' + '<div class="caption-box" id="' + photo.id + '">' + '<h1 class="photo-title">' + 'Photo By: ' + photo.user.name + '</h1>' + '<p class="photo-description"> Description: Awesome photo by ' + photo.user.name + ' aka: ' + photo.user.username + ' So far this photo has ' + '<span>' + photo.likes + '</span>' + ' Likes' + '</p>' + '</div>' + '</a>';
});
$('#photoBox').html(photoData);
$('#photoBox').lightGallery({
selector: '.tile',
download: false,
counter: false,
zoom: false,
thumbnail: false,
mode: 'lg-fade'
});
}

Categories

Resources