Fetching data in chunks - javascript

I have a carousel which I have built, which gets a list of products from my API and then each product is created as a slide in a carousel. This is all working perfectly.
When the current slide becomes active I download all of the images for that slide and populate the slide. This data also comes from the API.
What I want to do is have a speedier way to do this. At the moment I am loading these one at a time as they become "active". Ideally I want to be able to load 5 in straight away. So that the start of the array (0) is in the center of the loading array. Then when a user navigates left or right through the carousel I want to call in the next one forward or back.
So far my code is working so that when a slide is active it will have all images loaded, the code I have used for this is here:
module.carousel = (function(){
"use strict";
var exports = {};
exports.details = {};
exports.init = function (options) {
var defaultOptions = {
speed: 1500,
next: {},
back: {},
target: {}
};
if(options == null) options = {};
options = $.extend(defaultOptions, options);
exports.details.targetLength = options.target.children('li').length - 1;
exports.details.position = 0;
exports.details.products = options.target.children('li');
options.target.children('li:nth-child(' + (exports.details.position + 1) + ')').addClass('active');
exports.details.position += 1;
getMedia();
function removeActive() {
options.target.children('li.active').removeClass('active');
}
function addActive() {
options.target.children('li:nth-child(' + (exports.details.position) + ')').addClass('active');
}
function nextItem() {
if(exports.details.position >= exports.details.targetLength + 1) {
exports.details.position = 1;
} else {
exports.details.position += 1;
}
removeActive();
addActive();
getMedia();
}
function getMedia() {
var id = options.target.children('li.active').attr('data-id');
$.ajax({
url: "/beta/api/v1/watches/id/" + id + "/media",
dataType: "json",
async: false,
success: function(data) {
var mediaItems = "";
for(var x = 0, tot = data.length; x < tot; x++) {
mediaItems += "<div class='box'><img src='" + data[x] + "' class='intro-image'></div>";
}
$('#' + id + '_media').html(mediaItems);
}
});
}
function previousItem() {
if(exports.details.position === 1) {
exports.details.position = exports.details.targetLength + 1;
} else {
exports.details.position -= 1;
}
removeActive();
addActive();
getMedia();
}
$('html, body').on('swipeleft', function(event) {
event.stopPropagation();
nextItem();
});
$('html, body').on('swiperight', function(event) {
event.stopPropagation();
previousItem();
});
};
return exports;
}());
That is how my carousel works, and this is how I start it :
$(document).ready(function() {
$.getJSON("/beta/api/v1/watches", function(data) {
var productArray = [];
for(var i = 0, tot = data.length; i < tot; i++){
var productItem = "";
if(i === 0) {
productItem += "<li data-id='" + data[i].id + "' class='product active'>";
} else {
productItem += "<li data-id='" + data[i].id + "' class='product'>";
}
productItem += "<div class='product-header'><h3>"
+ data[i].name + "</h3><h3>" + data[i].case_finish
+ "</h3><h3>" + data[i].id + "</h3><h3>£" + data[i].price + "</h3></div>";
var product = data[i];
productItem += "<div id='" + data[i].id + "_media'></div>";
productItem += "</li>";
productArray.push(productItem);
}
$('#carousel').html(productArray);
$(document).on('swipeleft swiperight', function(event) {
event.stopImmediatePropagation();
});
module.carousel.init({
target: $('#carousel'),
next: $('#next'),
back: $('#back')
});
});
});

Related

Product Loop Problem in Javascript Categories

