Alterting cute file browser to be comaptible with any jquery version - javascript

I have been experimenting with cute file browser (perfect for my project).
Cute File Browser
But came accross a incomaptibiliy issue. Im not getting any errors in console, but im also not getting any elements being rendered. I have switched libraries about and I think this plugin only works with jquery version 1.11.0, the version my project is using is 1.11.3.
How should I attempt to fix/update this small script?
CUTE SCRIPT:
$(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', 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);
});
}
// Generate the breadcrumbs
var url = '';
if(filemanager.hasClass('searching')){
url = '<span>Search results: </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];
}
});
});

I tweaked certain jquery methods around in the render function using the 1.11.3 version and it appears animate() was causing the issues.
Change Script.js line 375:
From fileList.animate({'display':'inline-block'});
To fileList.css('display','inline-block');.
EDIT:
I noticed a slightly more improved method of revealing the hidden filelist without using inline styles and adding it to a more appoporate section of the script. Simply use filelist.show() in the following section of the render function.
change Script.js line 286-291:
if(!scannedFolders.length && !scannedFiles.length) {
filemanager.find('.nothingfound').show();
fileList.hide();
}
else {
filemanager.find('.nothingfound').hide();
fileList.show();
}
Hiding the filelist using filelist.hide() also helped me with a style bug relating to the .nothing-found error message being pushed down to the bottom of the page when needing to use a fixed height on the filelist.
Now im not depenedant on what version of jquery im using. Hope this helps others using this nice little script.

Related

How to call a function declared in a separate php file from a different javascript file

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];
}
});
});

Updating the text of a button with javascript

I'm trying to update the button as it counts down to a link being live, but the button text is not being updated...
here's my script
var meetings_default_view_default = {
start: function () {
window.setInterval(function () {
var _div = $('.meetings_wrapper');
var _meeting_id = [];
var _url = _div.data('url');
// Collect all the relevant meeting ids
_div.children().each(function () {
_meeting_id.push($(this).data('id'));
});
if (!_meeting_id.length) {
return;
}
$.post(_url, {meeting_id: _meeting_id}, function(data) {
if (data.alert) {
alert(data.alert);
return false
};
// if (!data.meeting_id) {
// alert('No data returned');
// }
for (var i in data.meeting_id) {
var meeting_data = data.meeting_id[ i ];
var meeting_id = meeting_data[ 'id' ];
// locate the start button *within* the panel with the appropriate id
var _button = _div.find('.panel[data-id=' + meeting_id + '] a.button').last();
var _css = 'button';
if (meeting_data['css_class']) {
_css += ' ' + meeting_data['css_class'];
}
_button.attr('class',_css);
if (meeting_data['label']) {
_button.find('span').text(meeting_data['label']);
}
}
});
}, 60000);
}
};
$(meetings_default_view_default.start);
everything else ( css ) changes, just not the text of the button ? been staring at this for ages now !
sorry, another silly mistake when tired. This works fine...
if (meeting_data['label']) {
_button.text(meeting_data['label']);
}
Even better - this does not overwrite the tags in the button element it just updates the text part.
if (meeting_data['label']) {
_button.textContent = meeting_data['label'];
}

Fadein callback not working properly with ajax-loaded json data

