how to virtualize ion-slides in ionic 4 - javascript

how to use the following method in ionic 4: https://swiperjs.com/api/#virtual
I tried to apply it according to the API documentation, but this code does not work. What am I doing wrong?
ngOnInit() {
//----------------------------------------------
var slides = document.querySelector("ion-slides");
// Optional parameters to pass to the swiper instance. See http://idangero.us/swiper/api/ for valid options.
slides.options = {
initialSlide: 1,
direction: "vertical",
speed: 150,
preloadImages: false,
lazy: true,
virtual: {
slides: (function() {
var slides = [];
for (var i = 0; i < 600; i += 1) {
slides.push(
'<ion-slide><img src="https://picsum.photos/600/600/?image=' +
(i + 1) +
'"/><p>' +
(i + 1) +
"</p></ion-slide>"
);
}
console.log(JSON.stringify(slides));
return slides;
}),
}
};
//----------------------------------------------
}

It looks like you have to initialize Swiper first
var mySwiper = new Swiper('.ion-slides');
can you try this here:
let mySwiper = new Swiper('.ion-slides', {
initialSlide: 1,
direction: "vertical",
speed: 150,
preloadImages: false,
lazy: true,
virtual: {
slides: (function() {
var slides = [];
for (var i = 0; i < 600; i += 1) {
slides.push(
'<ion-slide><img src="https://picsum.photos/600/600/?image=' +
(i + 1) +
'"/><p>' +
(i + 1) +
"</p></ion-slide>"
);
}
console.log(JSON.stringify(slides));
return slides;
})
}
});

Related

Where to put setInterval and clearInterval

I have a working slider. I would like to to autoplay the slides and stop the autoplay when user clicks the next or previous button.
I have tried to include setInterval-function but I am not sure how I should apply it in order to make it work. So far I did not manage to do this.
enter code here
var interleaveOffset = 0.2;
var swiperOptions = {
loop: true,
speed: 500,
grabCursor: true,
watchSlidesProgress: true,
mousewheelControl: true,
keyboardControl: true,
navigation: {
nextEl: ".swiper-button-next",
prevEl: ".swiper-button-prev"
},
on: {
progress: function() {
var swiper = this;
for (var i = 0; i < swiper.slides.length; i++) {
var slideProgress = swiper.slides[i].progress;
var innerOffset = swiper.width * interleaveOffset;
var innerTranslate = slideProgress * innerOffset;
swiper.slides[i].querySelector(".slide-inner").style.transform =
"translate3d(" + innerTranslate + "px, 0, 0)";
}
},
touchStart: function() {
var swiper = this;
for (var i = 0; i < swiper.slides.length; i++) {
swiper.slides[i].style.transition = "";
}
},
setTransition: function(speed) {
var swiper = this;
for (var i = 0; i < swiper.slides.length; i++) {
swiper.slides[i].style.transition = speed + "ms";
swiper.slides[i].querySelector(".slide-inner").style.transition =
speed + "ms";
}
}
}
};
var swiper = new Swiper(".swiper-container", swiperOptions);
I expect that slider plays the slides automatically and the autoplay stops when user clicks either next or previous button.
Use autoplay
autoplay: {
delay: 2500,
disableOnInteraction: true,
},
disableOnInteraction will disable autoplay when you will click on arrows.
From top of my head you can use something like this
let timer = null
const startSwiping = () => {
timer = setInterval(() => {
swiper.slideNext(100); // transition duration (ms) as argument
}, 500)
}
const stopSwiping = () => clearInterval(timer)
I did not try that but Swiper docs dont show any other option than swiper.slideNext(speed)

JavaScript in slider image

