Images loading very slowly in Fancybox even though I am preloading all of them (FancyApps2) - image

I have a slide show with bet 20 - 40 images, but there is a significant delay before each image loads even though I've set them all to preload (I recently increased it to preload: '40'). What can I do to improve this?
The settings for the slideshow are:
$(function () {
$('.fancybox').fancybox({
autoResize: true,
autoCenter: true,
scrolling: 'no',
preload: '40',
helpers: {
overlay: {
closeClick: false
},
},
});
I'm using it in conjunction with this function:
function manipulateDOM1() {
changeObjectsTrendy();
NextImageTrendy();
}
function changeObjectsTrendy() {
document.getElementById("questionTrendy").innerHTML = textTrendy[textTrendyNumber];
}
function NextImageTrendy() {
if (imgTrendyNumber < NumberOfTrendyImages)
{
imgTrendyNumber++;
document.images["trendy"].src = trendy[imgTrendyNumber];
document.images["trendyControl"].src = trendyControl[imgTrendyNumber];
textTrendyNumber++;
document.getElementById["questionTrendy"].innerHTML = textTrendy[textTrendyNumber];
}

Problem solved :-D
I just saw that there had been a recent update to the js for the fancybox slideshow, and thankfully that's made a huge difference (there's now only a marginal delay) :-)

Related

Squareup not loading iframes for Waterfox/IE11, Silent Error

I've confirmed that Square's code now works with pages served as application/xhtml+xml and with the exact same code Chrome works though Waterfox (and Firefox) do not load the iframes for the form fields. I've verified this in the DOM (they're not hidden, the original placeholder elements are still there).
Chrome requests the f.js file, Gecko browsers do not.
The placeholder elements that the iframe elements are supposed to replace are still in the DOM.
There are no error messages in the developer consoles in Waterfox 56, Firefox 64, Chrome 71 or Opera 12.1.
I've disabled prototypes for testing.
The browsers yield the same results for local and live testing.
The var sqPaymentForm = new SqPaymentForm(...); object is different for Gecko browsers.
What Gecko has for sqPaymentForm:
_handleDomContentLoaded
clientController
env
errorLogger
options
What Gecko does not have for sqPaymentForm:
build
_handleDomContentLoaded
Ironically I have limited access to IE11. I won't have time to setup the Mac until later on Friday mid-afternoon. Here are a couple cropped screenshots:
Firefox 56
IE 11
Here is the sqPaymentForm object (with obvious basic obfuscation):
var sqPaymentForm = new SqPaymentForm(
{
applicationId: 'sandbox-abc',
locationId: 'CBASEE123',
applePay: {elementId: 'sq-apple-pay'},
callbacks:
{
methodsSupported: function (methods)
{
if (methods.applePay && methods.applePay === true) {var element = document.getElementById('pay-button-area'); element.style.display = 'block';}
},
cardNonceResponseReceived: function(errors, nonce, cardData)
{
if (errors)
{
var errorDiv = document.getElementById('errors');
errorDiv.innerHTML = '';
errors.forEach(function(error) {var p = document.createElement('p'); p.innerHTML = error.message; errorDiv.appendChild(p);});
}
else
{
id_('card-nonce-submit').setAttribute('disabled','true');
id_('card_brand').value = cardData.card_brand;
id_('cc_end').value = cardData.last_4;
id_('cc_month').value = cardData.exp_month;
id_('cc_year').value = cardData.exp_year;
id_('zip').value = cardData.billing_postal_code;
document.getElementById('card-nonce').value = nonce;
payment_submit();
}
},
unsupportedBrowserDetected: function() {console.log('Error: unsupported browser.');},
createPaymentRequest: function ()
{
return {currencyCode: 'USD', countryCode: 'US', requestShippingAddress: false, total: {amount: '1.00', label: 'JAB Creations', pending: false},lineItems: [{amount: '1.00', label: 'Subtotal', pending: false},{amount: '0.00', label: 'Tax', pending: false}]};
},
},
cardNumber: {elementId: 'sq-card-number', placeholder: '0000 0000 0000 0000'},
cvv: {elementId: 'sq-cvv', placeholder: 'CVV'},
env: {},
excludeCanvas: {},
expirationDate: {elementId: 'sq-expiration-date', placeholder: 'MM/YY'},
inputClass: 'sq-input',
inputStyles: [
// Because this object provides no value for mediaMaxWidth or mediaMinWidth, these styles apply for screens of all sizes, unless overridden by another/ input style below.
{
backgroundColor: 'transparent',
color: ($('input[type="text"]').length > 0) ? window.getComputedStyle($('input[type="text"]')[0]).getPropertyValue('color') : '#fff',
fontFamily: 'sans-serif',//localStorage.getItem('input_style_font-family')
fontSize: '18px',//localStorage.getItem('input_style_font-size'),
fontWeight: 'bold',//localStorage.getItem('input_style_font-weight')
lineHeight: '18px',//localStorage.getItem('input_style_line-height'),
padding: '0'
},
// These styles are applied to inputs ONLY when the screen width is 400px
// or smaller. Note that because it doesn't specify a value for padding,
// the padding value in the previous object is preserved.
{
mediaMaxWidth: '400px',
fontSize: '48px',
lineHeight: '18px'
}],
maxTouchPoints: {},
inputEventReceived: function(inputEvent)
{
switch (inputEvent.eventType)
{
case 'focusClassAdded':
// Handle as desired
console.log(document.getElementsByClassName('sq-input--focus')[0]);
break;
case 'focusClassRemoved':
// Handle as desired
console.log(document.getElementsByClassName('sq-input--focus')[0]);
break;
case 'errorClassAdded':
// Handle as desired
break;
case 'errorClassRemoved':
// Handle as desired
break;
case 'cardBrandChanged':
// Handle as desired
break;
case 'postalCodeChanged':
// Handle as desired
break;
}
},
postalCode: {elementId: 'sq-postal-code', placeholder: 'Postal Code'}
});
How do I get the other browsers to load the iframe form fields? This certainly seems like a bug and I'm happy to report back any information that would help with troubleshooting.
Update 1
Running for (i in SqPaymentForm) {console.log('SqPaymentForm.'+i);} reveals the SqPaymentForm object in a different light. The SqPaymentForm.isSupportedBrowser function returns f() (from the only (JavaScript) request from the Square server) however the other browsers return the following:
SqPaymentForm.isSupportedBrowser
()
​length: 0
​name: "bound "
​<prototype>: function ()
I'm focusing my efforts on determining how browsers are "supported" by the convolutedly minimized code from Square.
Update 2
The SqPaymentForm.isSupportedBrowser() function returns true in Chrome and Waterfox. Going off of this documentation (https://docs.connect.squareup.com/payments/sqpaymentform/setup#step-4-render-sqpaymentform) I receive the following error:
paymentForm is not defined.
There is some ambiguity in the troubleshooting I did though after roughly an hour I decided to use setTimeout:
setTimeout(function()
{
sqPaymentForm.build();
sqPaymentForm.recalculateSize();
},2000);
...and it worked. So apparently either the Square developers specifically test with Chrome and/or Chrome will either wait until the method exists and execute it or it's load-related timing is somehow better.
So I would like to now ask: how do I adjust my code to not require having to rely on setTimeout?

Export to PDF increase number of items per page

I have a grid control which I wish to export the content of. Upon initialisation, the pageSize attribute is set to 10 items however I want to increase the number of items per page during exportToPDF.
I have tried to modify the pageSize of the dataSource prior to carrying out the export but this seems to have no effect on the end product.
var grid = $("#grid").data("kendoGrid");
var filter = grid.dataSource.filter;
grid.dataSource.query({
filter: filter,
pageSize: 20, // has no effect on the exported PDF
page: 1,
group: [{
field: "groupField1",
dir: "asc"
}, {
field: "groupField2",
dir: "asc"
}, {
field: "groupField3",
dir: "asc"
}]
});
var progress = $.Deferred();
grid._drawPDF(progress)
.then(function (root) {
return kendo.drawing.exportPDF(root, { forcePageBreak: ".page-break", multiPage: true });
})
.done(function (dataURI) {
// ... do some manual manipulation of dataURI
kendo.saveAs({
dataURI: manipualtedDataURI
});
progress.resolve();
Is there something I am missing so I can display more items on each page of the PDF export?
EDIT
Including my grid definition with the pdfExport function suggested by the below answer (which never gets called):
var grid = $("#reportGrid").kendoGrid({
pdf: {
allPages: true,
avoidLinks: true,
repeatHeaders: true,
template: kendo.template($("#page-template").html()),
scale: 0.7,
margin: { top: "2.5cm", right: "1cm", bottom: "1.5cm", left: "1cm" },
paperSize: "A4",
landscape: true
},
// *this function is not getting called*
pdfExport: function(e) {
e.sender.dataSource.pageSize(10);
e.promise.done(function() {
e.sender.dataSource.pageSize(20);
});
},
toolbar: kendo.template($("#template").html()),
...
});
Note: A template is used to include a header / footer on each page of the PDF export.
Another note: 'Manual manipulation of dataURI' includes going out to the server to perform a merge with another PDF file, so I cannot use the default export via the grid :(
EDIT 2
I have extended the Dojo example from #R.K.Saini's answer to use the method by which I need to generate the PDF export (as per original post).
The snippet logs the URI of the grid being exported and when the pdfExport function is called. As you will see, when using the built in grid 'Export to PDF' button, the pdfExport function is triggered but when using the additional button below the grid, it is not.
You can use pdfExport event to change page size of your grid datasource before pdf export started and then when the export finish you just need to revert back the previous page size.
The call back function of this event receive grid instance as e.sender and and a promise as e.promise which can be used to set back the page size when exporting finish.
For more info check http://docs.telerik.com/kendo-ui/api/javascript/ui/grid#events-pdfExport
$("#grid").kendoGrid({
dataSource: dataSource,
pdf: {
allPages: true
},
pdfExport: function(e) {
e.sender.dataSource.pageSize(10);
e.promise.done(function() {
e.sender.dataSource.pageSize(20);
});
},
...
//Other configguration
});
Here is a working demo http://dojo.telerik.com/UzOXO
Edit
You can also change grid page size in your custom export function just change grid page size before calling _drawPdf() function and change it back when done.
$("#btnPdfExport").kendoButton({
click: function () {
var grid = $("#grid").data("kendoGrid");
var progress = $.Deferred();
// Change grid datasource pagesize before calling _drawPDF
grid.dataSource.pageSize(20);
grid._drawPDF(progress)
.then(function (root) {
return kendo.drawing.exportPDF(root, { forcePageBreak: ".page-break", multiPage: true });
})
.done(function (dataURI) {
console.log("Exporting " + dataURI);
kendo.saveAs({
dataURI: dataURI,
fileName: "export.pdf"
});
progress.resolve();
// Change grid datasource pagesize when done
grid.dataSource.pageSize(10);
});
}
});
Check Update DOJO here http://dojo.telerik.com/UzOXO/8

jQuery UI, AJAX and CKEditor - CKEditor only loads the first time

I'm having an issue similar to the issues reported both here and here, with a only a few changes in how my form data is loaded.
The solution provided in the second link seemingly resolves my issue, but removing the show/hide scaling effects should not be required in order for CKEditor to instantiate properly. There's bound to be a much better alternative to resolving this conflict.
My issue:
When I open my page, and click the edit button, a jQueryUI Dialog pops up, loads its data via ajax, and then I attempt to replace the textarea added to the dialog with a CKEditor instance. The first time I load the page, the dialog works without a hitch. I'm able to modify the data within the editor, save my form data, and get on with life. However, if I close the dialog, then open it again, the editor is no longer enabled. The buttons still have hover effects, and are clickable, but do nothing. The text area of the editor is disabled and set to "style: visibility: hidden; display: none;". Nearly all the information I can find regarding this issue is from many years ago, and the fixes involve using functions/techniques that no longer exist or are applicable.
Control Flow
I open the page containing a text link 'Edit Update', which calls my Javascript function openEditTicketUpdateDialog.
function openEditTicketUpdateDialog(tup_id, url)
{
simplePost(null, url, new Callback
(
function onSuccess(data)
{
$('#editticketupdatedialog').dialog('option', 'buttons',
[
{
text: 'Save Edits',
click: function()
{
// Save the Update info
var formData = {
tup_update: CKEDITOR.instances.tup_update_edit.getData(),
tup_internal: +$('#tup_internal_edit').is(":checked"),
tup_important: +$('#tup_important_edit').is(":checked")
};
simplePost(formData, data['submitRoute'], new Callback
(
function onSuccess(data)
{
$('#update-' + tup_id).html(data.input['tup_update']);
$('#updateflags-' + tup_id).html(data.flags);
$('#editticketupdatedialog').dialog('close');
},
function onFail(errors)
{
console.log(errors);
}
));
}
},
{
text: 'Cancel',
click: function()
{
$(this).dialog("close");
}
}
]);
$('#editticketupdatedialog').dialog('option', 'title', data['title']);
$('#editticketupdatedialog').html(data['view']);
$('#editticketupdatedialog').dialog('open');
destroyEditor('tup_update_edit');
console.log('CKEDITOR.status: ' + CKEDITOR.status);
createEditor('tup_update_edit');
},
function onFail(errors)
{
console.log(errors);
}
));
}
This function uses three helper functions, simplePost, destroyEditor and createEditor.
function simplePost(data, url, callback)
{
post(data, url, true, false, callback);
}
function createEditor(name)
{
console.log('Create editor: ' + name);
console.log('Current Instance: ');
console.log(CKEDITOR.instances.name);
if (CKEDITOR.status == 'loaded')
{
CKEDITOR.replace(name,
{
customConfig: '/js/ckeditor/custom/configurations/standard_config.js'
});
}
else
{
CKEDITOR.on('load', createEditor(name));
CKEDITOR.loadFullCore && CKEDITOR.loadFullCore();
}
console.log('After instance created: ');
var instance = CKEDITOR.instances.name;
console.log(instance);
}
function destroyEditor(name)
{
console.log('Destroy editor: ' + name);
console.log('Current Instance: ');
console.log(CKEDITOR.instances.name);
if (CKEDITOR.instances.name)
{
console.log('Instance exists - destroying...');
CKEDITOR.instances.name.destroy();
$('#' + name).off().remove();
}
console.log('After instance removed: ');
var instance = CKEDITOR.instances.name;
console.log(instance);
}
This method of creating a CKEditor instance was gathered from here. This method of destroying a CKEditor instance was gathered from here.
As you can see, openEditTicketUpdateDialog fires an AJAX call to my getEditUpdateForm function through Laravel routes.
public function getEditUpdateForm($tup_id, $update_number)
{
$update = Update::find($tup_id);
$data = [
'title' => 'Editing update #' . $update_number . ' of ticket #' . $update->tup_ticket,
'view' => View::make('tickets.ticketupdate-edit')
->with('update', $update)
->render(),
'submitRoute' => route('tickets/update/submit', $tup_id)
];
return Response::json(array('status' => 1, 'data' => $data));
}
From here, a status of 1 is returned, and the onSuccess function is called. I've attempted to add the create/delete calls before the $('#editticketupdatedialog').dialog('open'); call, but to no avail. I've also tried multiple other solutions that I've found surfacing, which involve hacked implementations of jQueryUI's Dialog functions and attributes: _allowInteraction and moveToTop. I was originally successful in resolving this issue the first time it arose by calling this function before doing a CKEDITOR.replace:
function enableCKEditorInDialog()
{
$.widget( "ui.dialog", $.ui.dialog, {
/**
* jQuery UI v1.11+ fix to accommodate CKEditor (and other iframed content) inside a dialog
* #see http://bugs.jqueryui.com/ticket/9087
* #see http://dev.ckeditor.com/ticket/10269
*/
_allowInteraction: function( event ) {
return this._super( event ) ||
// addresses general interaction issues with iframes inside a dialog
event.target.ownerDocument !== this.document[ 0 ] ||
// addresses interaction issues with CKEditor's dialog windows and iframe-based dropdowns in IE
!!$( event.target ).closest( ".cke_dialog, .cke_dialog_background_cover, .cke" ).length;
}
});
}
After updating to Laravel 5, and making a few other changes serverside, this fix no longer works. I have been successful in resolving my issue by removing the show/hide properties from my dialog. I would very much prefer not to have to remove these properties, as half the reasoning for having the dialog is the aesthetics of an animation. Here is my dialog initialization.
$('#editticketupdatedialog').dialog({
modal: true,
draggable: false,
minWidth: 722,
autoOpen: false,
show:
{
effect: "scale",
duration: 200
},
hide:
{
effect: "scale",
duration: 200
},
closeOnEscape: true
});
When I have these animations enabled, the first time I use the dialog, it works perfectly. The second time, I receive the error TypeError: this.getWindow(...).$ is undefined - ckeditor.js:83:18 in the JS console, which refers to this line:
function(a)
{
var d = this.getWindow().$.getComputedStyle(this.$,null);
return d ? d.getPropertyValue(a) : ""
}
Recap
My main goal here is to find a fix for this issue, without having to remove the jQueryUI Dialog animation. I am unsure whom to point fingers at, as I really can't determine if the issue lies in CKEditor, jQueryUI or my implementation.
I finally found a solution that works in my case. losnir updated the outdated solution to a post here, and adding the open function to my dialog initialization resolved my issue.
My initialization is as follows:
$('#editticketupdatedialog').dialog({
modal: true,
draggable: false,
minWidth: 722,
autoOpen: false,
show:
{
effect: "scale",
duration: 200
},
hide:
{
effect: "scale",
duration: 200
},
closeOnEscape: true,
open: function()
{
$(this).parent().promise().done(function ()
{
destroyEditor('tup_update_edit');
console.log('CKEDITOR.status: ' + CKEDITOR.status);
createEditor('tup_update_edit');
});
}
});

CKEditor toolbar close button right align

I want to add a close a button in CK Editor (v4.4) and want to align it right, below screen shot shows the end product.
With the help of documentation from CKEditor website I was able to create a simple close plugin. With the help of little jQuery hack I am able align it right but if possible I would like to align it using standard toolbar creation approach rather then below hack.
Current working hack
<script>
$(document).ready(function () {
var rteComment = CKEDITOR.replace("txtPluginDemo", {
toolbar: [
['NumberedList', '-', 'Image'],
['Save'],
['CKClose'],
],
toolbarCanCollapse: false,
allowedContent: 'p img ol br',
disallowedContent: 'script',
extraAllowedContent: 'img[*]{*}(*)',
extraPlugins: 'ckclose',
image_previewText: "Image preview will be displayed here.",
disableNativeSpellChecker: false,
//If true <p></p> will be converted to <p>&nbsp,</p>
fillEmptyBlocks: true,
removePlugins: 'contextmenu,liststyle,tabletools',
skin: 'moonocolor',
});
rteComment.on("close", function (evt) {
alert("Ok time to close it.");
return true;
});
rteComment.on("instanceReady", function (evt) {
//THIS IS HACK
$(".cke_button__ckclose").closest(".cke_toolbar").css({ "float": "right" });
});
})
</script>
I am hoping that there will be some option in the below code which will let me specify the my css class here.
CKEDITOR.plugins.add('ckclose', {
// Register the icons. They must match command names.
icons: 'ckclose',
// The plugin initialization logic goes inside this method.
init: function (editor) {
// Define an editor command that inserts a timestamp.
editor.addCommand('closeEditor', {
// Define the function that will be fired when the command is executed.
exec: function (editor) {
if (editor.fire("close")) {
editor.destroy();
}
}
});
// Create the toolbar button that executes the above command.
editor.ui.addButton('CKClose', {
label: 'Discard changes and close the editor',
command: 'closeEditor',
toolbar: 'insert'
});
}
});
Below image is the Inspect Element View from Firefox.
I got help from the above answer slightly change the code its worked for me
CKEDITOR.on("instanceReady", function (evt) {
$(".cke_button__custom").closest(".cke_toolbar").css({ "float": "right" });
});
"custom" is my button name. Thank you,
You can put this piece
rteComment.on("instanceReady", function (evt) {
$(".cke_button__ckclose").closest(".cke_toolbar").css({ "float": "right" });
});
rignt inside
init: function( editor ) {
(e.g., before its closing bracket). That should be enough.
Also, you don't need to put initialization info in a SCRIPT tag of your main file. It can be cleaner to use config.js
http://docs.ckeditor.com/#!/guide/dev_configuration
Also, see an interesting example of a plugin here:
How to add an ajax save button with loading gif to CKeditor 4.2.1. [Working Sample Plugin]

Kendo grid change indicator and cancel not working

I'm new to Kendo and the Kendo grid but I'm trying to learn how to use the master detail Kendo grid where the detail grid is supposed to support batch editing. The data is available in a local JavaScript object.
This jsFiddle demonstrates the problems I'm seeing.
Here's how the grid is being created - see the jsFiddle for the complete snippet -
$("#grid").kendoGrid({
dataSource: items,
detailInit: createDetail,
columns: [
{ field: "Item", width: "200px" },
]
});
function createDetail(e) {
$("<div/>")
.appendTo(e.detailCell)
.kendoGrid({
dataSource: {
batch:true,
transport: {
read: function (options) {
options.success(e.data.SubItems);
}
}
},
editable:true,
pageable:true,
toolbar: ["save", "cancel"],
columns: [
{ field: "SubItem", title: "Sub Item", width: 200 },
{ field: "Heading1", title: "Heading 1", width: 100 }
]
});
}
When you edit an item in the grid and click to the next cell, the details grid automatically collapses not matter where I click, even in an adjacent cell. When I open it again, I don't see the change indicator in the cell (red notch) but the new value is there.
If I were to hook up the save to an ajax call, Kendo sends the right detail item(s) that were edited.
Nothing happens when I click cancel changes.
How do I get the grid to not collapse and see the change indicators ?
How do I get canceling of changes to work correctly ?
[Update] - Further investigation reveals that if I use an older Kendo version 2011.3.1129 , this works as expected. But if I use the newer 2012.3.1114, it doesn't. Dont know if this is a bug or a change in behavior.
After much effort, I found that the cause seems to be that the master grid is rebinding automatically causing the behavior I observed. I was able to get around this by handling the dataBinding event in the master grid and within that, checking if any of the detail datasources were dirty and if so, calling preventDefault.
Here are relevant code snippets :
dataBinding: function (e) {
if (masterGrid.AreChangesPending()) {
e.preventDefault();
}
}
AreChangesPending : function () {
var pendingChanges = false;
// I gave each detail div an id so that I can get a "handle" to it
$('div[id^="detail_"]').each(function (index) {
var dsrc = $(this).data("kendoGrid").dataSource;
$.each(dsrc._data, function () {
if (this.dirty == true || this.isNew()) {
pendingChanges = true;
}
});
// For some reason, Kendo did not detect new rows in the isNew()
// call above, hence the check below
if (dsrc._data.length != dsrc._total) {
pendingChanges = true;
}
});
return pendingChanges;
}

Resources