This is a design portfolio page. On load, the JSON data is retrieved via ajax, and one of the keys is used to generate a list of '.project-links' (no project is displayed on load, and the project images are loaded only when a project is selected (see showProj function)). My question regards the fadein/fadeout: the images are still painting onto the screen after the fade in completes, despite the project content being defined/loaded within the fadeOut callback; can someone please enlighten me as to how I can tweak this so that the fadeIn won't run until the projImages are loaded?
Thank you, svs.
function ajaxReq() {
var request = new XMLHttpRequest();
return request;
}
function makeLinks(projects) { // result = getJsonData > request.responseText
var projectList = document.getElementById("project-list");
for (var project in projects) {
if (projects[project].status !== "DNU") {
var projectId = projects[project].id;
var listItem = "<li><a class=\"project-link\" id=\""+projects[project].project+"\" href=\"#\">" + projects[project].project + "</a></li>";
projectList.innerHTML += listItem;
} // if !DNU
}
// ADD EVENT LISTENERS
var projLink = document.getElementsByClassName("project-link");
for (var i = 0; i < projLink.length; i++) {
var projId = projLink[i].id;
//projLink[i].dataset.projIx = [i];
projLink[i].addEventListener("click", showProject, false);
}
var showNext = document.getElementById("show-next");
var showPrev = document.getElementById("show-previous");
showNext.addEventListener("click", showProject, false);
showPrev.addEventListener("click", showProject, false);
// ARROW KEYS [not invoking the showProject function]
$(document).keydown(function(e) {
if(e.which==37) { // LEFT arrow
$(showPrev).click(showProject);
console.log("previous");
} else
if(e.which==39) { // RIGHT arrow
$(showNext).click(showProject);
console.log("next");
}
})
function showProject(projId) {
var intro = document.getElementById("intro");
if (intro) {
intro.parentNode.removeChild(intro);
}
projId.preventDefault();
var projLinks = document.getElementsByClassName("project-link"); // array
var selIx = $(".selected").index();
// ###### CLICK PREVIOUS/NEXT ######
if (this.id === "show-previous" || this.id === "show-next") {
// 1a. if nothing is .selected
if (selIx < 0) {
if (this.id === "show-previous") {
var selIx = projLinks.length-1;
}
else if (this.id === "show-next") {
var selIx = 0;
}
}
// 1b. if .selected:
else if (selIx > -1) {
if (this.id === "show-previous") {
if (selIx === 0) { // if # first slide
selIx = projLinks.length-1;
}
else {
selIx --;
}
}
else if (this.id === "show-next") {
if (selIx === projLinks.length-1) { // if # last slide
selIx = 0;
}
else {
selIx ++;
}
}
}
var selProjLi = projLinks[selIx]; // => li
} // click previous/next
// ###### CLICK .project-link ######
else if (this.id !== "show-previous" && this.id !== "show-next") {
var selIx = $(this).closest("li").index();
}
// FADE OUT, CALLBACK: LOAD NEW PROJECT
$("#project-display").fadeTo(450, 0.0, function() {
// ###### ALL ######
$(".selected").removeClass("selected");
var projId = projLink[selIx].id;
var selProjLi = projLink[selIx].parentElement;
selProjLi.className = "selected";
var projectDisplay = document.getElementById("project-display");
// set vars for the project display elements:
var projName = document.getElementById("project-name"); // h3
var projTools = document.getElementById("project-tools");
var projNotes = document.getElementById("project-notes");
var projImages = document.getElementById("project-images");
// disappear the metadata elements 'cause sometimes they'll be empty
projTools.style.display = "none";
projNotes.style.display = "none";
testimonial.style.display = "none";
for (var project in projects) { // 'Projects array' -> project
if (projects[project].project === projId) {
var activeProj = projects[project];
projName.innerHTML = activeProj.project;
// maintain centered display of project-metadata: check for a value, else the element remains hidden
if(activeProj["tools used"]) {
projTools.style.display = "inline-block";
projTools.innerHTML = activeProj["tools used"];
}
if(activeProj.notes) {
projNotes.style.display = "inline-block";
projNotes.innerHTML = activeProj.notes;
}
if(activeProj.testimonial) {
testimonial.style.display = "inline-block";
testimonial.innerHTML = activeProj.testimonial;
}
// HOW TO ENSURE THESE ARE ALREADY LOADED ***BEFORE #project-display FADES IN***
projImages.innerHTML = "";
for (var i = 0; i < activeProj.images.length; i++ ) {
projImages.innerHTML += "<img src=\"" + activeProj.images[i].url + "\" />";
}
} // if project id ...
} // for (var obj in data)
}) // fade out
$("#project-display").fadeTo(600, 1.0);
} // showProject
} // makeLinks
function getJsonData() {
var request = ajaxReq();
request.open("GET", "/json/projects.json", true);
request.setRequestHeader("content-type", "application/json");
request.send(null);
request.onreadystatechange = function() {
if (request.readyState === 4) {
if (request.status === 200) {
//makeLinks(request.responseText);
var projects = JSON.parse(request.responseText);
var projects = projects["Projects"];
makeLinks(projects); // makeLinks = callback
return projects;
}
}
} // onreadystatechange
} // getJsonData
getJsonData(makeLinks);
You can add a load event to the images and run the fadeOut when all the images are loaded.
Since you are going to need multiple images to complete loading, I chose to keep track of which loads are complete using an array of jQuery.Deferred() objects. Once all the Deferreds are resolved then you can run the fade animation.
Here's a function that should work:
function fadeWhenReady(projImages, images) {
projImages.innerHTML = "";
var loads = []; //create holding bin for deferred calls
//create images and attach load events
for (var i = 0; i < activeProj.images.length; i++ ) {
var deferred = $.Deferred();
var img = $("<img src=\"" + activeProj.images[i].url + "\" />");
img.on("load", function() { deferred.resolve() }); //after image load, resolve deferred
loads.push(deferred.promise()); //add the deferred event to the array
img.appendTo(projImages); //append image to the page
}
//when all deferreds are resolved, then apply the fade
$.when.apply($, loads).done(function() {
$("#project-display").fadeTo(600, 1.0);
});
}
In your function showProject remove your call to $("#project-display").fadeTo(600, 1.0); and replace the lines below with a call to the fadeWhenReady function.
projImages.innerHTML = "";
for (var i = 0; i < activeProj.images.length; i++ ) {
projImages.innerHTML += "<img src=\"" + activeProj.images[i].url + "\" />";
}
P.S. You are using a strange mix of jQuery and vanilla javascript. The calls to document.getElementById() don't mind me so much, but I'd certainly recommend replacing your XMLHttpRequests with jQuery.ajax().