I have a slider on my e-commerce homepage but it is freeze .I need to change it after 3 second .... Thanks in advance.
function aweMainSlider() {
var e = $(".main-slider");
e.owlCarousel({
items: 1,
nav: !0,
dots: !0,
onInitialized: function() {
e.find(".owl-item").each(function() {
var e = $(this),
o = e.find(".main-slider-item"),
a = e.find(".main-slider-image > img");
o.length && a.length && (o.addClass("background"),
o.css("background-image", "url(" + a.attr("src") + ")"), a.css({
opacity: 0,
visibility: "hidden"
}))
})
}
})
}

Jqgrid frozen columns - can't get them to freeze unless I manually resize the grid

I have read every post I can find on Frozen columns in jqgrid. And have implemented the following code.
The result... when I go to my spreadsheet grid in my app the 3 cols are NOT frozen. BUt if I drag the little resize icon in the lower left ever so slightly then POP they 3 columns are now frozen.
Why doesn't it work when the spreadsheet is first drawn?
Here's the code:
var $grid = $("#list4");
var resizeColumnHeader = function () {
var rowHight, resizeSpanHeight,
// get the header row which contains
headerRow = $(this).closest("div.ui-jqgrid-view")
.find("table.ui-jqgrid-htable>thead>tr.ui-jqgrid-labels");
// reset column height
headerRow.find("span.ui-jqgrid-resize").each(function () {
this.style.height = '';
});
// increase the height of the resizing span
resizeSpanHeight = 'height: ' + headerRow.height() + 'px !important; cursor: col-resize;';
headerRow.find("span.ui-jqgrid-resize").each(function () {
this.style.cssText = resizeSpanHeight;
});
// set position of the dive with the column header text to the middle
rowHight = headerRow.height();
headerRow.find("div.ui-jqgrid-sortable").each(function () {
var $div = $(this);
$div.css('top', (rowHight - $div.outerHeight()) / 2 + 'px');
});
};
var fixPositionsOfFrozenDivs = function () {
var $rows;
if (this.grid === undefined) {
return;
}
if (this.grid.fbDiv !== undefined) {
$rows = $('>div>table.ui-jqgrid-btable>tbody>tr', this.grid.bDiv);
$('>table.ui-jqgrid-btable>tbody>tr', this.grid.fbDiv).each(function (i) {
var rowHight = $($rows[i]).height(), rowHightFrozen = $(this).height();
if ($(this).hasClass("jqgrow")) {
$(this).height(rowHight);
rowHightFrozen = $(this).height();
if (rowHight !== rowHightFrozen) {
$(this).height(rowHight + (rowHight - rowHightFrozen));
}
}
});
$(this.grid.fbDiv).height(this.grid.bDiv.clientHeight+1);
$(this.grid.fbDiv).css($(this.grid.bDiv).position());
}
if (this.grid.fhDiv !== undefined) {
$rows = $('>div>table.ui-jqgrid-htable>thead>tr', this.grid.hDiv);
$('>table.ui-jqgrid-htable>thead>tr', this.grid.fhDiv).each(function (i) {
var rowHight = $($rows[i]).height(), rowHightFrozen = $(this).height();
$(this).height(rowHight);
rowHightFrozen = $(this).height();
if (rowHight !== rowHightFrozen) {
$(this).height(rowHight + (rowHight - rowHightFrozen));
}
});
$(this.grid.fhDiv).height(this.grid.hDiv.clientHeight);
$(this.grid.fhDiv).css($(this.grid.hDiv).position());
}
};
var fixGboxHeight = function () {
var gviewHeight = $("#gview_" + $.jgrid.jqID(this.id)).outerHeight(),
pagerHeight = $(this.p.pager).outerHeight();
$("#gbox_" + $.jgrid.jqID(this.id)).height(gviewHeight + pagerHeight);
gviewHeight = $("#gview_" + $.jgrid.jqID(this.id)).outerHeight();
pagerHeight = $(this.p.pager).outerHeight();
$("#gbox_" + $.jgrid.jqID(this.id)).height(gviewHeight + pagerHeight);
};
$grid.jqGrid({
datatype: "local",
shrinkToFit:false,
autowidth:true,
height: 450,
hoverrows: true,
sortable: false,
colNames:[' <br> <br> <br> <br>Year',
' <br> <br> <br>Your<br>Age',
' <br> <br> <br>Spouse<br>Age',
'Your Annual<br>Job<br>Income',
'Spouse Annual<br>Job<br>Income'
colModel:[
{name:'year',index:'year', width:50, align:"center",sortable:false, sorttype:"int",classes:'spreadsheet_cell0', frozen:true},
{name:'age0',index:'age0', width:50, align:"center",sortable:false, sorttype:"int",frozen:true},
{name:'age1',index:'age1', width:50, align:"center",sortable:false, sorttype:"int",frozen:true},
{name:'salary0',index:'salary0', width:100, align:"right",sortable:false,sorttype:"float",formatter:'currency', formatoptions:{decimalSeparator:".", thousandsSeparator: ",", decimalPlaces: 0, prefix: "$"}},
{name:'salary1',index:'salary1', width:100, align:"right",sortable:false,sorttype:"float",formatter:'currency', formatoptions:{decimalSeparator:".", thousandsSeparator: ",", decimalPlaces: 0, prefix: "$"}}
],
multiselect: false,
rowNum:20,
rowList:[10,20],
altRows:false,
onSelectRow: function (id) {
if (id && id!=previous_row) {
previous_row=id;
}
},
loadComplete: function () {
fixPositionsOfFrozenDivs.call(this);
}
});
// ADD DATA TO THE GRID
addData();
$grid.jqGrid('gridResize', {
minWidth: 450,
stop: function () {
fixPositionsOfFrozenDivs.call(this);
fixGboxHeight.call(this);
}
});
$grid.bind("jqGridResizeStop", function () {
resizeColumnHeader.call(this);
fixPositionsOfFrozenDivs.call(this);
fixGboxHeight.call(this);
});
$(window).on("resize", function () {
// apply the fix an all grids on the page on resizing of the page
$("table.ui-jqgrid-btable").each(function () {
fixPositionsOfFrozenDivs.call(this);
//fixGboxHeight.call(this);
});
});
// after all that freeze the cols and fix the divs
resizeColumnHeader.call($grid[0]);
$grid.jqGrid('setFrozenColumns');
$grid.triggerHandler("jqGridAfterGridComplete");
fixPositionsOfFrozenDivs.call($grid[0]);

Showing Progress while Child row loads

Coming again with another question :)
This time I had a requirement to show some progress while Child rows are being loaded. Since there is an Api call which relatively takes little time to return data, I do want to show the some progress unless the user who clicks the parent row is totally unaware whether there is a call done to see its child rows.
What I have done:
I wrote a style sheet class which has a
loader-small.gif
image as this:
tr.loading td.details-control {
background: url('/Images/loader-small.gif') no-repeat center center;
}
and applied like this:
$('#accountManagerEarningsDataTable tbody').on('click', 'td.details-control', function () {
var tr = $(this).closest('tr');
var row = table.row(tr);
try {
if (row.child.isShown()) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
}
else {
//Calling the loading Class ------>
tr.addClass('loading');
// Open this row
var arrForTable1 = [];
var arrForTable2 = [];
totalBrokerage = 0;
totalRetailBrokerage = 0;
totalSelfServiceBrokerage = 0;
console.log('You selected: ' + row.data().AccountManagerID);
var settings = {
"columnDefs": [
{ targets: 1, align: "right", decimals: 0 },
{ targets: 2, align: "right", decimals: 0 },
{ targets: 3, align: "right", decimals: 0 },
{ targets: 4, align: "right", decimals: 2 },
{ targets: 5, align: "right", decimals: 2 }
]
};
//problems with asynchoronus call back
var response = organization_GetAccountManagerDetailEarningsAccountData(row.data(), purl2, pcontext);
if (response.success === "true") {
for (var i = 0; i < response.value.length; i++) {
for (var j = 0; j < response.value[i].Securities.length; j++) {
var itemRow2 = {};
itemRow2["Security ID"] = response.value[i].Securities[j].SecurityId;
itemRow2["Trades"] = response.value[i].Securities[j].Trades;
itemRow2["Buy Qty"] = response.value[i].Securities[j].BuyQuantity;
itemRow2["Sell Qty"] = response.value[i].Securities[j].SellQuantity;
itemRow2["Total Brkg"] = response.value[i].Securities[j].Effective_Brokerage;
itemRow2["Online Brkg"] = response.value[i].Securities[j].Online_Brokerage;
arrForTable2.push(itemRow2);
totalBrokerage = totalBrokerage + parseFloat(response.value[i].Securities[j].Effective_Brokerage);
totalSelfServiceBrokerage = totalSelfServiceBrokerage + parseFloat(response.value[i].Securities[j].Online_Brokerage);
}
totalBrokerage = Math.round(totalBrokerage * 100) / 100;
totalSelfServiceBrokerage = Math.round(totalSelfServiceBrokerage * 100) / 100;
totalRetailBrokerage = Math.round(totalRetailBrokerage * 100) / 100;
var itemRow1 = {};
itemRow1["Account ID"] = response.value[i].AccountId;
itemRow1["Account Name"] = response.value[i].AccountName;
itemRow1["..."] = '<div class="alert alert-info" role="alert">' + buildHtmlTable(arrForTable2, 'table2x' + j, settings) + '<p>Total Brokerage ' + numberWithCommas(totalBrokerage) + '</p></div>';
arrForTable1.push(itemRow1);
arrForTable2 = [];
totalBrokerage = 0;
totalRetailBrokerage = 0;
totalSelfServiceBrokerage = 0;
}
tr.removeClass('loading');
htmlTable1 = buildHtmlTable(arrForTable1, 'table1x' + i);
row.child(htmlTable1).show();
tr.addClass('shown');
}
else {
row.child('<table><tr><td>' + response.value[0].AccountId + '</td></tr></table>').show();
tr.addClass('shown');
};
}
} catch (e) {
console.log(e.message);
}
});
The Problem:
Firefox nicely shows the Progress image after the user clicks it, but Edge and Chrome does not show. Both browsers crossed this piece of code when I was debugging from developer tools of the respective browser.
Its browser compatible problem? Is there a solution for it? Help me please.
In case of chrome there is such an issue while showing the loading bar while making a server call. Please make the following changes where you are making the service call. First add the class loading to the table
tr.addClass('loading');
After that make the service call by giving a timeout function
setTimeout(function(){
var response = organization_GetAccountManagerDetailEarningsAccountData(row.data(), purl2, pcontext);
......
//Your service calls and response call backs
},1);
On providing a timeout (say 1ms), Chrome will get the time to bind the loading bar to DOM, In other case the DOM Object is not available to show the spinner.