We made a category structure where products can be listed without changing the page. However, instead of stopping when the products in the category are exhausted, it first brings the products in the category, and then continues to pull products from another unrelated category. We couldn't find where we went wrong.
loadFsk('{{baseurl}}index.php?route=product/category&path='+selecteds.join('_'));
$.get('{{baseurl}}index.php?route=common/fskcats/search&catid=' + did, function (json) {
for (var i = (step); i < 6; i++) {
$('.seller-subcategories.step' + (i + 1)).remove();
}
if (step == 0) {
$('#catappends').html('');
}
if (json) {
var html = '<div class="seller-subcategories step' + (step + 1) + '"><ul class="seller-sub-ul">';
$(json['categorys']).each(function (k, v) {
html += '<li class="seller-sub-li"><a class="catjs" data-step="'
+ (step + 1) + '" data-id="' + v['category_id'] + '">' + v['name'] + '</a></li>'
});
html += '</ul></div>';
$('#catappends').append(html);
}
}, 'JSON');
});
function loadFsk(url,isnew=false){
$.ajax({
url: url,
dataType:'HTML',
success: function(htmlData){
if (isnew) {
$('.main-products-wrapper .main-products.product-grid').html($(htmlData).find('.product-grid .product-layout'));
}else{
$('.main-products-wrapper .main-products.product-grid').html($(htmlData).find('.main-products-wrapper .main-products.product-grid .product-layout'));
}
$('.pagination-results').html($(htmlData).find('.pagination-results'));
}
});
Journal.infiniteScrollInstance = $.ias({
container: '.main-products',
item: '.product-layout',
pagination: '.pagination-results',
next: '.pagination a.next'
});
}
window.addEventListener('load', () => {
let el = document.querySelector('.seller-horizontal .seller-ul .seller-li.active');
if(el){
let left_value = el.offsetLeft - (window.innerWidth/2) + (el.offsetWidth/2);
el.parentNode.scrollTo({
left: left_value,
behaviour: 'smooth',
});
}
})

onclick in div not calling function

I have a problem where onclick in the code does not work, as the function does not run when clicking.
function kaka(x) {
$('.' + x).each(function() {
html += this.outerHTML;
});
$("#klasa").html(html);
alert(html);
}
tab = ciong.split("&");
dlu = tab.length;
tab = removeDuplicates(tab);
for (var i = 0; i <= dlu; i++) {
$("#linki").html($("#linki").html() + "<div onclick='kaka(\'" + tab[i] + "\');'> " + tab[i] + " </div>");
}

I have javascript code to view a news from RSS as a vertical list. I need help to move the list of topics as horizontal one by one, in one line

I have javascript code to view a news from RSS as a vertical list.
(function ($) {
$.fn.FeedEk = function (opt) {
var def = $.extend({
MaxCount: 5,
ShowDesc: true,
ShowPubDate: true,
DescCharacterLimit: 0,
TitleLinkTarget: "_blank",
DateFormat: "",
DateFormatLang:"en"
}, opt);
var id = $(this).attr("id"), i, s = "", dt;
$("#" + id).empty();
if (def.FeedUrl == undefined) return;
$("#" + id).append('<img src="loader.gif" />');
var YQLstr = 'SELECT channel.item FROM feednormalizer WHERE output="rss_2.0" AND url ="' + def.FeedUrl + '" LIMIT ' + def.MaxCount;
$.ajax({
url: "https://query.yahooapis.com/v1/public/yql?q=" + encodeURIComponent(YQLstr) + "&format=json&diagnostics=false&callback=?",
dataType: "json",
success: function (data) {
$("#" + id).empty();
if (!(data.query.results.rss instanceof Array)) {
data.query.results.rss = [data.query.results.rss];
}
$.each(data.query.results.rss, function (e, itm) {
s += '<li><div class="itemTitle"><a href="' + itm.channel.item.link + '" target="' + def.TitleLinkTarget + '" >' + itm.channel.item.title + '</a></div>';
if (def.ShowPubDate){
dt = new Date(itm.channel.item.pubDate);
s += '<div class="itemDate">';
if ($.trim(def.DateFormat).length > 0) {
try {
moment.lang(def.DateFormatLang);
s += moment(dt).format(def.DateFormat);
}
catch (e){s += dt.toLocaleDateString();}
}
else {
s += dt.toLocaleDateString();
}
s += '</div>';
}
if (def.ShowDesc) {
s += '<div class="itemContent">';
if (def.DescCharacterLimit > 0 && itm.channel.item.description.length > def.DescCharacterLimit) {
s += itm.channel.item.description.substring(0, def.DescCharacterLimit) + '...';
}
else {
s += itm.channel.item.description;
}
s += '</div>';
}
});
$("#" + id).append('<ul class="feedEkList">' + s + '</ul>');
}
});
};
})(jQuery);
I need help to move the list of topics as horizontal one by one, in one line. by used javascript code. this code display just 5 topics, which I need it, but I have problem to how can I movement it as horizontal.

