How to load a file from the client side? - javascript

The following example tries to load audio data from the client side. I am aware that the security technically is problematic. But when the path is defined, it should work. When I load from localhost, it only works partially and not at all by the client. How could I improve my code to make it work? Many Thanks.
document.getElementById('button1').onclick = function() {
clip0.click();
}
var listener = new THREE.AudioListener();
var audioLoader = new THREE.AudioLoader();
getAudioFile.onchange = function(){
var files = this.files;
var file = URL.createObjectURL(files[0]);
};
var clip0 = document.querySelector('#clip0');
clip0.addEventListener('click', function () {
//console.log( ("Loadeng:") + "./three/examples/sounds/" + getAudioFile.files[0].name);
console.log( ("Loadeng:") + "C:/Users/Public/Music/" + getAudioFile.files[0].name );
//loadClip( "./three/examples/sounds/" + getAudioFile.files[0].name );
loadClip( "C:/Users/Public/Music/" + getAudioFile.files[0].name );
//loadClip('https://cdn.rawgit.com/mrdoob/three.js/master/examples/sounds/358232_j_s_song.mp3');
});
var audioLoaded = false,
result
function loadClip( audioUrl ) {
audioLoaded = false
console.log(`\nLoading sound...`);
audioLoader.load( audioUrl, function( buffer ) {
sound = new THREE.PositionalAudio( listener );
sound.setBuffer( buffer );
sound.setRefDistance( 20 );
sound.setLoop(false);
sound.setVolume(5);
console.log(`\nAudio finished loading!`);
audioLoaded = true
});
play.onclick = function playClip() {
console.log( `\nplayClip()` );
play.style.background = "#92ddb8";
reset.disabled = false;
play.disabled = true;
paused.disabled = false;
sound.play();
}
reset.onclick = function resetClip() {
console.log( `\nresetClip()` );
play.style.background = "";
play.style.color = "";
stop.disabled = true;
play.disabled = false;
paused.disabled = false;
sound.stop()
console.clear()
}
paused.onclick = function pausedClip() {
console.log( `\npausedClip()` );
play.style.background = "";
play.style.color = "";
stop.disabled = false;
play.disabled = false;
paused.disabled = true;
sound.pause();
}
}
#button1 {
position:absolute;
margin-top: 0px;
margin-left: 50px;
}
#getAudioFile {
position:absolute;
margin-top:0px;
margin-left:133px;
}
<script src="//cdn.rawgit.com/mrdoob/three.js/master/build/three.min.js"></script>
<p id="clip0"></p>
<button id="play" class="play">Play</button>
<button id="paused" class="paused">Pause</button>
<button id="reset" class="reset">Reset</button>
<input type="file" id="getAudioFile">
<button type="button" id="button1" onclick="getAudioFile">Load Clip:</button>

Related

CKEdidor return multiple selected files

