I want to add a button in javascript code I have which stores the heart rate from Gear 2 using Tizen sdk. In my code, the main div is inserted inside javascript code. I am using the following code:
//HTML CODE:
<div id="chartContainer" class="chart"></div>
//JAVASCRIPT CODE:
var chart = new CanvasJS.Chart("chartContainer",{
title :{
fontColor: "#ccc",
text: "Heart Rate"
},
backgroundColor: "#222",
data: [{
color: "#CD5C5C",
type: "line",
dataPoints: dps
}]
});
var lastSecond = -1;
var updateChart = function (heartrate) {
time = new Date().getTime() - initial;
console.log("[" + time + ", " + heartrate + "]");
temp = heartrate;
console.log("tempVar"+ temp);
tizen.filesystem.resolve(
'documents',
function(dir){
documentsDir = dir; dir.listFiles(onsuccess,onerror);
}, function(e) {
console.log("Error" + e.message);
}, "a"
);
dps.push({
x: time / 1000.0,
y: heartrate
});
if (dps.length > dataLength)
{
dps.shift();
}
var second = Math.round(time / 1000.0);
console.log(history.length);
if(lastSecond != second) {
// TODO use avg heart rate instead of smapshot.
history.push({
x: second,
y: heartrate
});
if(history.length > historyDataLength) {
history.shift();
}
lastSecond = second;
}
if(dps.length >= dataLength) {
chart.render();
}
var hrchart = "<center>" + heartrate + "bps</center><table width='100%' cellpadding=4px>";
for(var i = history.length - historyDataLength; i >= 0 && i < history.length; i++) {
hrchart += "<tr><td align='right' width='50%'>" + history[i].x + "s</td><td width='50%'>" + history[i].y + "bps</td></tr>";
}
hrchart += "</table>";
$('#textbox').html(hrchart);
};
updateChart(0);
updateChart(250);
for(var i = 0; i < dataLength; i++) {
updateChart(0);
}
I want to create a two buttons one for closing the application on click and one for storing data on click . How can I add those two buttons inside javascript code? Secondly is anyone familiar with "tizenhwkey" key? Which key is exactly? Thirdly I open the heartrate sensor using the following command window.webapis.motion.start("HRM", onchangedCB). How can I close the heart rate sensor? Function onchangeCB is the following:
function onchangedCB(hrmInfo)
{
if(hrmInfo.heartRate > 0) {
// add eventListener for tizenhwkey
document.addEventListener('tizenhwkey', function(e) {
if(e.keyName == "back")
tizen.application.getCurrentApplication().exit();
});
updateChart(hrmInfo.heartRate);
} else {
$('#textbox').html("No heart rate detected.");
}
}
This suppose to close application when pressing back button. However gear 2 has only one button. Is this button the tiwzenhwkey? For the hrm I am using the following code. For writing in file I am using:
function onsuccess(files) {
var testFile = null;
try{
testFile = documentsDir.createFile("test.txt");
if (testFile !== null) {
testFile.openStream(
"a",
function(fs){
fs.write(temp+"\n\n\n");
fs.close();
}, function(e){
console.log("Error " + e.message);
}, "UTF-8"
);
}
}
catch (e) { // file already exist -> append content
testFile = documentsDir.resolve('test.txt');
if(testFile !== null)
{
testFile.openStream(
"a",
function(fs){
fs.write(temp+"\n\n\n");
fs.close();
}, function(e){
console.log("Error " + e.message);
}, "UTF-8"
);
}
}
}
function onerror(error) {
console.log("The error " + error.message + " occurred when listing the files in the selected folder");
}
and
temp = heartrate;
tizen.filesystem.resolve(
'documents',
function(dir){
documentsDir = dir;
dir.listFiles(onsuccess,onerror);
}, function(e) {
console.log("Error" + e.message);
}, "a"
);
1. Create button in JS code
var b1 = document.createElement("BUTTON"); // Create Button
var b2 = document.createElement("BUTTON");
// Assign text to your button
b1.textContent = "Start";
b2.textContent = "Exit";
// Register click handlers to call respective functions
b1.onclick = function() {/*Code here*/};
b2.onclick = function() {/*Code here*/};
// Append them in your DOM i.e to show it on your page.
// Suppose to append it to an existing element in your page with id as "appp".
var attachTo = document.getElementById("appp");
attachTo.appendChild(b1);
attachTo.appendChild(b2);
2. TIZENHWKEY
On Gear, 'tizenhwkey' means "Swipe down" gesture and "Swipe UP" gesture.
Swipe Down acts as back key similar to how it works on phone. Swipe Up acts as menu button similar to how it works on phone
You can use below code to handle both the gestures I mentioned above.
document.addEventListener('tizenhwkey', function(e) {
if(e.keyName == "menu") {
}
if(e.keyName == "back") {
// you need to write exit statement
tizen.application.getCurrentApplication().exit();
}
}
Regarding HRM stop - use this to stop monitoring HRM.
webapis.motion.stop("HRM");
New line Issue - try this its working.
fs.write(temp + "\n\n\n");
I'm still a beginner but i know the basics on how to open a window and close it. Maybe this can help you.
<button onclick="openWin()">Open "myWindow"</button>
<button onclick="closeWin()">Close "myWindow"</button>
<script>
var myWindow;
function openWin() {
myWindow = window.open("", "myWindow", "width=200, height=100");
myWindow.document.write("<p>This is 'myWindow'</p>");
}
function closeWin(){
myWindow.close();
}
Related
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'];
}
As of now, I can successfully upload an image and display it in the browser and display that it has 0 likes initially.
What I'm trying to achieve is that when the user double clicks on the image, the 0 likes should become 1 likes (I know it's not grammatically correct, I just want it to function properly first before moving onto that issue).
If you look at the console logs, it indeed shows the like number switching back and forth with every double click, which's good. The bad part is I'm not sure how to display that change in the browser.
I've tried so many different ways but running out of options. What am I doing wrong and how can I fix this?
JS file:
function previewImages() {
var preview = document.createElement('div');
preview.className = "preview";
document.body.appendChild(preview);
if (this.files) {
[].forEach.call(this.files, readAndPreview);
}
function readAndPreview(file) {
// Make sure `file.name` matches our extensions criteria
if (!/\.(jpe?g|png|gif)$/i.test(file.name)) {
return alert(file.name + " is not an image");
} // else...
var reader = new FileReader();
reader.addEventListener("load", function () {
var image = new Image();
image.height = 100;
image.title = file.name;
image.src = this.result;
var initialCountOfLikes = 0;
var zeroLikes = document.createElement('p');
var zeroLikesTextNode = document.createTextNode(initialCountOfLikes + " likes");
document.body.appendChild(zeroLikes.appendChild(zeroLikesTextNode));
preview.appendChild(image);
image.onclick = function (event) {
if (event.detail === 2 && initialCountOfLikes === 0) {
console.log("clicked twice");
initialCountOfLikes++;
console.log("initialCountOfLikes++ => " + initialCountOfLikes);
}
else if(event.detail === 2 && initialCountOfLikes === 1) {
console.log("inside second if block");
initialCountOfLikes--;
console.log("initialCountOfLikes-- => " + initialCountOfLikes);
}
document.body.appendChild(zeroLikes.appendChild(zeroLikesTextNode));
};
});
reader.readAsDataURL(file);
}
}
document.querySelector('#file-input').addEventListener("change", previewImages);
Here's my HTML:
<div id="file-input-wrapper">
<input type="file" id="file-input" name="files" style="display: none;"/>
<label for="file-input" id="LblBrowse">
Upload your photo!
</label>
</div>
console logs:
clicked twice
index.js:126 initialCountOfLikes++ => 1
index.js:130 inside second if block
index.js:132 initialCountOfLikes-- => 0
index.js:124 clicked twice
index.js:126 initialCountOfLikes++ => 1
index.js:130 inside second if block
index.js:132 initialCountOfLikes-- => 0
This works. Your event.detail is registering as one, so I changed your listener to a dblClick event and removed that from the if statement. And nodes use nodeValue instead of innerText, so corrected in solution.
window.onload = function(){
function previewImages() {
var preview = document.createElement('div');
preview.className = "preview";
document.body.appendChild(preview);
if (this.files) {
[].forEach.call(this.files, readAndPreview);
}
function readAndPreview(file) {
// Make sure `file.name` matches our extensions criteria
if (!/\.(jpe?g|png|gif)$/i.test(file.name)) {
return alert(file.name + " is not an image");
} // else...
var reader = new FileReader();
reader.addEventListener("load", function () {
var image = new Image();
image.height = 100;
image.title = file.name;
image.src = this.result;
var initialCountOfLikes = 0;
var zeroLikes = document.createElement('p');
var zeroLikesTextNode = document.createTextNode(initialCountOfLikes + " likes");
document.body.appendChild(zeroLikes.appendChild(zeroLikesTextNode));
preview.appendChild(image);
image.ondblclick = function (event) {
if (initialCountOfLikes === 0) {
console.log("clicked twice");
initialCountOfLikes++;
console.log("initialCountOfLikes++ => " + initialCountOfLikes);
}
else if(initialCountOfLikes === 1) {
console.log("inside second if block");
initialCountOfLikes--;
console.log("initialCountOfLikes-- => " + initialCountOfLikes);
}
zeroLikesTextNode.nodeValue = initialCountOfLikes + " likes";
document.body.appendChild(zeroLikes.appendChild(zeroLikesTextNode));
};
});
reader.readAsDataURL(file);
}
}
document.querySelector('#file-input').addEventListener("change", previewImages);
}
You can start a timer, and measure the time between clicks, when the image is clicked. If the time between clicks is less than some number, then you can increase your count.
Something like the following:
firstClick = true;
let timer = new Date().getMilliseconds();
let someValue; // set this
image.onclick = function (event) {
let currentTime = new Date().getMilliseconds();
if(firstClick){
timer = new Date().getMilliseconds();
}
let difference = currentTime - timer;
if(difference >= someValue && !firstClick){
return;
}
firstClick = !firstClick;
timer = new Date().getMilliseconds();
if (event.detail === 2 && initialCountOfLikes === 0 && !firstClick) {
console.log("clicked twice");
initialCountOfLikes++;
console.log("initialCountOfLikes++ => " + initialCountOfLikes);
}
}
You can do something similar to what I'm doing below where you use a module to increment a private counter. The comments should be enough to explain what exactly is going on in the code:
//Load the existing number of likes from the server (im just using 5 as example)
const initialLikes = 5;
//Initialize a "like" counter
const likes = ((quantity) => {
//This is the count
let i = quantity;
//We return a module that allows us to increment the count or get the current count
return {
increment: () => i += 1,
quantity: () => i
}
})(initialLikes || 0);
//Store DOM elements we're accessing in variables
const captionEl = document.querySelector('#countEl');
const imgEl = document.querySelector('#puppyImg');
//Our double click handler:
const onDblClick = e => {
//Increment the count via our module, then update the count text
likes.increment();
captionEl.textContent = likes.quantity();
}
const init = () => {
//Set the initial count text on screen
captionEl.textContent = likes.quantity();
//Attach the event handler to the img
imgEl.addEventListener('dblclick', onDblClick);
};
init();
img:hover {
cursor: pointer;
}
<img id="puppyImg" src="https://s.abcnews.com/images/Lifestyle/puppy-ht-3-er-170907_4x3_992.jpg" height="160" width="190" alt="Cute puppy photo" />
<br /> Likes: <span id="countEl"></span>
I created, with some help, some javascript code to enable multiple operations to be accomplished when I press some buttons in my web app. It is working perfectly with the solution provided at the following link: One of Multiple Tasks Operated by Button Won't Execute provided by brk), but it is not working when I import the code into my CodePen text editor. There are three buttons, "online, offline, and all, which are upon being pressed, supposed to
switch the blue screen to black
hide the text that says, "PRESS BUTTONS BELOW"
hide the blinking --:-- symbol
However, when I press the "online", "offline", and "all" buttons, it almost seems as if nothing happens, because there is a short delay. Why does this delay happen? Also, the blinking --:-- symbol doesn't terminate blinking as it should...can you tell me why this is? Thanks so much in advance for the help!
See CodePen link here: https://codepen.io/IDCoder/pen/mXMqGV
Here is my javascript code:
var twitchTvStreamers;
var loaded = false;
$(document).ready(function(){
//GET TWITCH TV STREAMERS' STATUS AND API CALL
twitchTvStreamers=["FreeCodeCamp", "ESL_SC2", "OgamingSC2", "cretetion", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];
//OUT OF ALL THE TWITCH TV STREAMERS IN A TWITCH TV ARRAY FIND THOSE 8 STREAMERS LISTED
});
//filter online offline and all
var filterchannel = filterch => {
if(!loaded)
{
for(channel of twitchTvStreamers){
getChannelInfo(channel, filterch);
}
}
else
{
setTimeout(function(){
$('.display-output-here div').each(function(idx, item) {
if($(item).hasClass(filterch))
{
$(item).show();
}
else
{
$(item).hide();
}
});
}, 100);
}
if(!loaded)
{
for(channel of twitchTvStreamers){
getChannelInfo(channel, filterch);
}
}
{
setTimeout(function(){
$('.text1 div').each(function(idx, item) {
if($(item).hasClass(filterch))
{
$(item).hide();
}
});
}, 100);
}
};//end of var filterChannel
$('button').click(function(e) {
filterchannel(e.target.id);
})
var getChannelInfo = (channel, filterch) => {
loaded = true;
$.getJSON('https://wind-bow.glitch.me/twitch-api/streams/' + channel)
.done(function(info) {
console.log(channel);
if (info.stream === null) {
appendInfo(channel,'offline',filterch);
}
else {
appendInfo(channel,'online', filterch);
}
});
}
var appendInfo = (channel,target, filterch) => {
$.getJSON('https://wind-bow.glitch.me/twitch-api/channels/' + channel)
.done( function(ch){
channelID = ch.display_name;
channelLogo = ch.logo;
channelUrl = ch.url;
streamContent = ch.content;
$('.display-output-here').append('<div class="' + target + ' all">'+channel+' is '+target);
if(twitchTvStreamers[twitchTvStreamers.length - 1] === channel) {
filterchannel(filterch);
}
});
//BUTTONS OPERATIONS (ALL BUTTONS TARGETED BY USING CLASS THEY COME UNDER)
$(".user-status").on('click', function() {
$(".text1").hide();
$(".text2").hide(function() {
clearInterval(x);
});
$('.display-output-here').css("background", "black");
$('.TV-screen').css("background", "black");
});
var element = $(".text2");
var shown = true;
var x = setInterval(toggle, 500);
function toggle() {
if (shown) {
element.hide();
} else {
element.show();
}
shown = !shown;
}
}
//make part of video-screen text blink
var element = $(".text2");
var shown = true;
setInterval(toggle, 500);
function toggle() {
if(shown) {
element.hide();
shown = false;
} else {
element.show();
shown = true;
}
}
//share-links code:
$('.Linkedinbutton').click(function() {
var shareurl = $(this).data('shareurl');
window.open('https://www.linkedin.com/shareArticle?mini=true&url=https://codepen.io/IDCoder/full/mXMqGV/' + escape(shareurl) + '&title=' + document.title + '&source=SourceTitle&target=new');
return false;
});
//Facebook
var facebookShare = document.querySelector('[data-js="Facebookbutton"]');
facebookShare.onclick = function(e) {
e.preventDefault();
var facebookWindow = window.open('https://www.facebook.com/sharer/sharer.php?u=' + document.URL, 'facebook-popup', 'height=350,width=600');
if(facebookWindow.focus) { facebookWindow.focus(); }
return false;
}
/*
//user status button operations
*/
//search bar operation
$("#searchStreamers").on("keypress",function(e){
var typeStreamer = $('input').val();
if(e.which===13){
$('input').submit(function(e){
e.preventDefault();
});
}
});
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.
UPDATE - To help explain this I have created a fiddle which can be found here http://jsfiddle.net/Dano007/b11xarpp/5/
Overview.
I'd like to add a read more/collapse link to my comments, the visibility of comments will be restricted if over a certain size and the user will click "read more" to see them.
I found this example JS code here which seems perfect. http://jsfiddle.net/xn6Sp/9/
Problem.
I'm using a underscore.js .each wrapper to display my comments on the page, like so.
_.each(Badges, function (item) {
var wrapper = $('<div></div>');
wrapper.append('<div id="comments" class="item"></div>' + ' Reason: ' + item.comment + '</div>' + '<br>');
$('#container').append(wrapper);
});
However, using this seems to create the following issues.
1 - The read more link is not appended correctly
2 - It looks like the JS is reading the div contents as being empty and therefore not working.
Bounty is for:
1 - Making the read more/collpase link work correctly with the code shown in this jfiddle.
http://jsfiddle.net/Dano007/kgybcuqq/1/
I found the problem.
myBadgeQuery.find is async method, success function invokes only after the data is retrieved from server (parse.com in this case).
So ideally, the collapse logic is supposed to be executed after you append the data inside DOM.
I created function called collapseIt and wrapped all the collapse logic inside it and called it inside success of myBadgeQuery.find..
myBadgeQuery.find({
success: function (Badgeresults) {
var Badges = [];
for (var i = 0; i < Badgeresults.length; i++) {
Badges.push({
comment: Badgeresults[i].get('Comment'),
});
}
_.each(Badges, function (item) {
console.log("Got the data");
var wrapper = $('<div></div>');
wrapper.append('<div id="comments" class="item"></div>' + ' Reason: ' + item.comment + '</div>' + '<br>');
$('#container').append(wrapper);
});
//Invoke collapse code after you append the data. This is async function so you have to wait till data is appended.
collapseIt();
},
error: function (error) {
alert("Error: " + error.code + " " + error.message);
}
});
Collapse code :
//////////////////Hide/show comments on code//////////////
var collapseIt = function(){
var collapsedSize = '20px';
$('.item').each(function() {
console.log("inside each");
var h = this.scrollHeight;
console.log(h);
var div = $(this);
if (h > 30) {
div.css('height', collapsedSize);
div.after('<a id="more" class="item" href="#">Read more</a><br/>');
var link = div.next();
link.click(function(e) {
e.stopPropagation();
if (link.text() != 'Collapse') {
link.text('Collapse');
div.animate({
'height': h
});
} else {
div.animate({
'height': collapsedSize
});
link.text('Read more');
}
});
}
});
};
Updated Fiddle.. Should work for you. http://jsfiddle.net/rahulrulez/kgybcuqq/3/
Fiddle with individual collapsible links : http://jsfiddle.net/rahulrulez/kgybcuqq/4/
Try
$(function () {
var Badges = {
"comment" : ["stuff", "stuff", "stuff", "stuff"
, "stuff", "stuff the end"]
};
$.each(Badges.comment, function (key, value) {
$("#container").append('<br /><span id=comment-'+key+'>'
+ ' Reason: ' + value + '</span>');
});
var collapsedSize = '50px';
$('.item').each(function () {
var h = this.scrollHeight;
var div = $(".item");
if (h > 30) {
div.css('height', collapsedSize);
div.after('<a id="more" href="#"'
+ 'style="display:block;'
+ 'position:relative;margin-top:4px;">'
+ 'Read more'
+ '</a><br/>');
$("#container *:gt(3)").filter(function (i, el) {
return $(el).offset().top > $("#more").offset().top
}).hide();
var link = div.next();
link.click(function (e) {
e.stopPropagation();
link.text(function (i, o) {
return o === "Read more" ? "Collapse" : "Read more";
});
if (link.text() === 'Collapse') {
div.animate({
'height': h
});
$(".item *").show();
} else {
div.animate({
'height': collapsedSize,
});
$(".item *:gt(3)").hide();
}
});
}
});
})
jsfiddle http://jsfiddle.net/guest271314/kka3n0h3/