Combining two control panels(AB) or toggle them (A) or (B)

I have two control panels; one is for the default draw features, the other for measure tools.
The problem is that since they are in different panels it is possible to run two controls simultaneously, one from each panel. (this didn't seem like much of a problem before, but I noticed that when the measure and default draw tools are activated together, they cancel out the line end function)
What I am trying to do is either place all controls in one panel and toggle them together or toggle the panels(e.g. when control from panel 1 is activated, deactivate all controls in panel 2)
Here is my code:
Default Controls Panel:
OpenLayers.Control.CustomNavToolbar = OpenLayers.Class(OpenLayers.Control.Panel,{
initialize: function(options){
OpenLayers.Control.Panel.prototype.initialize.apply(this, [options]);
this.addControls([
new OpenLayers.Control.Navigation({displayClass: 'olControlNavigation', zoomBoxEnabled:false}),
new OpenLayers.Control.DrawFeature(vlayer, OpenLayers.Handler.Point, {displayClass: 'olControlDrawPoint'}),
new OpenLayers.Control.DrawFeature(vlayer, OpenLayers.Handler.Path, {displayClass: 'olControlDrawPath'}),
new OpenLayers.Control.DrawFeature(vlayer, OpenLayers.Handler.Polygon, {displayClass: 'olControlDrawPolygon'}),
new OpenLayers.Control.ZoomBox({displayClass: 'olControlZoomBox', alwaysZoom:true})
])
this.displayClass = 'olControlCustomNavToolbar'
},
draw: function(){
var div = OpenLayers.Control.Panel.prototype.draw.apply(this, arguments);
this.defaultControl = this.controls[0];
return div;
}
});
var panel = new OpenLayers.Control.CustomNavToolbar({div:OpenLayers.Util.getElement('panel')});
map.addControl(panel);
Measure Controls Panel:
allControls = {
line: new OpenLayers.Control.Measure(OpenLayers.Handler.Path, {
persist: true,
handlerOptions: {
layerOptions: {
renderers: renderer,
styleMap: styleMap
}
},
textNodes: null,
callbacks:{
create:
function(){
this.textNodes = [];
// vlayer.destroyFeatures(vlayer.features);
mouseMovements = 0;
},
modify:
function(point, line){
if(mouseMovements++ < 5){
return;
}
var len = line.geometry.components.length;
var from = line.geometry.components[len -2];
var to = line.geometry.components[len -1];
var ls = new OpenLayers.Geometry.LineString([from, to]);
var dist = this.getBestLength(ls);
if(!dist[0]){
return;
}
var total = this.getBestLength(line.geometry);
var label = dist[0].toFixed(3) + " " + dist[1];
var textNode = this.textNodes[len -2] || null;
if(textNode && !textNode.layer){
this.textNodes.pop();
textNode = null;
}
if(!textNode){
var c = ls.getCentroid();
textNode = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(c.x, c.y), {}, {
label: "",
fontColor: "#800517",
fontSize: "13px",
fontFamily: "Tahoma",
fontWeight: "bold",
labelAlign: "cm"
});
this.textNodes.push(textNode);
vlayer.addFeatures([textNode]);
}
textNode.geometry.x = (from.x + to.x) / 2;
textNode.geometry.y = (from.y + to.y) / 2;
textNode.style.label = label;
textNode.layer.drawFeature(textNode);
this.events.triggerEvent("measuredynamic", {
measure: dist[0],
total: total[0],
units: dist[1],
order: 1,
geometry: ls
});
}
}
}),
polygon: new OpenLayers.Control.Measure(
OpenLayers.Handler.Polygon, {
persist: true,
immediate: true,
handlerOptions: {
layerOptions: {
renderers: renderer,
styleMap: styleMap
}
}
}
)
};
var control;
for(var key in allControls) {
control = allControls[key];
control.events.on({
"measure": handleMeasurements,
"measurepartial": handleMeasurements
});
map.addControl(control);
}
..and just for reference
function handleMeasurements(evt){
var geometry = evt.geometry;
var units = evt.units;
var order = evt.order;
var measure = evt.measure;
var element = document.getElementById('output');
var position = (map.getLonLatPxFromViewPortPx);
var out = "";
if(order == 1){
out += "Distance: " + measure.toFixed(3) + " " + units;
}
else{
out += "Area: " + measure.toFixed(3) + " " + units + "<sup>2</" + "sup>";
}
element.innerHTML = out;
}
function toggleControl(element){
vlayer.destroyFeatures(vlayer.features);
for(key in allControls){
var control = allControls[key];
if(element.value == key && element.click){
control.activate();
var label = document.getElementById('output');
var emptyOut = "";
label.innerHTML = emptyOut;
}
else{
control.deactivate();
}
}
}
Been looking for a way to do this and so far have not been able to find anything useful, if you could help me with some suggestions about how to go about this it would be very appreciated. Thanks
EDIT: I am not using GeoExt and am not considering using it. I'm looking for suggestions about how to go about this using only the OpenLayers 2.11 library. Thanks again.

Categories

Resources