How to create a plugin to add attachment or file in rich text editor of Adobe CQ 5?

I need help in creating a plugin for rich text editor in Adobe cq 5 to add an image, pdf, video, ppt or any file into rich text editor.
The existing rte plugins that are available are findreplace, undo, spellcheck, table etc
How to create a plugin to add a file to rich text editor?
The plugins are an ext js files. Appreciate if any one can suggest answer. It will be of great help.
Thanks
I added a custom drop down into my RTE. It was used to add values to the editor on selecting values from it. I think this might help you solve your issue because similarly you can create your required plugin.
Please refer comments next to the methods for your reference.
/**
* Placeholder Plugin
*/
var keyvalueEnteries = [];
var newText;
var doc;
var range
CUI.rte.plugins.PlaceholderPlugin = new Class({
toString: "PlaceholderPlugin",
extend: CUI.rte.plugins.Plugin,
/**
* #private
*/
cachedFormats: null,
/**
* #private
*/
formatUI: null,
getFeatures: function() {
return [ "Myparaformat" ];
},
/**
* #private
*
*/
getKeys: function() {
var com = CUI.rte.Common;
if (this.cachedFormats == null) {
this.cachedFormats = this.config.formats || { };
com.removeJcrData(this.cachedFormats);
this.cachedFormats = com.toArray(this.cachedFormats, "tag", "description");
}
return this.cachedFormats;
},
initializeUI: function(tbGenerator) {
var plg = CUI.rte.plugins;
var ui = CUI.rte.ui;
if (this.isFeatureEnabled("placeHolder")) {
this.formatUI = tbGenerator.createParaFormatter("placeHolder", this,null,this.getKeys());
tbGenerator.addElement("placeHolder", plg.Plugin.SORT_PARAFORMAT, this.formatUI,
10);
}
},
notifyPluginConfig: function(pluginConfig) { //This function gets executed once on load of RTE for the first time
var url = pluginConfig.sourceURL;
keyvalueEnteries = CQ.HTTP.eval(url);
keyvalueEnteries = JSON.stringify(keyvalueEnteries);
if(keyvalueEnteries == undefined){
keyvalueEnteries = '[{"key":"","value":"None"}]';
}
pluginConfig = pluginConfig || { };
//creating JSON sttructure
var placeholderJSON = '{"formats":' + keyvalueEnteries + '}';
var placeHolderVals = eval('(' + placeholderJSON + ')');
var defaults = placeHolderVals;
if (pluginConfig.formats) {
delete defaults.formats;
}
CUI.rte.Utils.applyDefaults(pluginConfig, defaults);
this.config = pluginConfig;
},
execute: function(cmd) { // This function gets executed when there is change in the state of custom plugin/drop down
if (this.formatUI) {
var formatId = this.formatUI.getSelectedFormat();
if (formatId && range != undefined) {
var placeholderElement = "";
if(formatId == 'none' && range.collapsed == false){//checks if None is selected in placeholder and the text is selected
range.deleteContents();
}else if(formatId != 'none'){
placeholderElement = document.createTextNode(" ${" + formatId + "} ");
range.insertNode(placeholderElement); //INSERTS PLACEHOLDER AT CURRENT CARET LOCATION
range.setStartAfter(placeholderElement);//INSERTS CURSOR AT THE END OF CURRENT PLACEHOLDER IF PLACEHOLDER IS SELECTED AGAIN
}
}
}
},
updateState: function(selDef) { // This function gets executed on click on the editor space in RTE
doc = selDef.editContext.doc; //GET THE DOCUMENT INSIDE THE IFRAME
range = doc.getSelection().getRangeAt(0); //GETS CURRENT CARET POSITION
}
});
//register plugin
CUI.rte.plugins.PluginRegistry.register("placeholder",
CUI.rte.plugins.PlaceholderPlugin);
CUI.rte.ui.ext.ParaFormatterImpl = new Class({
toString: "ParaFormatterImpl",
extend: CUI.rte.ui.TbParaFormatter,
// Interface implementation ------------------------------------------------------------
addToToolbar: function(toolbar) {
var com = CUI.rte.Common;
this.toolbar = toolbar;
if (com.ua.isIE) {
// the regular way doesn't work for IE anymore with Ext 3.1.1, hence working
// around
var helperDom = document.createElement("span");
helperDom.innerHTML = "<select class=\"x-placeholder-select\">"
+ this.createFormatOptions() + "</select>";
this.formatSelector = CQ.Ext.get(helperDom.childNodes[0]);
} else {
this.formatSelector = CQ.Ext.get(CQ.Ext.DomHelper.createDom({
tag: "select",
cls: "x-placeholder-select",
html: this.createFormatOptions()
}));
}
this.initializeSelector();
toolbar.add(
CQ.I18n.getMessage("Placeholder"), // Type the name you want to appear in RTE for the custom plugin /drop down
" ",
this.formatSelector.dom);
},
/**
* Creates HTML code for rendering the options of the format selector.
* #return {String} HTML code containing the options of the format selector
* #private
*/
createFormatOptions: function() {
var htmlCode = "";
if (this.formats) {
var formatCnt = this.formats.length;
htmlCode += "<option value='none'>None</option>";
for (var f = 0; f < formatCnt; f++) {
var text = this.formats[f].text;
htmlCode += "<option value=\"" + this.formats[f].value + "\">" + text
+ "</option>";
}
}
return htmlCode;
},
createToolbarDef: function() {
return {
"xtype": "panel",
"itemId": this.id,
"html": "<select class=\"x-placeholder-select\">"
+ this.createFormatOptions() + "</select>",
"listeners": {
"afterrender": function() {
var item = this.toolbar.items.get(this.id);
if (item && item.body) {
this.formatSelector = CQ.Ext.get(item.body.dom.childNodes[0]);
this.initializeSelector();
}
},
"scope": this
}
};
},
initializeSelector: function() {
this.formatSelector.on('change', function() {
var format = this.formatSelector.dom.value;
if (format.length > 0) {
this.plugin.execute(this.id);
}
}, this);
this.formatSelector.on('focus', function() {
this.plugin.editorKernel.isTemporaryBlur = true;
}, this);
// fix for a Firefox problem that adjusts the combobox' height to the height
// of the largest entry
this.formatSelector.setHeight(20);
},
getSelectorDom: function() {
return this.formatSelector.dom;
},
getSelectedFormat: function() {
var format;
if (this.formatSelector) {
format = this.formatSelector.dom.value;
if (format.length > 0) {
return format;
}
} else {
var item = this.toolbar.items.get(this.id);
if (item.getValue()) {
return item;
}
}
return null;
},
selectFormat: function(formatToSelect, auxRoot, formatCnt, noFormatCnt) {
var indexToSelect = -1;
var selectorDom = this.formatSelector.dom;
if ((formatToSelect != null) && (formatCnt == 1) && (noFormatCnt == 0)) {
var options = selectorDom.options;
for (var optIndex = 0; optIndex < options.length; optIndex++) {
var optionToCheck = options[optIndex];
if (optionToCheck.value == formatToSelect) {
indexToSelect = optIndex;
break;
}
}
}
selectorDom.disabled = (noFormatCnt > 0) && (auxRoot == null);
selectorDom.selectedIndex = indexToSelect;
}
});