I am using CKFinder 3 in a Web project as described on the CKFinder Website my problem is that I can't return multiple selected Images. The problem is that when I select multiple Images just the first one is returned.
Is there a way to return multiple files?
var button1 = document.getElementById( 'ckfinder-popup-1' );
var button2 = document.getElementById( 'ckfinder-popup-2' );
button1.onclick = function() {
selectFileWithCKFinder( 'ckfinder-input-1' );
};
button2.onclick = function() {
selectFileWithCKFinder( 'ckfinder-input-2' );
};
function selectFileWithCKFinder( elementId ) {
CKFinder.modal( {
chooseFiles: true,
width: 800,
height: 600,
onInit: function( finder ) {
finder.on( 'files:choose', function( evt ) {
var file = evt.data.files.first();
var output = document.getElementById( elementId );
output.value = file.getUrl();
} );
finder.on( 'file:choose:resizedImage', function( evt ) {
var output = document.getElementById( elementId );
output.value = evt.data.resizedUrl;
} );
}
} );
I have found a way how to do it.
The only bummer is that you can’t resize images.
var button1 = document.getElementById( 'ckfinder-popup-1' );
button1.onclick = function() {
selectFileWithCKFinder( 'ckfinder-input-1' );
};
function selectFileWithCKFinder( elementId ) {
CKFinder.modal( {
chooseFiles: true,
width: 800,
height: 600,
onInit: function( finder ) {
finder.on( 'files:choose', function( evt ) {
var url='';
for(i = 0; i < evt.data.files.models.length ; i++){
var file = evt.data.files.models[i];
var tempurl = file.getUrl();
url +=','+tempurl;
}
var output = document.getElementById( elementId );
output.value = url;
} );
finder.on( 'file:choose:resizedImage', function( evt ) {
var url='';
for(i = 0; i < evt.data.files.models.length ; i++){
var file = evt.data.files.models[i];
var tempurl = file.getUrl();
url +=','+tempurl;
}
var output = document.getElementById( elementId );
output.value = url;
} );
}
} );
}
</script> ```

webrtc remote video not playing in phonegap ios app?

I have found quite a few similar qustions but they are mainly old and outdated and some of them provided a few pointers which I followed to no avail.
Basically, I'm tring to use webrtc and the phonegap iosrtc plugin to create a simple 2 way video chat.
I followed everything to the letter and I managed to show my own video in the app but the 'remote' video is not showing and I ant figure out what the issue is at all!
I have enabled the debugging in phonegap but I don't get any errors.
This is my complete code:
HTML:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://rtcmulticonnection.herokuapp.com/dist/RTCMultiConnection.min.js"></script>
<script src="https://rtcmulticonnection.herokuapp.com/node_modules/webrtc-adapter/out/adapter.js"></script>
<script src="https://rtcmulticonnection.herokuapp.com/socket.io/socket.io.js"></script>
<!-- custom layout for HTML5 audio/video elements -->
<link rel="stylesheet" href="https://rtcmulticonnection.herokuapp.com/dev/getHTMLMediaElement.css">
<script src="https://rtcmulticonnection.herokuapp.com/dev/getHTMLMediaElement.js"></script>
<script src="https://rtcmulticonnection.herokuapp.com/node_modules/recordrtc/RecordRTC.js"></script>
<script src="cordova.js"></script>
<script src="ios-websocket-hack.js"></script>
<section class="make-center">
<div>
<label><input type="checkbox" id="record-entire-conference"> Record Entire Conference In The Browser?</label>
<span id="recording-status" style="display: none;"></span>
<button id="btn-stop-recording" style="display: none;">Stop Recording</button>
<br><br>
<input type="text" id="room-id" value="abcdef" autocorrect=off autocapitalize=off size=20>
<button id="open-room">Open Room</button>
<button id="join-room">Join Room</button>
<button id="open-or-join-room">Auto Open Or Join Room</button>
</div>
<div id="videos-container" style="margin: 20px 0;"></div>
<div id="room-urls" style="text-align: center;display: none;background: #F1EDED;margin: 15px -10px;border: 1px solid rgb(189, 189, 189);border-left: 0;border-right: 0;"></div>
</section>
JAVASCRIPT:
// ......................................................
// .......................UI Code........................
// ......................................................
document.getElementById('open-room').onclick = function() {
disableInputButtons();
connection.open(document.getElementById('room-id').value, function(isRoomOpened, roomid, error) {
if(isRoomOpened === true) {
showRoomURL(connection.sessionid);
}
else {
disableInputButtons(true);
if(error === 'Room not available') {
alert('Someone already created this room. Please either join or create a separate room.');
return;
}
alert(error);
}
});
};
document.getElementById('join-room').onclick = function() {
disableInputButtons();
connection.join(document.getElementById('room-id').value, function(isJoinedRoom, roomid, error) {
if (error) {
disableInputButtons(true);
if(error === 'Room not available') {
alert('This room does not exist. Please either create it or wait for moderator to enter in the room.');
return;
}
alert(error);
}
});
};
document.getElementById('open-or-join-room').onclick = function() {
disableInputButtons();
connection.openOrJoin(document.getElementById('room-id').value, function(isRoomExist, roomid, error) {
if(error) {
disableInputButtons(true);
alert(error);
}
else if (connection.isInitiator === true) {
// if room doesn't exist, it means that current user will create the room
showRoomURL(roomid);
}
});
};
// ......................................................
// ..................RTCMultiConnection Code.............
// ......................................................
var connection = new RTCMultiConnection();
// by default, socket.io server is assumed to be deployed on your own URL
//connection.socketURL = '/';
// comment-out below line if you do not have your own socket.io server
connection.socketURL = 'https://rtcmulticonnection.herokuapp.com:443/';
connection.socketMessageEvent = 'video-conference-demo';
connection.session = {
audio: true,
video: true
};
connection.sdpConstraints.mandatory = {
OfferToReceiveAudio: true,
OfferToReceiveVideo: true
};
connection.videosContainer = document.getElementById('videos-container');
connection.onstream = function(event) {
var existing = document.getElementById(event.streamid);
if(existing && existing.parentNode) {
existing.parentNode.removeChild(existing);
}
/*event.mediaElement.removeAttribute('src');
event.mediaElement.removeAttribute('srcObject');
event.mediaElement.muted = true;
event.mediaElement.volume = 0;*/
var video = document.createElement('video');
try {
video.setAttributeNode(document.createAttribute('autoplay'));
video.setAttributeNode(document.createAttribute('playsinline'));
} catch (e) {
video.setAttribute('autoplay', true);
video.setAttribute('playsinline', true);
}
if(event.type === 'local') {
video.setAttribute('class', 'myvideo');
//$('.yourVideo').attr('src', event.stream);
//$('.yourVideo').attr('id', event.streamid);
alert('local');
video.volume = 0;
try {
video.setAttributeNode(document.createAttribute('muted'));
} catch (e) {
video.setAttribute('muted', true);
}
}
if (event.type === 'remote') {
alert('remote');
video.setAttribute('class', 'othersvideo');
}
video.src = URL.createObjectURL(event.stream);
//var width = parseInt(connection.videosContainer.clientWidth / 3) - 20;
var width = $(document).width();
var height = $(document).height();
var mediaElement = getHTMLMediaElement(video, {
/*title: event.userid,*/
buttons: ['full-screen'],
width: 100,
height: 100,
showOnMouseEnter: false
});
connection.videosContainer.appendChild(mediaElement);
setTimeout(function() {
// mediaElement.media.play();
video.play();
}, 5000);
mediaElement.id = event.streamid;
// to keep room-id in cache
localStorage.setItem(connection.socketMessageEvent, connection.sessionid);
chkRecordConference.parentNode.style.display = 'none';
if(chkRecordConference.checked === true) {
btnStopRecording.style.display = 'inline-block';
recordingStatus.style.display = 'inline-block';
var recorder = connection.recorder;
if(!recorder) {
recorder = RecordRTC([event.stream], {
type: 'video'
});
recorder.startRecording();
connection.recorder = recorder;
}
else {
recorder.getInternalRecorder().addStreams([event.stream]);
}
if(!connection.recorder.streams) {
connection.recorder.streams = [];
}
connection.recorder.streams.push(event.stream);
recordingStatus.innerHTML = 'Recording ' + connection.recorder.streams.length + ' streams';
}
if(event.type === 'local') {
connection.socket.on('disconnect', function() {
if(!connection.getAllParticipants().length) {
location.reload();
}
});
}
};
var recordingStatus = document.getElementById('recording-status');
var chkRecordConference = document.getElementById('record-entire-conference');
var btnStopRecording = document.getElementById('btn-stop-recording');
btnStopRecording.onclick = function() {
var recorder = connection.recorder;
if(!recorder) return alert('No recorder found.');
recorder.stopRecording(function() {
var blob = recorder.getBlob();
invokeSaveAsDialog(blob);
connection.recorder = null;
btnStopRecording.style.display = 'none';
recordingStatus.style.display = 'none';
chkRecordConference.parentNode.style.display = 'inline-block';
});
};
connection.onstreamended = function(event) {
var mediaElement = document.getElementById(event.streamid);
if (mediaElement) {
mediaElement.parentNode.removeChild(mediaElement);
}
};
connection.onMediaError = function(e) {
if (e.message === 'Concurrent mic process limit.') {
if (DetectRTC.audioInputDevices.length <= 1) {
alert('Please select external microphone. Check github issue number 483.');
return;
}
var secondaryMic = DetectRTC.audioInputDevices[1].deviceId;
connection.mediaConstraints.audio = {
deviceId: secondaryMic
};
connection.join(connection.sessionid);
}
};
// ..................................
// ALL below scripts are redundant!!!
// ..................................
function disableInputButtons(enable) {
document.getElementById('room-id').onkeyup();
document.getElementById('open-or-join-room').disabled = !enable;
document.getElementById('open-room').disabled = !enable;
document.getElementById('join-room').disabled = !enable;
document.getElementById('room-id').disabled = !enable;
}
// ......................................................
// ......................Handling Room-ID................
// ......................................................
function showRoomURL(roomid) {
var roomHashURL = '#' + roomid;
var roomQueryStringURL = '?roomid=' + roomid;
var html = '<h2>Unique URL for your room:</h2><br>';
html += 'Hash URL: ' + roomHashURL + '';
html += '<br>';
html += 'QueryString URL: ' + roomQueryStringURL + '';
var roomURLsDiv = document.getElementById('room-urls');
roomURLsDiv.innerHTML = html;
roomURLsDiv.style.display = 'block';
}
(function() {
var params = {},
r = /([^&=]+)=?([^&]*)/g;
function d(s) {
return decodeURIComponent(s.replace(/\+/g, ' '));
}
var match, search = window.location.search;
while (match = r.exec(search.substring(1)))
params[d(match[1])] = d(match[2]);
window.params = params;
})();
var roomid = '';
if (localStorage.getItem(connection.socketMessageEvent)) {
roomid = localStorage.getItem(connection.socketMessageEvent);
} else {
roomid = connection.token();
}
var txtRoomId = document.getElementById('room-id');
txtRoomId.value = roomid;
txtRoomId.onkeyup = txtRoomId.oninput = txtRoomId.onpaste = function() {
localStorage.setItem(connection.socketMessageEvent, document.getElementById('room-id').value);
};
var hashString = location.hash.replace('#', '');
if (hashString.length && hashString.indexOf('comment-') == 0) {
hashString = '';
}
var roomid = params.roomid;
if (!roomid && hashString.length) {
roomid = hashString;
}
if (roomid && roomid.length) {
document.getElementById('room-id').value = roomid;
localStorage.setItem(connection.socketMessageEvent, roomid);
// auto-join-room
(function reCheckRoomPresence() {
connection.checkPresence(roomid, function(isRoomExist) {
if (isRoomExist) {
connection.join(roomid);
return;
}
setTimeout(reCheckRoomPresence, 5000);
});
})();
disableInputButtons();
}
// detect 2G
if(navigator.connection &&
navigator.connection.type === 'cellular' &&
navigator.connection.downlinkMax <= 0.115) {
alert('2G is not supported. Please use a better internet service.');
}
window.cordova.InAppBrowser.open(" https://vps267717.ovh.net/webrtc", "_blank", "location=no,toolbar=yes");
As you can see in my code, I have this:
if (event.type === 'remote') {
alert('remote');
video.setAttribute('class', 'othersvideo');
}
But this never fires for some reason!
I have spent the last 3 days trying to figure this out but I haven't had any luck.
So any help and advice would be appreciated.
Thanks in advance.

how to save this screenshot in local drive without any pop up?

I want to save this screenshot in local drive without showing a popup to download.
(function() {
'use strict';
$("body").prepend ( `
<button id="btCapture">SCREENSHOT</button>
<input type="submit" value="Take Screenshot Of Div" onclick="capture();" />
<form method="POST" enctype="multipart/form-data" action="save.php" id="myForm">
<input type="hidden" name="img_val" id="img_val" value="" />
</form>
<div></div>`);
document.getElementById("btCapture").onclick = function() { generate();};
(function (exports) {
function urlsToAbsolute(nodeList) {
if (!nodeList.length) {
return [];
}
var attrName = 'href';
if (nodeList[0].prototype === HTMLImageElement.prototype || nodeList[0].protottype === HTMLScriptElement.prototype) {
attrName = 'src';
}
nodeList = [].map.call(nodeList, function (el, i) {
var attr = el.getAttribute(attrName);
if (!attr) {
return;
}
var absURL = /^(https?|data):/i.test(attr);
if (absURL) {
return el;
} else {
return el;
}
});
return nodeList;
}
function screenshotPage() {
urlsToAbsolute(document.images);
urlsToAbsolute(document.querySelectorAll("link[rel='stylesheet']"));
var screenshot = document.documentElement.cloneNode(true);
var b = document.createElement('base');
b.href = document.location.protocol + '//' + location.host;
var head = screenshot.querySelector('head');
head.insertBefore(b, head.firstChild);
screenshot.style.pointerEvents = 'none';
screenshot.style.overflow = 'hidden';
screenshot.style.webkitUserSelect = 'none';
screenshot.style.mozUserSelect = 'none';
screenshot.style.msUserSelect = 'none';
screenshot.style.oUserSelect = 'none';
screenshot.style.userSelect = 'none';
screenshot.dataset.scrollX = window.scrollX;
screenshot.dataset.scrollY = window.scrollY;
var script = document.createElement('script');
script.textContent = '(' + addOnPageLoad_.toString() + ')();';
screenshot.querySelector('body').appendChild(script);
var blob = new Blob([screenshot.outerHTML], {
type: 'text/html'
});
return blob;
}
function addOnPageLoad_() {
window.addEventListener('DOMContentLoaded', function (e) {
var scrollX = document.documentElement.dataset.scrollX || 0;
var scrollY = document.documentElement.dataset.scrollY || 0;
window.scrollTo(scrollX, scrollY);
});
}
function generate() {
window.URL = window.URL || window.webkitURL;
window.open(window.URL.createObjectURL(screenshotPage()));
}
exports.screenshotPage = screenshotPage;
exports.generate = generate;
})(window);
})
;
You can't. Allowing web pages to write files to arbitrary paths on the end-user's machine would be a massive hole for malware to exploit. The user must be involved.

How to disable/enable multiple upload buttons with multiple checkboxes

I am a beginner and am having trouble making my code work. I want to enable/disable a file upload button by clicking a check box. the code works fine when I have only 1 upload button and one check box but it does not when I have more then one. Can anyone please help?
this is JSFiddle preview .
html code
<label>
<input type="checkbox" id="confirm">
</label>
<input type="file" class="style5" id="abstract" name="abstract" disabled onchange="ValidateSingleInput(this);"/>
<br>
<label>
<input type="checkbox" id="confirmp">
</label>
<input type="file" class="style5" id="poster" name="poster" disabled onchange="ValidateSingleInput(this);"/>
<span class="style5"><br>
<label>
<input type="checkbox" id="confirmr">
</label>
<input type="file" class="style5" id="resume" name="resume" disabled onchange="ValidateSingleInput(this);" />
<span class="style5">
javascript code
window.onload = function() {
var checker = document.getElementById('confirm');
var sbm = document.getElementById('abstract');
checker.onchange = function () {
if(this.checked) {
sbm.disabled = false;
}
else {
sbm.disabled = true;
}
};
};
window.onload = function() {
var checker = document.getElementById('confirmp');
var sbm = document.getElementById('poster');
checker.onchange = function () {
if(this.checked) {
sbm.disabled = false;
}
else {
sbm.disabled = true;
}
};
};
window.onload = function() {
var checker = document.getElementById('confirmr');
var sbm = document.getElementById('resume');
checker.onchange = function () {
if(this.checked) {
sbm.disabled = false;
}
else {
sbm.disabled = true;
}
};
};
You have many window.onload so only the last one is active by the end of the script. One window.onload is enough and then you can run all your functions together. Try this updated demo.
window.onload = function() {
var checker = document.getElementById('confirm');
var sbm_abstract = document.getElementById('abstract');
var checkerp = document.getElementById('confirmp');
var sbm_poster = document.getElementById('poster');
var checkerr = document.getElementById('confirmr');
var sbm_resume = document.getElementById('resume');
checker.onchange = function () {
if(this.checked) {
sbm_abstract.disabled = false;
}
else {
sbm_abstract.disabled = true;
}
} ;
checkerp.onchange = function () {
if(this.checked) {
sbm_poster.disabled = false;
}
else {
sbm_poster.disabled = true;
}
};
checkerr.onchange = function () {
if(this.checked) {
sbm_resume.disabled = false;
}
else {
sbm_resume.disabled = true;
}
};
};
I renamed the variables to not override each other and i initialize all your functions in one window.onload event.
Whenever you write a new window.onload = function() { ... }; you are overwriting the previous function that was going to be executed when the window loads, and that's why only the last check box works.
So, to solve the problem, make sure you put your code inside the same onload.
This should work:
window.onload = function() {
var checker = document.getElementById('confirm');
var sbm = document.getElementById('abstract');
checker.onchange = function () {
if(this.checked) {
sbm.disabled = false;
}
else {
sbm.disabled = true;
}
};
var checkerp = document.getElementById('confirmp');
var sbmp = document.getElementById('poster');
checkerp.onchange = function () {
if(this.checked) {
sbmp.disabled = false;
}
else {
sbmp.disabled = true;
}
};
var checkerr = document.getElementById('confirmr');
var sbmr = document.getElementById('resume');
checkerr.onchange = function () {
if(this.checked) {
sbmr.disabled = false;
}
else {
sbmr.disabled = true;
}
};
};
You only need one window.onload.
Try this:
window.onload = function () {
var checker = document.getElementById('confirm'),
sbm = document.getElementById('abstract'),
checker2 = document.getElementById('confirmp'),
sbm2 = document.getElementById('poster'),
checker3 = document.getElementById('confirmr'),
sbm3 = document.getElementById('resume');
checker.onchange = function () {
enableDisable(checker, sbm);
};
checker2.onchange = function () {
enableDisable(checker2, sbm2);
};
checker3.onchange = function () {
enableDisable(checker3, sbm3);
};
function enableDisable(target, btn) {
btn.disabled = target.checked ? false : true;
};
};
Updated fiddle

Delete specific item from local storage

I have a note taking application that im working on . Its made to look like Google Keep
It saves each note in local storage .
I would like to add a delete option to each of the notes (similar to Keep) , but don't know know to do it.
The full code is on my Github page https://github.com/oxhey/keep
HTML :
<!doctype html>
<html>
<head>
<title>Notes</title>
<link href="styles/normalize.css" rel="stylesheet" />
<link href="styles/main.css" rel="stylesheet" />
<link rel="stylesheet" type="text/css" href="window.css">
</head>
<script>
var nw = require('nw.gui');
var win = nw.Window.get();
win.isMaximized = false;
</script>
<body id="gui">
<header class="app-header">
<ul style="margin-top:0.3px">
<li><a href='#' title='Close' id='windowControlClose'></a></li>
<li><a href='#' title='Maximize' id='windowControlMaximize'></a></li>
<li><a href='#' title='Minimize' id='windowControlMinimize'></a></li>
</ul>
<h2 style="margin-top: 10px;margin-left: 20px;color: #fff;">Notes</h2>
</header>
<section class="main-section">
<article class="note add-note">
<h1 class="note-title"></h1>
<p class="note-content">Add a note</p>
</article>
</section>
<script src="js/jquery.js"></script>
<script src="js/main.js"></script>
<script>
// Min
document.getElementById('windowControlMinimize').onclick = function()
{
win.minimize();
};
// Close
document.getElementById('windowControlClose').onclick = function()
{
win.close();
gui.App.closeAllWindows();
};
// Max
document.getElementById('windowControlMaximize').onclick = function()
{
if (win.isMaximized)
win.unmaximize();
else
win.maximize();
};
win.on('maximize', function(){
win.isMaximized = true;
});
win.on('unmaximize', function(){
win.isMaximized = false;
});
</script>
</body>
</html>
Javascript : Main.js
var Strings = {
'en-us': {
DEFAULT_TITLE: "Title",
ADD_NOTE: "Add a note",
SEARCH_PLACEHOLDER: "Search Jin's Keep"
}
};
var Lang = Strings['en-us'];
var Keys = {
ENTER: 10
}
var notes;
function Note(title, content, id) {
Note.numInstances = (Note.numInstances || 0) + 1;
this.id = id ? id : Note.numInstances
this.title = title;
this.content = content;
}
Note.prototype.render = function(index) {
var elem = $('<article class="note" data-index="' + index + '"><h1 class="note-title">' + this.title + '</h1><p class="note-content">' + this.content + '</p></article>');
$(".add-note").after(elem);
}
Note.prototype.toJSON = function() {
return {
id: this.id,
title: this.title,
content: this.content
};
}
function createNote() {
var elem = $(".add-note");
var title = elem.find(".note-title");
var content = elem.find(".note-content");
elem.removeClass("active");
title.hide();
if(title.text() != Lang.DEFAULT_TITLE || content.text() != Lang.ADD_NOTE) {
var id = notes ? notes.length+1 : 1;
var note = new Note(title.text(), content.text(), id);
notes.push(note);
note.render(notes.length-1);
title.text(Lang.DEFAULT_TITLE);
content.text(Lang.ADD_NOTE);
saveNotes();
}
}
function activateNote(note) {
var title = note.find(".note-title");
note.addClass("active");
title.show();
if(isEmpty(title.text())) {
title.text(Lang.DEFAULT_TITLE);
}
}
function saveCurrentNote() {
var noteElement = $(".note.active");
if(noteElement) {
console.log("will save this element: ", noteElement[0]);
var noteIndex = noteElement.attr("data-index");
var note = notes[noteIndex];
note.title = noteElement.find(".note-title").text();
note.content = noteElement.find(".note-content").text();
saveNotes();
deactivateCurrentNote(noteElement);
}
}
function deactivateCurrentNote(note) {
note.removeClass("active");
var title = note.find(".note-title");
if(isEmpty(title.text()) || title.text() == Lang.DEFAULT_TITLE) {
title.hide();
}
$(":focus").blur();
}
function isEmpty(string) {
return string.replace(/\s| /g, '').length == 0;
}
function addTabIndex() {
tabIndex = 3;
$(".note .note-content, .note .note-title").each(function() {
var el = $(this);
el.attr("tabindex", tabIndex++);
});
}
function loadNotes() {
var rawObjects = JSON.parse(localStorage.getItem("notes"));
if(rawObjects && rawObjects.length) {
rawObjects.forEach(function(obj, index) {
obj.__proto__ = Note.prototype;
obj.render(index);
});
return rawObjects;
} else {
console.warn("Couldn't load any note because local storage is empty.");
return [];
}
}
function saveNotes() {
localStorage.setItem("notes", JSON.stringify(notes))
}
$(document).ready(function() {
notes = loadNotes();
addTabIndex();
$(".note").each(function() {
var note = $(this);
var title = note.find(".note-title");
if(isEmpty(title.text()) || title.text() == Lang.DEFAULT_TITLE ) {
title.hide();
}
});
$(".main-section").on("click", ".note .note-content, .note .note-title", function(evt) {
var note = $(this).parent();
activateNote(note);
//console.log('2 - Setting content editable to true', evt);
var noteSection = $(this);
noteSection.prop("contentEditable", true);
});
$(".main-section").on("click", ".note .note-title", function(evt) {
//console.log("3 - Clearing TITLE's text");
var title = $(this);
if(title.text() == Lang.DEFAULT_TITLE) {
title.text("");
}
});
$(".main-section").on("click", ".note .note-content", function(evt) {
//console.log('4 - Clearing CONTENT text', evt);
var content = $(this);
if(content.text() == Lang.ADD_NOTE) {
content.text("");
content.focus();
}
});
$(".main-section").on("click", function(evt) {
if(evt.target == this) {
//console.log('5', evt);
var currentNote = $(".note.active");
if(currentNote.length) {
//console.log('5.a');
if(currentNote.hasClass("add-note")) {
console.log('5 - Creating a new note');
createNote();
} else {
console.log('5 - Saving current note');
saveCurrentNote();
}
if(currentNote.find(".note-title").text() == Lang.DEFAULT_TITLE) {
currentNote.find(".note-title").hide();
}
}
}
});
$(".main-section").on("keypress", ".note .note-content, .note .note-title", function(evt) {
var currentNote = $(".note.active");
console.log('6');
if(evt.which == Keys.ENTER && evt.ctrlKey) {
console.log('2');
if(currentNote.hasClass("add-note")) {
createNote();
} else {
saveCurrentNote();
}
}
});
});
Thanks
Something like this? Use a data attribute on a delete button and pass that as a parameter to a removeNote function.
HTML
<button class="delete" data-id="1">Delete note</button>
JS
$(document).on('click', '.delete', function () {
var id = $(this).data('id');
removeNote(id);
});
function removeNote(id) {
localStorage.removeItem(id);
}

Categories