Multi Progressbar with upload jquery - javascript

I have a bug with progressbar when I upload multiple files, and I can not find the problem: (
I upload multiple files, but file are:
1.jpg
2.jpg
3.jpg
4.jpg
example bug when dragging files
1.jpg / complete
1.jpg / complete
1.jpg / complete
1.jpg / complete
my progressbar has bugging and I can not find where is the problem..
my script :
(function ($) {
var body = document.body;
var h = $(document).height();
var u = {
message: 'Drag and drop file here..',
post_url: 'upload.php'
}
$.fn.dragme = function (uu) {
var t = this;
if (uu) $.extend(u, uu);
t.each(function () {
$(body).append("<div class='droparea' style='height: 100%;display:none;'><span class='message'>" + u.message + "</span></div>");
$('.message').css({
top: '50%',
color: '#F8F8F8',
margin: '45%',
position: 'relative'
});
$(t).on({
dragenter: function (d) {
d.preventDefault();
d.stopPropagation();
if ($('.droparea').length != 1) {
$('.droparea').css('display', 'block');
$('.message').css({
top: '50%',
color: '#F8F8F8',
margin: '45%',
position: 'relative'
});
}
console.log('dragEnter');
},
//---------------------------dragover basic ----------------------------------------//
dragover: function (d) {
d.preventDefault();
d.stopPropagation();
$('.droparea').css('display', 'block');
//console.log('dragover');
},
//---------------------------dragleave basic ----------------------------------------//
dragleave: function (d) {
d.preventDefault();
d.stopPropagation();
$('.droparea').on('dragleave', function (d) {
$('.droparea').remove();
});
}
});
//---------------------------drop add template ----------------------------------------//
this.addEventListener('drop', function (e) {
e.preventDefault();
e.stopPropagation();
$('.droparea').remove();
var files = e.dataTransfer.files;
var template = '<li class="file-preview" id="' + files.name + '">' +
'<div class="progress">' +
'<div class="progressbaru">cool</div>' +
'</div>' +
'</li>';
upload(files, $(this), 0); //upload 1 files
$('#container').append(template);
}, false);
});
//-------------------------------------------------------------------------------//
// function upload
//-------------------------------------------------------------------------------//
function upload(files, area, index) {
var file = files[index];
var xhr = new XMLHttpRequest();
var template = '<li class="file-preview" id="' + files.name + '">' +
'<div class="progress">' +
'<div class="progressbaru"></div>' +
'</div>' +
'</li>';
var formData = new FormData();
formData.append("file", files);
//-------------------------- load -----------------------------------------------//
xhr.addEventListener('load', function (e) {
if (index < files.length - 1) {
alert('here');
upload(files,area, index+1); // upload+1...
$('container').append(template);
console.log(e);
}
}, false);
//---------------------------progressbar----------------------------------------//
xhr.upload.addEventListener('progress',function(e){
if (e.lengthComputable) {
var pourcent = Math.round(e.loaded / e.total * 100);
$('.progressbaru').css('width', pourcent + "%");
console.log(e);
}
else {
alert("Failed to compute file upload length");
}
},false);
//---------------------------! end progressbar----------------------------------------//
xhr.open('post', u.post_url, true); //in real is post
//xhr.setRequestHeader("Content-Type", "multipart/form-data");
xhr.send(formData);
xhr.onreadystatechange = function (e) {
if (xhr.readyState == 4) {
console.log(['xhr upload complete', e]);
}
}
//console.log(formData);
}
}
})(jQuery);
$(document).ready(function () {
$('body').dragme({
});
});
simple html code:
<body>
<div id="list">
<ul id="container"></ul>
</div>
</body>
Any suggestions, would be very grateful. Thank you!
Update,
bug in video : http://www.youtube.com/watch?v=5B8P4kNFp_g

Related

fetch javascript input/output from google sheet

I have the code below on Apps script but keep getting 'ReferenceError: setInterval is not defined on line 17'. Not sure how to fix this but it does load when i use the scipt below in a cell in google sheets and set it up to output to another - it runs apart from that error. not sure if it's because i have it set up wrong or because google apps script doesn't like the code
function scart() {// ==UserScript==
setInterval(function() {
var possibleClasses = [".listenArtworkWrapper", ".listenInfo"],
sizes = { 't500x500': '500x500', 'original': 'original size' },
regexp = /t\d{3}x\d{3}/gi;
$('.modal__content:not(.appeared)')
.addClass('appeared')
.each(handleModal);
function handleModal() {
var imageURL;
for (var i = 0; i < possibleClasses.length; i++) {
if ($(possibleClasses[i] + " .image__full").length > 0) {
imageURL = $(possibleClasses[i] + " .image__full").css('background-image');
}
}
if (!imageURL) {
logError('No suitable selector found!');
} else {
imageURL = /url\("(.+)"\)/.exec(imageURL)[1];
}
$(".modal__content .image__full").parent().remove();
$(".modal__content .imageContent").append("<img style='width: 500px; height: 500px; margin-bottom: 15px;' src='" + imageURL.replace(regexp, 't500x500') + "'>");
Object.keys(sizes).forEach(function (size) {
var url = imageURL.replace(regexp, size);
$.ajax({
type: 'HEAD',
url: url,
complete: function(xhr) {
if (xhr.status !== 200) {
return;
}
$(".modal__content .imageContent").append(
makeButton(url, sizes[size])
);
}
});
});
}
function makeButton(url, sizeLabel) {
var $btn = $('<button />')
.css({ margin: '10px auto 0 auto', display: 'block', width: '100%'})
.attr('class', 'sc-button sc-button-medium sc-button-responsive')
.text('Download ' + sizeLabel);
$btn.on('click', function(e) {
e.preventDefault();
download(url);
});
return $btn;
}
function download(url) {
url = url.split('?')[0];
if (!url.startsWith('http')) {
url = window.location.protocol + (url.startsWith('//') ? '' : '//') + url;
}
var fileNameParts = url.split('/');
var fileName = fileNameParts[fileNameParts.length - 1];
var options = {
url: url,
name: fileName,
onerror: function (e) {
logError('Download failed. Reason: ' + e.error);
}
};
GM_download(options);
}
function logError(message) {
var details = {
title: GM_info.script.name,
text: message,
};
GM_notification(details);
console.error('%c' + GM_info.script.name + '%c: ' + message, 'font-weight: bold', 'font-weight: normal');
}
}, 250);
}
setInterval is not actually a function within Google App Script. You'll have to utilize the other built-in features. I typically use Utilities.sleep(timeout) to make this work. You can see more here.

How to insert a placeholder element in Summernote?

I'm developing a plugin for Summernote WYSIWYG editor (version 0.8.1) to insert iframe elements into the code.
Working with the samples provided, I managed to get the plugin button in the menu, which opens a dialog where I can enter an URL and a title. It's no problem to add an iframe Tag to the source, but this is not what I want.
I want to insert a placeholder into the code, with a markup like (or similar to) this:
<div class="ext-iframe-subst" data-src="http://www.test.example" data-title="iframe title"><span>iframe URL: http://www.test.example</span></div>
Now, summernote lets me edit the contents of the span, but I'd like to have a placeholder instead, that can't be modified in the editor.
How can I insert a placeholder into the editor, that has the following properties:
It is editable as a single block (can be deleted with a single delete)
On click, I can open a popover similar to the link or image popover to adjust size f.i.
The inner content is not modifyable
This is what I have so far:
// Extends plugins for adding iframes.
// - plugin is external module for customizing.
$.extend($.summernote.plugins, {
/**
* #param {Object} context - context object has status of editor.
*/
'iframe': function (context) {
var self = this;
// ui has renders to build ui elements.
// - you can create a button with `ui.button`
var ui = $.summernote.ui;
var $editor = context.layoutInfo.editor;
var options = context.options;
var lang = options.langInfo;
// add context menu button
context.memo('button.iframe', function () {
return ui.button({
contents: '<i class="fa fa-newspaper-o"/>',
tooltip: lang.iframe.iframe,
click: context.createInvokeHandler('iframe.show')
}).render();
});
// This events will be attached when editor is initialized.
this.events = {
// This will be called after modules are initialized.
'summernote.init': function (we, e) {
console.log('IFRAME initialized', we, e);
},
// This will be called when user releases a key on editable.
'summernote.keyup': function (we, e) {
console.log('IFRAME keyup', we, e);
}
};
// This method will be called when editor is initialized by $('..').summernote();
// You can create elements for plugin
this.initialize = function () {
var $container = options.dialogsInBody ? $(document.body) : $editor;
var body = '<div class="form-group row-fluid">' +
'<label>' + lang.iframe.url + '</label>' +
'<input class="ext-iframe-url form-control" type="text" />' +
'<label>' + lang.iframe.title + '</label>' +
'<input class="ext-iframe-title form-control" type="text" />' +
'<label>' + lang.iframe.alt + '</label>' +
'<textarea class="ext-iframe-alt form-control" placeholder="' + lang.iframe.alttext + '" rows=""10""></textarea>' +
'</div>';
var footer = '<button href="#" class="btn btn-primary ext-iframe-btn disabled" disabled>' + lang.iframe.insert + '</button>';
this.$dialog = ui.dialog({
title: lang.iframe.insert,
fade: options.dialogsFade,
body: body,
footer: footer
}).render().appendTo($container);
};
// This methods will be called when editor is destroyed by $('..').summernote('destroy');
// You should remove elements on `initialize`.
this.destroy = function () {
this.$dialog.remove();
this.$dialog = null;
};
this.bindEnterKey = function ($input, $btn) {
$input.on('keypress', function (event) {
if (event.keyCode === 13) { //key.code.ENTER) {
$btn.trigger('click');
}
});
};
this.createIframeNode = function (data) {
var $iframeSubst = $('<div class="ext-iframe-subst"><span>' + lang.iframe.iframe + '</span></div>');
$iframeSubst.attr("data-src", data.url).attr("data-title", data.title);
return $iframeSubst[0];
};
this.show = function () {
var text = context.invoke('editor.getSelectedText');
context.invoke('editor.saveRange');
console.log("iframe.getInfo: " + text);
this
.showIframeDialog(text)
.then(function (data) {
// [workaround] hide dialog before restore range for IE range focus
ui.hideDialog(self.$dialog);
context.invoke('editor.restoreRange');
// build node
var $node = self.createIframeNode(data);
if ($node) {
// insert iframe node
context.invoke('editor.insertNode', $node);
}
})
.fail(function () {
context.invoke('editor.restoreRange');
});
};
this.showIframeDialog = function (text) {
return $.Deferred(function (deferred) {
var $iframeUrl = self.$dialog.find('.ext-iframe-url');
var $iframeTitle = self.$dialog.find('.ext-iframe-title');
var $iframeBtn = self.$dialog.find('.ext-iframe-btn');
ui.onDialogShown(self.$dialog, function () {
context.triggerEvent('dialog.shown');
$iframeUrl.val(text).on('input', function () {
ui.toggleBtn($iframeBtn, $iframeUrl.val());
}).trigger('focus');
$iframeBtn.click(function (event) {
event.preventDefault();
deferred.resolve({ url: $iframeUrl.val(), title: $iframeTitle.val() });
});
self.bindEnterKey($iframeUrl, $iframeBtn);
});
ui.onDialogHidden(self.$dialog, function () {
$iframeUrl.off('input');
$iframeBtn.off('click');
if (deferred.state() === 'pending') {
deferred.reject();
}
});
ui.showDialog(self.$dialog);
});
};
}
});
// add localization texts
$.extend($.summernote.lang['en-US'], {
iframe: {
iframe: 'iframe',
url: 'iframe URL',
title: 'title',
insert: 'insert iframe',
alt: 'Text alternative',
alttext: 'you should provide a text alternative for the content in this iframe.',
test: 'Test'
}
});
You can use contenteditable attribute on your span element and it will work and keep the iframe plugin HTML in the editor and it will delete the whole block when hitting Del or Backspace keys.
There are some demo plugins in the Github repository and there is one that demontrates usage of dialog and popover editing and you can check the logic and code here.
In createIframeNode we create the element and set the data attributes
this.createIframeNode = function (data) {
var $iframeSubst = $(
'<div class="ext-iframe-subst"><span contenteditable="false">' +
lang.iframe.url + ': ' + data.url +
'</span></div>'
);
$iframeSubst
.attr("data-src", data.url)
.attr("data-title", data.title);
return $iframeSubst[0];
};
We also create a currentEditing variable to save the element under cursor when the popover menu popups so the opoup dialog will know that we're editing an element and not create a new one.
In updateIframeNode we're using the currentEditing element to update
Here we re-create only the span element because the currentEditing is the actual div.ext-iframe-subst and then we update the data attributes:
this.updateIframeNode = function (data) {
$(currentEditing).html(
'<span contenteditable="false">' +
lang.iframe.url + ': ' + data.url +
'</span>'
)
$(currentEditing)
.attr("data-src", data.url)
.attr("data-title", data.title);
}
Full working plugin
Run the code snippet and try to insert iframes using the button with the square icon. You can edit existing iFrame elements and the block deletes all together.
/**
* #param {Object} context - context object has status of editor.
*/
var iframePlugin = function (context) {
var self = this;
// ui has renders to build ui elements.
// - you can create a button with `ui.button`
var ui = $.summernote.ui;
var dom = $.summernote.dom;
var $editor = context.layoutInfo.editor;
var currentEditing = null;
var options = context.options;
var lang = options.langInfo;
// add context menu button
context.memo('button.iframe', function () {
return ui.button({
contents: '<i class="note-icon-frame"/>',
tooltip: lang.iframe.iframe,
click: (event) => {
currentEditing = null;
context.createInvokeHandler('iframe.show')(event);
}
}).render();
});
context.memo('button.iframeDialog', function () {
return ui.button({
contents: '<i class="note-icon-frame"/>',
tooltip: lang.iframe.iframe,
click: (event) => {
context.createInvokeHandler('iframe.show')(event);
// currentEditing
}
}).render();
});
// This events will be attached when editor is initialized.
this.events = {
// This will be called after modules are initialized.
'summernote.init': function (we, e) {
$('data.ext-iframe', e.editable).each(function() { self.setContent($(this)); });
},
// This will be called when user releases a key on editable.
'summernote.keyup summernote.mouseup summernote.change summernote.scroll': function() {
self.update();
},
'summernote.dialog.shown': function() {
self.hidePopover();
},
};
// This method will be called when editor is initialized by $('..').summernote();
// You can create elements for plugin
this.initialize = function () {
var $container = options.dialogsInBody ? $(document.body) : $editor;
var body = '<div class="form-group row-fluid">' +
'<label>' + lang.iframe.url + '</label>' +
'<input class="ext-iframe-url form-control" type="text" />' +
'<label>' + lang.iframe.title + '</label>' +
'<input class="ext-iframe-title form-control" type="text" />' +
// '<label>' + lang.iframe.alt + '</label>' +
// '<textarea class="ext-iframe-alt form-control" placeholder="' + lang.iframe.alttext + '" rows=""10""></textarea>' +
'</div>';
var footer = '<button href="#" class="btn btn-primary ext-iframe-btn disabled" disabled>' + lang.iframe.insertOrUpdate + '</button>';
this.$dialog = ui.dialog({
title: lang.iframe.insert,
fade: options.dialogsFade,
body: body,
footer: footer
}).render().appendTo($container);
// create popover
this.$popover = ui.popover({
className: 'ext-iframe-popover',
}).render().appendTo('body');
var $content = self.$popover.find('.popover-content');
context.invoke('buttons.build', $content, options.popover.iframe);
};
// This methods will be called when editor is destroyed by $('..').summernote('destroy');
// You should remove elements on `initialize`.
this.destroy = function () {
self.$popover.remove();
self.$popover = null;
self.$dialog.remove();
self.$dialog = null;
};
this.bindEnterKey = function ($input, $btn) {
$input.on('keypress', function (event) {
if (event.keyCode === 13) { //key.code.ENTER) {
$btn.trigger('click');
}
});
};
self.update = function() {
// Prevent focusing on editable when invoke('code') is executed
if (!context.invoke('editor.hasFocus')) {
self.hidePopover();
return;
}
var rng = context.invoke('editor.createRange');
var visible = false;
var $data = $(rng.sc).closest('div.ext-iframe-subst');
if ($data.length) {
currentEditing = $data[0];
var pos = dom.posFromPlaceholder(currentEditing);
const containerOffset = $(options.container).offset();
pos.top -= containerOffset.top;
pos.left -= containerOffset.left;
self.$popover.css({
display: 'block',
left: pos.left,
top: pos.top,
});
// save editor target to let size buttons resize the container
context.invoke('editor.saveTarget', currentEditing);
visible = true;
}
// hide if not visible
if (!visible) {
self.hidePopover();
}
};
self.hidePopover = function() {
self.$popover.hide();
};
this.createIframeNode = function (data) {
var $iframeSubst = $(
'<div class="ext-iframe-subst"><span contenteditable="false">' +
lang.iframe.url + ': ' + data.url +
'</span></div>'
);
$iframeSubst.attr("data-src", data.url).attr("data-title", data.title);
return $iframeSubst[0];
};
this.updateIframeNode = function (data) {
$(currentEditing).html(
'<span contenteditable="false">' +
lang.iframe.url + ': ' + data.url +
'</span>'
)
$(currentEditing).attr("data-src", data.url).attr("data-title", data.title);
}
this.show = function () {
var text = context.invoke('editor.getSelectedText');
context.invoke('editor.saveRange');
this
.showIframeDialog(text)
.then(function (data) {
// [workaround] hide dialog before restore range for IE range focus
ui.hideDialog(self.$dialog);
context.invoke('editor.restoreRange');
if (currentEditing) {
self.updateIframeNode(data);
} else {
// build node
var $node = self.createIframeNode(data);
if ($node) {
// insert iframe node
context.invoke('editor.insertNode', $node);
}
}
})
.fail(function () {
context.invoke('editor.restoreRange');
});
};
this.showIframeDialog = function (text) {
return $.Deferred(function (deferred) {
var $iframeUrl = self.$dialog.find('.ext-iframe-url');
var $iframeTitle = self.$dialog.find('.ext-iframe-title');
var $iframeBtn = self.$dialog.find('.ext-iframe-btn');
ui.onDialogShown(self.$dialog, function () {
context.triggerEvent('dialog.shown');
var dataSrc = currentEditing ? $(currentEditing).attr('data-src') : '';
var dataTitle = currentEditing ? $(currentEditing).attr('data-title') : '';
$iframeTitle.val(dataTitle);
$iframeUrl.val(dataSrc).on('input', function () {
ui.toggleBtn($iframeBtn, $iframeUrl.val());
}).trigger('focus');
$iframeBtn.click(function (event) {
event.preventDefault();
deferred.resolve({ url: $iframeUrl.val(), title: $iframeTitle.val() });
});
self.bindEnterKey($iframeUrl, $iframeBtn);
});
ui.onDialogHidden(self.$dialog, function () {
$iframeUrl.off('input');
$iframeBtn.off('click');
if (deferred.state() === 'pending') {
deferred.reject();
}
});
ui.showDialog(self.$dialog);
});
};
}
// Extends plugins for adding iframes.
// - plugin is external module for customizing.
$.extend(true, $.summernote, {
plugins: {
iframe: iframePlugin,
},
options: {
popover: {
iframe: [
['iframe', ['iframeDialog']],
],
},
},
lang: {
'en-US': {
iframe: {
iframe: 'iframe',
url: 'iframe URL',
title: 'title',
insertOrUpdate: 'insert/update iframe',
alt: 'Text alternative',
alttext: 'you should provide a text alternative for the content in this iframe.',
test: 'Test',
},
},
},
});
$(document).ready(function() {
$('#editor').summernote({
height: 200,
toolbar: [
['operation', ['undo', 'redo']],
['style', ['bold', 'italic', 'underline']],
['color', ['color']],
['insert', ['iframe', 'link','picture', 'hr']],
['view', ['codeview']],
],
});
});
<!-- include libraries(jQuery, bootstrap) -->
<link href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet">
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<!-- include summernote css/js -->
<link href="https://cdn.jsdelivr.net/npm/summernote#0.8.18/dist/summernote.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/summernote#0.8.18/dist/summernote.min.js"></script>
<div id="editor">Hello Summernote</div>
By default when summernote creadted its editor div contains the contents
< /p>< br>/p>
so it if you empty summernote onload then problem will be resolved.
There is code to remove contents:
$(function () {
$('#summernote').summernote({
inheritPlaceholder: true,
placeholder: 'Enter your Inquiry here...',
});
$('#summernote').summernote('code', ''); //This line remove summercontent when load
});
Try Using
$(document).ready(function() {
$('#summernote').summernote({
placeholder: 'Hello stand alone ui',
tabsize: 2,
height: 120
});
});
<!-- include libraries(jQuery, bootstrap) -->
<link href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet">
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<!-- include summernote css/js -->
<link href="https://cdn.jsdelivr.net/npm/summernote#0.8.18/dist/summernote.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/summernote#0.8.18/dist/summernote.min.js"></script>
<div id="summernote"></div>

Js position button in bottom right corner instead of centered

I'm trying to position this button for my quickview in the bottom right corner of the image instead of centered, but I can't figure out how to do it. The code is using top and left offsets to position the button in the center. How can I position it in the bottom right corner instead? To see an example of the positioning I'm hoping to achieve, go to: http://www.shrimptoncouture.com/collections/all-clothing.
Here's what I'm working with. Any help would be greatly appreciated:
Cmsmart.noConflict();
Cmsmart(function($) {
var producturl;
function geturlrewrite(){
var mypath = arguments[0];
var patt = /\/[^\/]{0,}$/ig;
if(mypath){
if(mypath[mypath.length-1]=="/"){
mypath = mypath.substring(0,mypath.length-1);
return (mypath.match(patt)+"/");
}
return mypath.match(patt);
}
return '';
}
function urltrim(){
return arguments[0].replace(/^\s+|\s+$/g,"");
}
function installquickview(){
if (typeof CMSMART == 'undefined') return;
var argInput = arguments[0];
var productlistBlocks = $(argInput.productlistClassArr);
var datasaved = [];
var mypath = 'cmsmquickview/index/index';
if(CMSMART.QuickView.BASE_URL.indexOf('index.php') == -1){
mypath = 'cmsmquickview/index/index';
}else{
mypath = 'cmsmquickview/index/index';
}
var baseUrl = CMSMART.QuickView.BASE_URL + mypath;
var _quickviewbutton = '<a id="cmsmart_quickview_button" href="#">' + CMSMART.QuickView.BOTTON_LABEL + '</a>';
var _quickform = '<div id="csmm_quickform">' +
'<div id = "quickviewshow" ></div>' +
'</div>';
$(document.body).append(_quickform);
$(document.body).append(_quickviewbutton);
var quickviewButton = $('#cmsmart_quickview_button');
//alert(encodeURIComponent(CMSMART.QuickView.BASE_URL + 'ab=3dfd&ddfdfd=234'));
$.each(productlistBlocks, function(i, vl){
var productlist = $(vl);
$.each(productlist, function(index, value) {
var reloadurl = '';
var aClass = argInput.aClass[i]?argInput.aClass[i]:argInput.aClass[0];
producturl = $(aClass, value);
if(producturl.attr('href')){
var producturlpath = producturl.attr('href').replace(CMSMART.QuickView.BASE_URL,"");
//var producturlpath = geturlrewrite(producturl.attr('href'))[0];
//producturlpath[0] == "\/" ? producturlpath = producturlpath.substring(1,producturlpath.length) : producturlpath;
//producturlpath = urltrim(producturlpath);
reloadurl += baseUrl+ ("/path/"+producturlpath).replace(/\/\//g,"/");
//alert(reloadurl);
var imgClass = argInput.imgClass[i]?argInput.imgClass[i]:argInput.imgClass[0];
$(this).bind('mouseover', function() {
//var o = $(this).offset();
//var o = $(this);
var o = $(imgClass+':eq(0)', this);
$('#cmsmart_quickview_button').attr('href',reloadurl).show()
.css({
'top': o.offset().top+(o.height() - quickviewButton.height())/2+'px',
'left': o.offset().left+(o.width() - quickviewButton.outerWidth())/2+'px',
'visibility': 'visible'
});
});
$(value).bind('mouseout', function() {
$('#cmsmart_quickview_button').hide();
});
}
});
});
if(CMSMART.QuickView.CENTER)
{
$("#quickviewshow").css('margin', ($(window).height() / 2 - $("#quickviewshow").height() / 2) + "px auto auto auto");
}
$('#cmsmart_quickview_button')
.bind('mouseover', function() {
$(this).show();
})
.bind('click', function() {
idbyurl = ($(this).attr('href')).replace(/\W/g,"");
showqv();
$("#quickviewshow").html('<a id="cmsmart_quickview_button_close" title="Close Quick View"> </a><a class="quickviewloading"><a>');
$("#cmsmart_quickview_button_close").on( "click", function() {
closeqv();
$("div.zoomContainer").remove();
});
$(this).hide();
if(datasaved[idbyurl]){
$("#quickviewshow").html('<a id="cmsmart_quickview_button_close" title="Close Quick View"> </a>');
$("#cmsmart_quickview_button_close").on( "click", function() {
closeqv();
});
$("#quickviewshow").append(datasaved[idbyurl]);
showqv();
relimg();
return false;
}
else{
$.ajax({
url: $(this).attr('href'),
cache: false
}).done(function( html ) {
$("#quickviewshow").html('<a id="cmsmart_quickview_button_close" title="Close Quick View"> </a>');
$("#cmsmart_quickview_button_close").on( "click", function() {
closeqv();
$("div.zoomContainer").remove();
});
$("#quickviewshow").append(html);
showqv();
datasaved[idbyurl] = html;
relimg();
});
}
return false;
});
$('#csmm_quickform').click(function(e) {
if($(e.target).is('#quickviewshow, #quickviewshow *')) return;
$('#csmm_quickform').hide();
$("div.zoomContainer").remove();
});
}
$( document ).ready(function() {
installquickview(CMSMART.QuickView.BUTTON_CONFIG);
});
$(window).resize(function() {
$("#quickviewshow").css('margin', ($(window).height() / 2 - $("#quickviewshow").height() / 2) + "px auto auto auto");
});
function relimg(){
maxh = $('div.product-quickview').outerHeight() - 45;
if($('div.qvtabhead')) maxh = maxh - $('div.qvtabhead').outerHeight();
if($('div.qvformaddtocart')) maxh = maxh - $('div.qvformaddtocart').outerHeight();
if($('div.tabquickshow')) $('div.tabquickshow').css('max-height', maxh + "px");
//submitbqv();
$('#showlargeimg').elevateZoom({ zoomWindowWidth:300, zoomWindowHeight:300, borderSize: 2, zoomWindowOffetx:15, cursor:'move' });
$('#mycarousel').jcarousel({
scroll: 4
});
$("li img.p_image_hover").click(
function () {
smallImage = $(this).attr('src');
largeImage = $(this).attr('data-zoom-image');
$('img#showlargeimg').attr('src', smallImage);
var ez = $('#showlargeimg').data('elevateZoom');
ez.swaptheimage(smallImage, largeImage);
}
);
$('a.tabquickviewcontrol').click(
function(){
$('a.tabquickviewcontrol').removeClass("highlight");
$(this).addClass("highlight");
var divsl = $(this).attr('href');
$('.tabquickshow').css('display', 'none');
$(divsl).css('display', 'block');
return false;
}
)
}
function showqv(){ $("#csmm_quickform").css("display", "block"); }
function closeqv(){ $("#csmm_quickform").css("display", "none"); }
function btcloseqv(){
$("#cmsmart_quickview_button_close").on( "click", function() {
$("#csmm_quickform").css("display", "none");
});
}
function submitbqv(){
var fr = $('#product_addtocart_form');
var btc = $('.btn-cart', fr);
btc.attr('onclick', '');
btc.click(function(){
var cansubmit = true;
$('select.required-entry', fr).each(function(){
if($(this).val() == ''){
$(this).addClass('validation-failed');
$(this).focus();
cansubmit = false;
return false;
}else { $(this).removeClass('validation-failed'); }
});
if(cansubmit) fr.submit();
});
}
btcloseqv();
});
It might be something like:
$('#cmsmart_quickview_button').attr('href',reloadurl).show()
.css({
'top' : o.offset().top + o.height() - quickviewButton.height()+'px',
'left': o.offset().left+ o.width() - quickviewButton.outerWidth()+'px',
'visibility': 'visible'
});
If that isn't it, keep playing with that code until you get what you want. You might try o.offset().bottom and o.offset().right but I don't know if they are defined.

Bind function in jQuery plugin function

I'm trying to implement an infinite scroll in a div with filtering option, as well, filtering should work when user stops typing in the box.
Html:
<div class="span2" style="margin-top: 50px;">
<input id="Search" class="input-mysize" />
<div id="listNav" style="height: 370px; border: 1px solid; overflow: auto; margin-right: 20px; width: 90%;">
</div>
</div>
JS in Html:
$(function() {
function onSuccess(row, container) {
container.append('<div style="border:1px solid; cursor: hand; cursor: pointer;" >' +
'<table border="0">' +
'<tr>' +
'<td id="Location' + row.Id + '">'+
'<b>Name: </b>' + row.Name + '</br >' + '<b>Address: </b>' + row.Address + '' +
'</td>' +
'<td onclick="locationDetails(' + row.Id + ')"> > </td>' +
'</tr>' +
'</table>' +
'</div>');
var tdId = "Location" + row.Id;
var element = $('#' + tdId);
$(element).click(function() {
google.maps.event.trigger(arrMarkers[row.Id], 'click');
});
};
//...
$('#listNav').empty();
$('#listNav').jScroller("/Dashboard/GetClients", {
numberOfRowsToRetrieve: 7,
onSuccessCallback: onSuccess,
onErrorCallback: function () {
alert("error");
}
});
//...
$('#Search').keyup(function(){
clearTimeout(typingTimer);
if ($('#myInput').val) {
typingTimer = setTimeout(doneTyping, doneTypingInterval);
}
});
function doneTyping () {
startInt = startInt + 5;
$('#listNav').empty();
$('#listNav').unbind();
$('#listNav').jScroller("/Dashboard/GetClients", {
numberOfRowsToRetrieve: 7,
start : startInt,
locationFilter: $('#Search').val(),
onSuccessCallback: onSuccess,
onErrorCallback: function () {
alert("error");
}
});
};
});
rest of JS (based on jScroller plug in):
(function ($) {
"use strict";
jQuery.fn.jScroller = function (store, parameters) {
var defaults = {
numberOfRowsToRetrieve: 10,
locationFilter: '',
onSuccessCallback: function (row, container) { },
onErrorCallback: function (thrownError) { window.alert('An error occurred while trying to retrive data from store'); },
onTimeOutCallback: function () { },
timeOut: 3 * 1000,
autoIncreaseTimeOut: 1000,
retryOnTimeOut: false,
loadingButtonText: 'Loading...',
loadMoreButtonText: 'Load more',
fullListText: 'There is no more items to show',
extraParams: null
};
var options = jQuery.extend(defaults, parameters);
var list = jQuery(this),
end = false,
loadingByScroll = true;
var ajaxParameters;
if (options.extraParams === null) {
ajaxParameters = {
start: 0,
numberOfRowsToRetrieve: options.numberOfRowsToRetrieve,
locationFilter: options.locationFilter
};
}
else {
ajaxParameters = {
start: 0,
numberOfRowsToRetrieve: options.numberOfRowsToRetrieve,
locationFilter: option.locationFilter,
extraParams: options.extraParams
};
}
list.html('');
function loadItems() {
preLoad();
jQuery.ajax({
url: store,
type: "POST",
data: ajaxParameters,
timeOut: options.timeOut,
success: function (response) {
list.find("#jscroll-loading").remove();
if (response.Success === false) {
options.onErrorCallback(list, response.Message);
return;
}
for (var i = 0; i < response.data.length; i++) {
if (end === false) {
options.onSuccessCallback(response.data[i], list);
}
}
if (loadingByScroll === false) {
if (end === false) {
list.append('<div><a class="jscroll-loadmore">' + options.loadMoreButtonText + '</a></div>');
}
}
ajaxParameters.start = ajaxParameters.start + options.numberOfRowsToRetrieve;
if (ajaxParameters.start >= response.total) {
end = true;
list.find('#jscroll-fulllist').remove();
list.find(".jscroll-loadmore").parent("div").remove();
}
},
error: function (xhr, ajaxOptions, thrownError) {
if (thrownError === 'timeout') {
options.onTimeOutCallback();
if (options.retryOnTimeOut) {
options.timeOut = options.timeOut + (1 * options.autoIncreaseTimeOut);
loadItems();
}
}
else {
options.onErrorCallback(thrownError);
}
}
});
}
function preLoad() {
if (list.find("#jscroll-loading").length === 0) {
list.find(".jscroll-loadmore").parent("div").remove();
list.append('<a id="jscroll-loading">' + options.loadingButtonText + '</a>');
}
}
//called when doneTyping is called and first time page loaded
jQuery(document).ready(function () {
loadItems();
});
//called when user scrolls down in a div
$('#listNav').bind('scroll', function () {
if ($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight) {
loadItems();
}
});
};
})(jQuery);
It's mostly working, but at some cases when user stops typing, the
jQuery(document).ready(function () {
loadItems();
});
and
$('#listNav').bind('scroll', function () {
if ($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight) {
loadItems();
}
});
are both called instead of just first one, adding bad html to the div. Most cases only jQuery(document).ready is called, which is what i need.
As well why is jQuery(document).ready() is called every time the doneTyping() is called ? I though it should be called only the first time the page is loaded after DOM is ready.
I assume that your JS code in your HTML starts with a $(document).ready({}), so there would be no need to add $(document).ready({}) inside your plugin. Just call loadItems(); without the document ready event.

Javascript upload video on youtube using drag and drop

I want to upload the video on youtube. Problem statement is that user drag and drop the video on my application and when user click on the upload button video is uploaded to the youtube.
I have written this code
$('#drop-files').bind('drop', function(e) {
rc = count;
var files = e.dataTransfer.files;
//alert("files -"+files[0].path);
count += files.length;
$('#uploaded-holder').show();
$.each(files, function(index, file) {
console.log("aaaa : "+file);
//alert("sarthi : "+file.name);
if (!(files[index].type.match('image.*') || files[index].type.match('pdf.*') || files[index].type.match('video.*'))) {
alert("ONLY IMAEG AND VIDEO")
callModel();
} else {
// Start a new instance of FileReader*/
var fileReader = new FileReader();
var obj = {};
// When the filereader loads initiate a function
//alert("file "+file);
fileReader.onload = (function(file) {
var isVideo = 1;
return function(e) {
// Push the data URI into an array
dataArray.push({
name : file.name,
value : this.result
});
// Move each image 40 more pixels across
//z = z+40;
var image;
var video;
if(file.type.match('image.*'))
image = this.result;
else if(file.type.match('pdf.*'))
image = "assets/img/pdf.png";
else if(file.type.match('video.*')){
video = this.result;
}
// Just some grammatical adjustments
/*if(dataArray.length == 1) {
$('#upload-button span').html("1 file to be uploaded");
} else {
$('#upload-button span').html(dataArray.length+" files to be uploaded");
}*/
if(file.type.match('image.*')) {
//alert("1");
var html = tmpl(template, {
image:image,
loadingbar:"loadingbar"+rc,
loadper:"loadper"+rc,
type:"type"+rc,
dd:"dd"+rc,
ed:"ed"+rc,
grey:"greey"+rc,
upbtn: "upbtn"+rc,
dderrorid: "dderr"+rc,
ederrorid: "ederr"+rc
});
obj = {
htmlstring:html,
type:"type"+rc,
dd:"dd"+rc,
ed:"ed"+rc,
upbtn: "upbtn"+rc,
loadbar: "loadingbar"+rc,
loadper:"loadper"+rc,
grey:"greey"+rc,
file:file,
flag:0,
dderrorid: "dderr"+rc,
ederrorid: "ederr"+rc
}
$('#dropped-files').append(html);
var now = new Date();
var today = (now.getMonth() + 1) + '-' + now.getDate() + '-' + now.getFullYear();
$('#'+obj.ed).val(today);
uploadObject[rc] = obj;
$("#"+obj.upbtn).click(function(e){
if(!($("#uid").val() == "")){
$('.error').hide();
if(!($("#"+obj.dd).val() == "")){
$('#'+obj.dderrorid + " span").hide();
if(!($("#"+obj.ed).val() == "")){
$('#'+obj.ederrorid + " span").hide();
upload(e);
} else {
$('#'+obj.ederrorid + " span").show();
}
} else {
$('#'+obj.dderrorid + " span").show();
}
} else {
$('.error').show();
}
});
$("#"+obj.grey).click(function(e){
removeFiles(e);
});
rc++;
}
else{
if($('#dropped-files > .video').length < maxFiles) {
//alert("2");
var html1 = tmpl(vtemplate, {
video:video,
loadingbar:"loadingbar"+rc,
loadper:"loadper"+rc,
type:"type"+rc,
dd:"dd"+rc,
ed:"ed"+rc,
grey:"greey"+rc,
upbtn: "upbtn"+rc,
dderrorid: "dderr"+rc,
ederrorid: "ederr"+rc
});
obj = {
htmlstring:html1,
type:"type"+rc,
dd:"dd"+rc,
ed:"ed"+rc,
upbtn: "upbtn"+rc,
loadbar: "loadingbar"+rc,
loadper:"loadper"+rc,
grey:"greey"+rc,
file:file,
flag:0,
dderrorid: "dderr"+rc,
ederrorid: "ederr"+rc
}
//$('#dropped-files').append(html1);
now = new Date();
today = (now.getMonth() + 1) + '-' + now.getDate() + '-' + now.getFullYear();
$('#'+obj.ed).val(today);
uploadObject[rc] = obj;
$("#"+obj.upbtn).click(function(e){
if(!($("#uid").val() == "")){
$('.error').hide();
if(!($("#"+obj.dd).val() == "")){
$('#'+obj.dderrorid + " span").hide();
if(!($("#"+obj.ed).val() == "")){
$('#'+obj.ederrorid + " span").hide();
$("input[type='file']")
.prop("files", e.originalEvent.dataTransfer.files) // put files into element
.closest("form")
.submit();
} else {
$('#'+obj.ederrorid + " span").show();
}
} else {
$('#'+obj.dderrorid + " span").show();
}
} else {
$('.error').show();
}
});
$("#"+obj.grey).click(function(e){
removeFiles(e);
});
rc++;
}
$('#dropped-files').append(html1);
}
};
})(files[index]);
fileReader.readAsDataURL(file);
}
});
});
I am not able to get the absolute path of file dropped on my application.
Thanks in advance !
You can not access clients (local address) at serverside. This may help you!
Passing path to uploaded file from HTML5 drag & drop to input field
and
http://www.whatwg.org/specs/web-apps/current-work/multipage/dnd.html

Categories