How to convert the values in an array to strings and send to php?

I have a javascript file here.What it does is,when a user selects seats accordings to his preference in a theater layout,the selected seats are stored in an array named "seat".This code works fine until function where the selected seats are shown in a window alert.But from there onwards,the code doesn't seem to do anything.
After the above window alert, I've tried to serialize the above array and send it to the "confirm.php" file.But it does not show anything when echoed the seats.
Here is the js code.
<script type="text/javascript">
$(function () {
var settings = {
rows: 6,
cols: 15,
rowCssPrefix: 'row-',
colCssPrefix: 'col-',
seatWidth: 80,
seatHeight: 80,
seatCss: 'seat',
selectedSeatCss: 'selectedSeat',
selectingSeatCss: 'selectingSeat'
};
var init = function (reservedSeat) {
var seat = [], seatNo, className;
for (i = 0; i < settings.rows; i++) {
for (j = 0; j < settings.cols; j++) {
seatNo = (i + j * settings.rows + 1);
className = settings.seatCss + ' ' + settings.rowCssPrefix + i.toString() + ' ' + settings.colCssPrefix + j.toString();
if ($.isArray(reservedSeat) && $.inArray(seatNo, reservedSeat) != -1) {
className += ' ' + settings.selectedSeatCss;
}
seat.push('<li class="' + className + '"' +
'style="top:' + (i * settings.seatHeight).toString() + 'px;left:' + (j * settings.seatWidth).toString() + 'px">' +
'<a title="' + seatNo + '">' + seatNo + '</a>' +
'</li>');
}
}
$('#place').html(seat.join(''));
};
var jArray = <?= json_encode($seats) ?>;
init(jArray);
$('.' + settings.seatCss).click(function () {
if ($(this).hasClass(settings.selectedSeatCss)) {
alert('This seat is already reserved!');
} else {
$(this).toggleClass(settings.selectingSeatCss);
}
});
$('#btnShowNew').click(function () {
var seat = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) {
item = $(this).attr('title');
seat.push(item);
});
window.alert(seat);
});
$('#btnsubmit').click(function () {
var seat = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) {
item = $(this).attr('title');
seat.push(item);
var seatar = JSON.stringify(seat);
$.ajax({
method: "POST",
url: "confirm.php",
data: {data: seatar}
});
});
});
});
</script>
Can somebody help me figure it out what's wrong in here?
Please Add content type as json.
$.ajax({
method: "POST",
url: "confirm.php",
contentType: "application/json"
data: {data: seatar}
});
For testing you can print file_get_contents('php://input') as this works regardless of content type.

include json data in the load more button function

how do i include json data in the load more button function at
load more button : Jsfiddle example
var index = 1;
$(document).on("pagecreate", "#page1", function(){
$("#btnAdd").on("click", function(){
var allItems = '';
for (var i = 0; i < 100; i++) {
allItems += '<li><a href="javascript:showDetails(' + (index + i) + ')" >item number ' + (index + i) + '</a></li>';
}
index += 100;
$("#ListTemp").empty().append(allItems).listview("refresh");
var element = $("#ListTemp li").detach();
$("#ListDspQry").append(element);
});
});
My json url is : http://www.beritanisma.com/category/superlawak/?json=get_category_posts
been trying for days but it ended up showing no results, please help me masters, thank you..
var index = 0;
$(document).on("pagecreate", "#page1", function(){
$("#btnAdd").on("click", function(){
var url = "http://www.beritanisma.com/category/superlawak/?json=get_category_posts"
$.getJSON(url, function(data){
var allItems = '';
for (var i = 0; i < data.posts.length; i++) {
console.log(data.posts[i].url);
allItems += '<li><a href="javascript:showDetails(' + (index + i) + ')" >'+data.posts[i].url+'' + (index + i) + '</a></li>';
}
index += 100;
$("#ListTemp").empty().append(allItems).listview("refresh");
var element = $("#ListTemp li").detach();
$("#ListDspQry").append(element);
});
});
});

Categories