Javascript Events using HTML Class Targets - 1 Me - 0

I am trying to create collapsible DIVs that react to links being clicked. I found how to do this using "next" but I wanted to put the links in a separate area. I came up with this which works...
JSFiddle - Works
function navLink(classs) {
this.classs = classs;
}
var homeLink = new navLink(".content-home");
var aboutLink = new navLink(".content-about");
var contactLink = new navLink(".content-contact");
var lastOpen = null;
$('.home').click(function() {
if(lastOpen !== null) {
if(lastOpen === homeLink) {
return; } else {
$(lastOpen.classs).slideToggle('fast');
}
}
$('.content-home').slideToggle('slow');
lastOpen = homeLink;
}
);
$('.about').click(function() {
if(lastOpen !== null) {
if(lastOpen === aboutLink) {
return; } else {
$(lastOpen.classs).slideToggle('fast');
}
}
$('.content-about').slideToggle('slow');
lastOpen = aboutLink;
}
);
$('.contact').click(function() {
if(lastOpen !== null) {
if(lastOpen === contactLink) {
return; } else {
$(lastOpen.classs).slideToggle('fast');
}
}
$('.content-contact').slideToggle('slow');
lastOpen = contactLink;
}
);​
I am now trying to create the same result but with a single function instead of one for each link. This is what I came up with....
function navLink(contentClass, linkClass, linkId) {
this.contentClass = contentClass;
this.linkClass = linkClass;
this.linkId = linkId;
}
var navs = [];
navs[0] = new navLink(".content-home", "nav", "home");
navs[1] = new navLink(".content-about", "nav", "about");
navs[2] = new navLink(".content-contact", "nav", "contact");
var lastOpen = null;
$('.nav').click(function(event) {
//loop through link objects
var i;
for (i = 0; i < (navsLength + 1); i++) {
//find link object that matches link clicked
if (event.target.id === navs[i].linkId) {
//if there is a window opened, close it
if (lastOpen !== null) {
//unless it is the link that was clicked
if (lastOpen === navs[i]) {
return;
} else {
//close it
$(lastOpen.contentClass).slideToggle('fast');
}
}
//open the content that correlates to the link clicked
$(navs[i].contentClass).slideToggle('slow');
navs[i] = lastOpen;
}
}
});​
JSFiddle - Doesn't Work
No errors so I assume that I am just doing this completely wrong. I've been working with Javascript for only about a week now. I've taken what I've learned about arrays and JQuery events and tried to apply them here. I assume I'm way off. Thoughts? Thanks
You just forgot to define navsLength:
var navsLength=navs.length;
Of course you could also replace it with a $().each loop as you're using jQuery.
[Update] Two other errors I corrected:
lastOpen=navs[i];
for(i=0; i < navsLength ; i++)
Demo: http://jsfiddle.net/jMzPJ/4/
Try:
var current, show = function(){
var id = this.id,
doShow = function() {
current = id;
$(".content-" + id).slideToggle('slow');
},
toHide = current && ".content-" + current;
if(current === id){ //Same link.
return;
}
toHide ? $(toHide).slideToggle('fast', doShow): doShow();;
};
$("#nav").on("click", ".nav", show);
http://jsfiddle.net/tarabyte/jMzPJ/5/

Categories