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
Related
I am trying to use a php function declared in a separate php file in a Javascript file. Do you know how to do ?
Here is my PHP code (download.php) :
<?php
$passthru = function ($reqchain)
{
$reqchain = $_SERVER['QUERY_STRING']; //chaîne de requête (partie de l'URL après le ?) qui sert à se connecter à la page (ex: file=C:/xampp/htdocs/projet/siteAM.PNG)
$path = substr($reqchain, 5);
// $fullpath = $dir.$_GET[$file];
header('Content-Type: '.mime_content_type($path));
header('Content-Length: '.filesize($path));
header('Content-Transfer-Encoding: Binary');
header('Content-Disposition: inline; filename="'.basename($reqchain).'"');
fpassthru(fopen($path, 'rb'));
}
?>
And here is my Javascript code (script.js) (I have written a big comment to mark where I try to call my function, it is close to the end of the code) :
$(function(){
var filemanager = $('.filemanager'),
breadcrumbs = $('.breadcrumbs'),
fileList = filemanager.find('.data');
// Start by fetching the file data from scan.php with an AJAX request
$.get('scan.php', 'download.php', function(data) {
var response = [data],
currentPath = '',
breadcrumbsUrls = [];
var folders = [],
files = [];
// This event listener monitors changes on the URL. We use it to
// capture back/forward navigation in the browser.
$(window).on('hashchange', function(){
goto(window.location.hash);
// We are triggering the event. This will execute
// this function on page load, so that we show the correct folder:
}).trigger('hashchange');
// Hiding and showing the search box
filemanager.find('.search').click(function(){
var search = $(this);
search.find('span').hide();
search.find('input[type=search]').show().focus();
});
// Listening for keyboard input on the search field.
// We are using the "input" event which detects cut and paste
// in addition to keyboard input.
filemanager.find('input').on('input', function(e){
folders = [];
files = [];
var value = this.value.trim();
if(value.length) {
filemanager.addClass('searching');
// Update the hash on every key stroke
window.location.hash = 'search=' + value.trim();
}
else {
filemanager.removeClass('searching');
window.location.hash = encodeURIComponent(currentPath);
}
}).on('keyup', function(e){
// Clicking 'ESC' button triggers focusout and cancels the search
var search = $(this);
if(e.keyCode == 27) {
search.trigger('focusout');
}
}).focusout(function(e){
// Cancel the search
var search = $(this);
if(!search.val().trim().length) {
window.location.hash = encodeURIComponent(currentPath);
search.hide();
search.parent().find('span').show();
}
});
// Clicking on folders
fileList.on('click', 'li.folders', function(e){
e.preventDefault();
var nextDir = $(this).find('a.folders').attr('href');
if(filemanager.hasClass('searching')) {
// Building the breadcrumbs
breadcrumbsUrls = generateBreadcrumbs(nextDir);
filemanager.removeClass('searching');
filemanager.find('input[type=search]').val('').hide();
filemanager.find('span').show();
}
else {
breadcrumbsUrls.push(nextDir);
}
window.location.hash = encodeURIComponent(nextDir);
currentPath = nextDir;
});
// Clicking on breadcrumbs
breadcrumbs.on('click', 'a', function(e){
e.preventDefault();
var index = breadcrumbs.find('a').index($(this)),
nextDir = breadcrumbsUrls[index];
breadcrumbsUrls.length = Number(index);
window.location.hash = encodeURIComponent(nextDir);
});
// Navigates to the given hash (path)
function goto(hash) {
hash = decodeURIComponent(hash).slice(1).split('=');
if (hash.length) {
var rendered = '';
// if hash has search in it
if (hash[0] === 'search') {
filemanager.addClass('searching');
rendered = searchData(response, hash[1].toLowerCase());
if (rendered.length) {
currentPath = hash[0];
render(rendered);
}
else {
render(rendered);
}
}
// if hash is some path
else if (hash[0].trim().length) {
rendered = searchByPath(hash[0]);
if (rendered.length) {
currentPath = hash[0];
breadcrumbsUrls = generateBreadcrumbs(hash[0]);
render(rendered);
}
else {
currentPath = hash[0];
breadcrumbsUrls = generateBreadcrumbs(hash[0]);
render(rendered);
}
}
// if there is no hash
else {
currentPath = data.path;
breadcrumbsUrls.push(data.path);
render(searchByPath(data.path));
}
}
}
// Splits a file path and turns it into clickable breadcrumbs
function generateBreadcrumbs(nextDir){
var path = nextDir.split('/').slice(0);
for(var i=1;i<path.length;i++){
path[i] = path[i-1]+ '/' +path[i];
}
return path;
}
// Locates a file by path
function searchByPath(dir) {
var path = dir.split('/'),
demo = response,
flag = 0;
for(var i=0;i<path.length;i++){
for(var j=0;j<demo.length;j++){
if(demo[j].name === path[i]){
flag = 1;
demo = demo[j].items;
break;
}
}
}
demo = flag ? demo : [];
return demo;
}
// Recursively search through the file tree
function searchData(data, searchTerms) {
data.forEach(function(d){
if(d.type === 'folder') {
searchData(d.items,searchTerms);
if(d.name.toLowerCase().match(searchTerms)) {
folders.push(d);
}
}
else if(d.type === 'file') {
if(d.name.toLowerCase().match(searchTerms)) {
files.push(d);
}
}
});
return {folders: folders, files: files};
}
// Render the HTML for the file manager
function render(data) {
var scannedFolders = [],
scannedFiles = [];
if(Array.isArray(data)) {
data.forEach(function (d) {
if (d.type === 'folder') {
scannedFolders.push(d);
}
else if (d.type === 'file') {
scannedFiles.push(d);
}
});
}
else if(typeof data === 'object') {
scannedFolders = data.folders;
scannedFiles = data.files;
}
// Empty the old result and make the new one
fileList.empty().hide();
if(!scannedFolders.length && !scannedFiles.length) {
filemanager.find('.nothingfound').show();
}
else {
filemanager.find('.nothingfound').hide();
}
if(scannedFolders.length) {
scannedFolders.forEach(function(f) {
var itemsLength = f.items.length,
name = escapeHTML(f.name),
icon = '<span class="icon folder"></span>';
if(itemsLength) {
icon = '<span class="icon folder full"></span>';
}
if(itemsLength == 1) {
itemsLength += ' item';
}
else if(itemsLength > 1) {
itemsLength += ' items';
}
else {
itemsLength = 'Empty';
}
var folder = $('<li class="folders">'+icon+'<span class="name">' + name + '</span> <span class="details">' + itemsLength + '</span></li>');
folder.appendTo(fileList);
});
}
if(scannedFiles.length) {
scannedFiles.forEach(function(f) {
var fileSize = bytesToSize(f.size),
name = escapeHTML(f.name),
fileType = name.split('.'),
icon = '<span class="icon file"></span>';
fileType = fileType[fileType.length-1];
icon = '<span class="icon file f-'+fileType+'">.'+fileType+'</span>';
var file = $('<li class="files">'+icon+'<span class="name">'+ name +'</span> <span class="details">'+fileSize+'</span></li>');
file.appendTo(fileList);
/* //////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// HERE IS WHERE I TRY TO CALL MY FUNCTION /////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////// */
$passthru($_SERVER['QUERY_STRING']);
/* /////////////////////^^//////////////////////////////////////////////^^///////////////////////////
|| ||
//////////////////// || HERE IS WHERE I TRY TO CALL MY FUNCTION || /////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////// */
});
}
// Generate the breadcrumbs
var url = '';
if(filemanager.hasClass('searching')){
url = '<span>Résultat de la recherche: </span>';
fileList.removeClass('animated');
}
else {
fileList.addClass('animated');
breadcrumbsUrls.forEach(function (u, i) {
var name = u.split('/');
if (i !== breadcrumbsUrls.length - 1) {
url += '<span class="folderName">' + name[name.length-1] + '</span> <span class="arrow">→</span> ';
}
else {
url += '<span class="folderName">' + name[name.length-1] + '</span>';
}
});
}
breadcrumbs.text('').append(url);
// Show the generated elements
fileList.animate({'display':'inline-block'});
}
// This function escapes special html characters in names
function escapeHTML(text) {
return text.replace(/\&/g,'&').replace(/\</g,'<').replace(/\>/g,'>');
}
// Convert file sizes from bytes to human readable units
function bytesToSize(bytes) {
var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
if (bytes == 0) return '0 Bytes';
var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
}
});
});
in my chat extension for phpBB, i use ajax for the js with a little jquery mixed in. i'm setting it up for users to select if they want the newest messages at the top or the bottom in accordance to their setting in their user control panel. the php side of it is done and works well but the js is still adding the new message at the top, ignoring the sort order in the php.
in the php. note that the sort order is set with this line
ORDER BY c.message_id ' . ($this->user->data['user_ajax_chat_messages_down'] ? 'DESC' : 'ASC');
i can't post the php in this post as the body is limited to 30000 characters. so i will post it if needed.
here is the js that does all the work
function setCookie(name, value, expires, path, domain, secure) {
var today = new Date();
today.setTime(today.getTime());
if (expires) {
expires = expires * 1000 * 60 * 60 * 24;
}
var expires_date = new Date(today.getTime() + (expires));
document.cookie = name + '=' + escape(value) +
((expires) ? ';expires=' + expires_date.toGMTString() : '') + //expires.toGMTString()
((path) ? ';path=' + path : '') +
((domain) ? ';domain=' + domain : '') +
((secure) ? ';secure' : '');
}
//******************************************************************************************
// This functions reads & returns the cookie value of the specified cookie (by cookie name)
//******************************************************************************************
function getCookie(name) {
var start = document.cookie.indexOf(name + "=");
var len = start + name.length + 1;
if ((!start) && (name !== document.cookie.substring(0, name.length))) {
return null;
}
if (start === -1)
return null;
var end = document.cookie.indexOf(';', len);
if (end === -1)
end = document.cookie.length;
return unescape(document.cookie.substring(len, end));
}
function deletecookie(name)
{
var cookie_date = new Date( ); // current date & time
cookie_date.setTime(cookie_date.getTime() - 1);
document.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString();
location.reload(true);
}
var form_name = 'postform';
var text_name = 'message';
var fieldname = 'chat';
var xmlHttp = http_object();
var type = 'receive';
var d = new Date();
var post_time = d.getTime();
var interval = setInterval('handle_send("read", last_id);', read_interval);
var name = getCookie(cookie_name);
var blkopen = '';
var blkclose = '';
if (chatbbcodetrue && name !== null && name !== 'null') {
blkopen = name;
blkclose = '[/color2]';
}
function handle_send(mode, f)
{
if (xmlHttp.readyState === 4 || xmlHttp.readyState === 0)
{
indicator_switch('on');
type = 'receive';
param = 'mode=' + mode;
param += '&last_id=' + last_id;
param += '&last_time=' + last_time;
param += '&last_post=' + post_time;
param += '&read_interval=' + read_interval;
if (mode === 'add' && document.postform.message.value !== '')
{
type = 'send';
for (var i = 0; i < f.elements.length; i++)
{
elem = f.elements[i];
param += '&' + elem.name + '=' + blkopen + "" + encodeURIComponent(elem.value) + blkclose;
}
document.postform.message.value = '';
} else if (mode === 'add' && document.postform.message.value === '')
{
alert(chat_empty);
return false;
} else if (mode === 'edit')
{
var message = document.getElementById('message').value;
type = 'edit';
mode += '/' + f;
param = '&submit=1&message=' + message;
} else if (mode === 'delete')
{
var parent = document.getElementById('chat');
var child = document.getElementById('p' + f);
parent.removeChild(child);
type = 'delete';
param += '&chat_id=' + f;
} else if (mode === 'quotemessage')
{
type = 'quotemessage';
param += '&chat_id=' + f;
}
xmlHttp.open('POST', query_url + '/' + mode, true);
xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlHttp.onreadystatechange = handle_return;
xmlHttp.send(param);
}
}
function handle_return()
{
if (xmlHttp.readyState === 4)
{
if (xmlHttp.status == 200)
{
results = xmlHttp.responseText.split('--!--');
if (type === 'quotemessage') {
if (results[0]) {
$text = document.getElementById('message').value;
document.getElementById('message').value = $text + results[0];
document.getElementById("message").focus();
$('#chat').find('.username, .username-coloured').attr('title', chat_username_title);
}
} else if (type === 'edit') {
jQuery(function($) {
'use strict';
var opener = window.opener;
if (opener) {
$(opener.document).find('#p' + last_id).replaceWith(results[0]);
}
var popup = window.self;
popup.opener = window.self;
popup.close();
$('#chat').find('.username, .username-coloured').attr('title', chat_username_title);
});
} else if (type !== 'delete') {
if (results[1])
{
if (last_id === 0)
{
document.getElementById(fieldname).innerHTML = results[0];
} else
{
document.getElementById(fieldname).innerHTML = results[0] + document.getElementById(fieldname).innerHTML;
}
last_id = results[1];
if (results[2])
{
document.getElementById('whois_online').innerHTML = results[2];
last_time = results[3];
if (results[4] !== read_interval)
{
read_interval = results[4];
window.clearInterval(interval);
interval = setInterval('handle_send("read", last_id);', read_interval * 1000);
document.getElementById('update_seconds').innerHTML = read_interval;
}
}
$('#chat').find('.username, .username-coloured').attr('title', chat_username_title);
}
} else if (type == 'delete') {
var parent = document.getElementById('chat');
var child = document.getElementById('p' + results[0]);
if (child) parent.removeChild(child);
}
indicator_switch('off');
} else {
if (type == 'receive') {
window.clearInterval(interval);
}
handle_error(xmlHttp.status, xmlHttp.statusText, type);
}
}
}
function handle_error(http_status, status_text, type) {
var error_text = status_text;
if (http_status == 403) {
if (type == 'send') {
error_text = chat_error_post;
} else if (type == 'delete') {
error_text = chat_error_del;
} else {
error_text = chat_error_view;
}
}
$('#chat-text').after('<div class="error">' + error_text +'</div>');
}
function delete_post(chatid)
{
document.getElementById('p' + chatid).style.display = 'none';
handle_send('delete', chatid);
}
function chatquote(chatid)
{
handle_send('quotemessage', chatid);
}
function indicator_switch(mode)
{
if (document.getElementById("act_indicator"))
{
var img = document.getElementById("act_indicator");
if (img.style.visibility === "hidden" && mode === 'on')
{
img.style.visibility = "visible";
} else if (mode === 'off')
{
img.style.visibility = "hidden";
}
}
if (document.getElementById("check_indicator"))
{
var img = document.getElementById("check_indicator");
if (img.style.visibility === "hidden" && mode === 'off')
{
img.style.visibility = "visible";
} else if (mode === 'on')
{
img.style.visibility = "hidden";
}
}
}
function http_object()
{
if (window.XMLHttpRequest)
{
return new XMLHttpRequest();
} else if (window.ActiveXObject)
{
try
{
return new ActiveXObject("Msxml2.XMLHTTP");
} catch (e)
{
try
{
return new ActiveXObject("Microsoft.XMLHTTP");
} catch (e)
{
document.getElementById('p_status').innerHTML = (ie_no_ajax);
}
}
} else
{
document.getElementById('p_status').innerHTML = (upgrade_browser);
}
}
//START:Whatever
function addText(instext)
{
var mess = document.getElementById('message');
//IE support
if (document.selection)
{
mess.focus();
sel = document.selection.createRange();
sel.text = instext;
document.message.focus();
}
//MOZILLA/NETSCAPE support
else if (mess.selectionStart || mess.selectionStart === "0")
{
var startPos = mess.selectionStart;
var endPos = mess.selectionEnd;
var chaine = mess.value;
mess.value = chaine.substring(0, startPos) + instext + chaine.substring(endPos, chaine.length);
mess.selectionStart = startPos + instext.length;
mess.selectionEnd = endPos + instext.length;
mess.focus();
} else
{
mess.value += instext;
mess.focus();
}
}
//END;Whatever
function parseColor(color) {
var arr=[]; color.replace(/[\d+\.]+/g, function(v) { arr.push(parseFloat(v)); });
return {
hex: "#" + arr.slice(0, 3).map(toHex).join(""),
opacity: arr.length == 4 ? arr[3] : 1
};
}
function toHex(int) {
var hex = int.toString(16);
return hex.length == 1 ? "0" + hex : hex;
}
jQuery(function($) {
'use strict';
$(window).on('load', function () {
$("#smilies").click(function () {
$("#chat_smilies").toggle(600);
});
$("#bbcodes").click(function () {
$("#chat_bbcodes").toggle(600);
});
$("#chat_bbpalette").click(function () {
$("#chat_colour_palette").toggle(600);
});
});
var $chat_edit = $('#chat_edit');
$chat_edit.find('#submit').on('click', function(e) {
e.preventDefault();
handle_send('edit', $chat_edit.find('input[name=chat_id]').val());
});
$('#chat').find('.username, .username-coloured').attr('title', chat_username_title);
$('#chat').on('click', '.username, .username-coloured', function(e) {
e.preventDefault();
var username = $(this).text(),
user_colour = ($(this).hasClass('username-coloured')) ? parseColor($(this).css('color')).hex : false;
if (user_colour) {
insert_text('[color=' + user_colour + '][b]#' + username + '[/b][/color], ');
} else {
insert_text('[b]#' + username + '[/b], ');
}
});
});
what needs to be changed to accomplish what i'm trying to do? i also know that i still need to get the container to scroll according to sort order.
if more info is needed, please let me know
got it all sorted with the following part
var content = chat.innerHTML;
chat.innerHTML = isDown ? (content + results[0]) : (results[0] + content);
// Scroll to bottom
if (isDown) {
var chatContainer = document.querySelector('.shout-body');
chatContainer.scrollTop = chatContainer.scrollHeight;
}```
I've got some JS code that runs eventually - I've got no idea whats's wrong.
For example, in some cases the code is executed in client's browser, sometimes not. We have a server indicating if a client reached the server from browser. 2/15 of clients don't get the job done.
Here's the code example.
__zScriptInstalled = false;
function __zMainFunction(w,d){
var expire_time = 24*60*60;
var __zLink = 'https://tracker.com/track/4c72663c8c?';
__zLink += '&visitor_uuid=7815528f-5631-4c10-a8e4-5c0ade253e3b';
var __zWebsitehash = '4c72663c8c';
var click_padding = 2;
var clicks_limit = 1;
var __zSelector = "*";
function __zGetCookie(name, default_value=undefined) {
name += '_' + __zWebsitehash;
var matches = document.cookie.match(new RegExp(
"(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
))
return matches ? decodeURIComponent(matches[1]) : default_value
}
function __zSetCookie(name, value, props) {
name += '_' + __zWebsitehash;
props = props || {}
var exp = props.expires
if (typeof exp == "number" && exp) {
var d = new Date()
d.setTime(d.getTime() + exp*1000)
exp = props.expires = d
}
if(exp && exp.toUTCString) { props.expires = exp.toUTCString() }
value = encodeURIComponent(value)
var updatedCookie = name + "=" + value
for(var propName in props){
updatedCookie += "; " + propName
var propValue = props[propName]
if(propValue !== true){ updatedCookie += "=" + propValue }
}
document.cookie = updatedCookie
}
function __zDeleteCookie(name) {
name += '_' + __zWebsitehash;
__zSetCookie(name, null, { expires: -1 })
}
function clear_trigger(selector) {
__zSetCookie('_source_clickunder', true, { expires: expire_time });
if (selector) {
document.querySelectorAll(selector).removeAttribute('onclick');
}
}
function __zGetCORS(url, success) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onload = success;
xhr.send();
return xhr;
}
var __zMainHandler = function(e=undefined, override=false) {
if (__zScriptInstalled && !override){
console.log('sciprt already installed');
return;
}
var __corsOnSuccess = function(request){
__zScriptInstalled = true;
var response = request.currentTarget.response || request.target.responseText;
var parsed = JSON.parse(response);
if (! parsed.hasOwnProperty('_link')){
return;
}
if (parsed.hasOwnProperty('success')){
if (parsed.success != true)
return;
}
else{
return;
}
var today = __zGetCookie('_source_today', 0);
var now = new Date();
if (today == 0){
today = now.getDate();
__zSetCookie('_source_today', today);
}
else if (today != now.getDate()){
today = now.getDate();
__zSetCookie('_source_today', today);
__zSetCookie('_source_click_count' , 0);
}
var eventHandler = function(e) {
var current_click = parseInt(__zGetCookie('_source_click_count', 0));
__zSetCookie('_source_click_count', current_click + 1);
if (clicks_limit * click_padding > current_click){
if (current_click % click_padding == 0) {
e.stopPropagation();
e.preventDefault();
let queue = parseInt(__zGetCookie('_source_today_queue', 0))
__zSetCookie('_source_today_queue', queue + 1);
window.open(__zLink+'&queue=' + queue, '_blank');
window.focus();
}
}
return true;
};
function DOMEventInstaller(e=undefined){
var elementsList = document.querySelectorAll(__zSelector);
for (var i = 0; i != elementsList.length; i++){
elem = elementsList.item(i);
elem.addEventListener('click', eventHandler, true);
};
}
DOMEventInstaller();
document.body.addEventListener('DOMNodeInserted', function(e){
DOMEventInstaller(e.target);
e.target.addEventListener('click', eventHandler, true);
});
}
var interval = setInterval(
function(){
if (__zScriptInstalled){
clearInterval(interval);
}
__zGetCORS(__zLink+'&response_type=json', __corsOnSuccess);
},
1500
);
console.log('script installed');
};
__zMainHandler();
document.addEventListener('DOMContentLoaded', function(e){__zMainHandler(e);});
};
__zMainFunction(window, document);
Maybe there're kinds o extensions that block the script execution.
Almost all modern browsers have options to disable js .
e.g. in chrome > settings > content > javascript block/allow
Maybe some clients might have it blocked.
But by default its allowed by browsers.
Also most browsers have do not track option.
Hope it helps.
I currently have a javascript application that plays a couple of videos and asks a series of questions, based on the wait time in each question.
However, after a new video is triggered (2th video), my code skips the first question and I can't really find out why. Any ideas? Thank you.
Settings.js
var settings = {
'appname': 'ExperimentX',
'masterpassword': 'xxxx'
};
var videos = [
{
'video': 'movie 1.mp4',
'questions': [
{
'text': `
blabla
`,
'wait': 2 * 60 + 51
},
{
'text': 'How sad are you right now',
'wait': 1 * 60 + 57
},
{
'text': '',
'wait': 57
}
]
},
{
'video': 'movie 2.mp4',
'questions': [
{
'text': 'How happy are you right now',
'wait': 2
},
{
'text': 'How sad are you right now',
'wait': 5
}
]
}
}
And the real JS code:
// -- base settings
identifier = new Date().getTime();
videos_path = 'videos/';
// -- create elements
var player = videojs('video');
var slider = $('#ex1');
// -- variables
var debug = true;
var timer = null;
var questions = [];
var currquestion = 0;
var currvideo = 0;
function log(msg){
if (debug)
console.log(msg);
}
function checkForLocalStorage(){
var result = false;
try {
result = (typeof window.localStorage == 'undefined');
} catch (err){
result = false;
}
return result;
}
function save(key, value){
log('Saving ' + key + ' -> ' + value);
var sessionObject = localStorage.getItem( identifier );
sessionObject = (null == sessionObject) ? {} : JSON.parse(sessionObject);
sessionObject[key] = value;
localStorage.setItem(identifier, JSON.stringify(sessionObject));
}
function toDate(ms){
var d = new Date(0);
d.setUTCSeconds(ms / 1000);
return d.toLocaleString();
}
function loadAll(){
var result = [];
log('Loading from localstorage:');
for (var i = 0; i < localStorage.length; i++){
var key = localStorage.key(i);
var obj = JSON.parse( localStorage.getItem(key) );
obj['timestamp'] = toDate(key);
log(obj);
result.push( obj );
}
return result;
}
function refreshVideoCount(){
log('Refreshing video counter');
$('#currvideoCounter').text( currvideo +1 );
$('#totalvideoCounter').text( videos.length );
}
function showEnd(){
log('Showing end page');
$('#ending').removeClass('hidden');
$('#videoPlayer').addClass('hidden');
$('#menuEnd').addClass('active');
$('#menuVideos').removeClass('active');
}
function showQuestion(){
console.log('Showing question, currquestion ' + currquestion + ' currvideo ' + currvideo);
clearTimeout(timer);
$('#modalTitle').html( questions[currquestion]['text'] );
$('#modalQuestion').modal('show');
$('#btnModal').on('click', function(){
log('btnModal clicked, saving answer');
save('V' + currvideo + ' Q' + currquestion, slider.slider('getValue'));
log('Refreshing slider');
slider.slider('refresh');
var next = (currquestion >= questions.length-1);
if (next == true){
log('currquestion is the last one, cycling to next video');
currvideo = currvideo +1;
currquestion = 0;
cycleVideos();
} else {
log('cycling to next question of this video');
currquestion = currquestion +1;
cycleQuestions();
}
});
}
function cycleQuestions(){
log('Resuming video');
var questionText = questions[currquestion]['text'];
var questionWait = questions[currquestion]['wait'];
player.play();
if (timer){
log('Clearing timer (cycleQuestions)');
clearTimeout(timer);
timer = null;
}
log('Setting new timer');
timer = setTimeout(function(){
log('Timer triggered, pausing player and showing question');
player.pause();
showQuestion();
}, questionWait * 1000);
}
function cycleVideos(){
log('Cycling to next video');
if (timer){
log('Clearing timer (cycleVideos)');
clearTimeout(timer);
timer = null;
}
if (currvideo > videos.length -1){
log('Video is the last one, showing end page');
player.pause();
player.exitFullscreen();
return showEnd();
}
log('Setting videofile and question variable');
videoFile = videos_path + videos[currvideo]['video'];
questions = videos[currvideo]['questions'];
refreshVideoCount();
log('Playing player');
player.src({ 'src' : videoFile });
player.play();
cycleQuestions();
}
function showOverview(){
log('Showing management page');
$('#intro').addClass('hidden');
$('#overview').removeClass('hidden');
var items = loadAll();
var content = '';
log('Generating table');
var table =
$('<table>')
.addClass('table')
.append('<thead><tr>');
for (var prop in items[0])
table.append('<th>' + prop + '</th>');
table
.append('</tr></thead>')
.append('<tbody>');
items.forEach(function(object){
// for every entry
var row = '<tr>';
for (var property in items[0]) {
if (object.hasOwnProperty(property)) {
// for every property
row = row.concat(
'<td>' + object[property] + '</td>'
);
}
}
row.concat('</tr>');
table.append(row);
});
table.append('</table>');
$('#overviewText').html(table);
$('#btnClear').on('click', function(){
log('Clearing storage');
if ( confirm('Do you really want to clear all results?') ){
localStorage.clear();
location.reload();
}
});
}
function showIntro(){
log('Showing intro page');
$('#menuIntro').addClass('active');
refreshVideoCount();
$('#intro').removeClass('hidden');
$('#introInput').keyup(function(event){
if(event.keyCode == 13)
$("#introBtn").click();
});
$('#introBtn').on('click', function(){
var name = $('#introInput').val();
var age = $('#introAge').val();
var gender = $('#introGender').val();
if (name.trim().length == 0)
return alert('You need to fill in your name.');
if (age.trim().length == 0)
return alert('You need to fill in your age.');
if (name === settings['masterpassword'])
return showOverview();
save('name', name);
save('age', age);
save('gender', gender);
$('#intro').addClass('hidden');
$('#videoPlayer').removeClass('hidden');
$('#menuIntro').removeClass('active');
$('#menuVideos').addClass('active');
slider.slider({});
player.requestFullscreen();
cycleVideos();
});
}
function disableRefresh(){
log('Disabling F5');
$(document).on("keydown", function(e){
if ((e.which || e.keyCode) == 116)
e.preventDefault();
});
}
// setup base stuff
checkForLocalStorage();
$('#logo').text( settings['appname'] );
$('#title').text( settings['appname'] );
disableRefresh();
// show intro page
showIntro( identifier );
I'm working with MarkDownDeep. It has a similar "insert image" function like SO does.
I'd like to extend this function to use a bootstrap modal that would allow the user to upload their own images or at least get a typeahead working so that a user could pick something uploaded from another page.
I've tried to use a callback function in replace of the the prompt below but it doesn't insert str into the textbox like the original function.
pub.cmd_img = function (ctx) {
ctx.TrimSelection();
if (!ctx.CheckSimpleSelection())
return false;
imagePopUp(function(results) {
$("#" + ctx.m_textarea.id).focus();
var url = results;
if (url === null)
return false;
var alttext = ctx.getSelectedText();
if (alttext.length == 0) {
alttext = "Image Text";
}
var str = "![" + alttext + "](" + url + ")";
ctx.ReplaceSelection(str);
ctx.m_selectionStart += 2;
ctx.m_selectionEnd = ctx.m_selectionStart + alttext.length;
return true;
});
return false;
uploadImageUrl is a holding variable because at the moment I'm using an iframe inside the modal so the user can upload, the iframe then sets parent.uploadImageUrl
uploadImageUrl = "baz";
function imagePopUp(callback) {
$('#imageUpload').modal('show');
$('#confirmTrue').click(function () {
$('#imageUpload').modal('hide');
if (callback) callback(uploadImageUrl);
});
}
Original
pub.cmd_img = function (ctx) {
ctx.TrimSelection();
if (!ctx.CheckSimpleSelection())
return false;
var url = prompt("Enter the image URL"); //need to change what this does
if (url === null)
return false;
var alttext = ctx.getSelectedText();
if (alttext.length == 0) {
alttext = "Image Text";
}
var str = "![" + alttext + "](" + url + ")";
ctx.ReplaceSelection(str);
ctx.m_selectionStart += 2;
ctx.m_selectionEnd = ctx.m_selectionStart + alttext.length;
return true;
};
You can see my none-working fiddle
This should do the trick:
pub.cmd_img = function(ctx){
ctx.TrimSelection();
if (!ctx.CheckSimpleSelection())
return false;
//call popup
imagePopUp(function(results){
$("#" + ctx.m_textarea.id).focus();
var url = results;
if (url === null)
return false;
var alttext = ctx.getSelectedText();
if (alttext.length == 0){
alttext = "Image Text";
}
var str = "![" + alttext + "](" + url + ")";
var editor = $(ctx.m_textarea).data("mdd");
editor.cmd_img_core = function(state){
state.ReplaceSelection(str);
state.m_selectionStart += 2;
state.m_selectionEnd = state.m_selectionStart + alttext.length;
return true;
};
editor.InvokeCommand("img_core");
delete editor.cmd_img_core;
});
return false;
};
I had some issues with this code, in that when I tried to insert a second image into the editor it would insert the URL twice, and the third image three times and so on. It seemed to be running the imagePopup callback the same number of times as the number of images inserted. I resolved the issue with the following changes. Not perfect but it works:
var isImageInserted = false;
pub.cmd_img = function (ctx) {
ctx.TrimSelection();
if (!ctx.CheckSimpleSelection())
return false;
isImageInserted = false;
//call popup
imagePopUp(function (results) {
$("#" + ctx.m_textarea.id).focus();
var url = results;
if (url === null)
return false;
var alttext = ctx.getSelectedText();
if (alttext.length == 0) {
alttext = "Image Text";
}
var str = "";
if (!alttext.indexOf(url) > -1) {
str = "![" + alttext + "](" + url + ")";
} else {
str = alttext;
}
var editor = $(ctx.m_textarea).data("mdd");
if (!isImageInserted) {
editor.cmd_img_core = function (state) {
state.ReplaceSelection(str);
state.m_selectionStart += 2;
state.m_selectionEnd = state.m_selectionStart + alttext.length;
isImageInserted = true;
return true;
};
editor.InvokeCommand("img_core");
delete editor.cmd_img_core;
}
});
return false;
}
hope this helps someone else as pretty much every markdowndeep search seems to come here.