No error messages, the file gets selected, however the input.onchange = () => {} never gets called.
I added: to the top of HTML to no result. Any idea why this doesn't work in Edge?
toolbar.addHandler('image', () => {
const range = this.quillReply.getSelection();
this.selectLocalImage()
})
toolbar.addHandler('link', (value) => {
if (value) {
var href = prompt('Enter the URL');
this.quillReply.format('link', href);
} else {
this.quillReply.format('link', false);
}
});
}
selectLocalImage = () => {
const input = document.createElement('input');
input.setAttribute('type', 'file');
input.click();
// Listen upload local image and save to server
input.onchange = () => {
}
}
The C should be capitalized in onChange.
I also met this question,this code snippets seems to be used in quill editor as a image uploader plugin.
I solved it after change the "selectLocalImage" function to below:
/**
* Select local image
*/
selectLocalImage = () => {
const input = document.createElement('input');
input.setAttribute('type', 'file');
input.addEventListener('change', () => {
// do something like upload local image and save to server
});
input.click();
}
tested in edge 44 and chrome 71.
Related
I am using hadlerbars as the view engine for express and i want the text in the variable code to be copied to the clipboard i tried many solutions . This is my current code
function copyLink() {
var copytext = document.getElementById('alcslink').innerHTML
let code = copytext.split(":- ").pop() /*formatted */
code.select();
code.setSelectionRange(0, 99999); /* For mobile devices */
/* Copy the text inside the text field */
navigator.clipboard.writeText(code.value);
}
when i run this it gives me this error in the web console
TypeError: code.select is not a function
This is how I use it:
Note, it does not work in the snippet engine. You will need to add it to your code.
Sorry.
const writeToClipboard = async (txt) => {
const result = await navigator.permissions.query({ name: "clipboard-write" });
if (result.state == "granted" || result.state == "prompt") {
await navigator.clipboard.writeText(txt);
console.log('Copied to clipboard');
}
};
document.querySelector('button').addEventListener('click', async () => {
const el = document.querySelector('div');
await writeToClipboard(el.innerHTML);
});
<div>copy me</div>
<button>Click</button>
I am making a small website and I need to save the state of the page after refreshing. I have the following javascript code where I have used local storage to store the inputs with setItem. They get stored just fine, however I'm not sure how to retrieve them.
window.addEventListener('load', () => {
todos = JSON.parse(localStorage.getItem('todos')) || [];
const form = document.querySelector("#listForm");
const input= document.querySelector("#newElement");
const listTask= document.querySelector("#tasks");
form.addEventListener('submit', (e) =>{
e.preventDefault();
const task=input.value;
const taskElement = document.createElement('div');
taskElement.classList.add('task');
if(!task){
alert("You need to write something!");
return;
}
todos.push(task);
localStorage.setItem('todos', JSON.stringify(todos));
const taskContentEl= document.createElement('div');
taskContentEl.classList.add('content');
taskElement.appendChild(taskContentEl);
const taskInputEl=document.createElement('input');
taskInputEl.classList.add('text');
taskInputEl.type='text';
taskInputEl.value= task;
taskInputEl.setAttribute('readonly','readonly');
taskContentEl.appendChild(taskInputEl);
listTask.appendChild(taskElement);
const taskActionsEl= document.createElement('div');
taskActionsEl.classList.add('actions');
const editEl= document.createElement('button');
editEl.classList.add('edit');
editEl.innerText='Edit';
const doneEl= document.createElement('button');
doneEl.classList.add('done');
doneEl.innerText='Done?';
taskActionsEl.appendChild(doneEl);
const deleteEl= document.createElement('button');
deleteEl.classList.add('delete');
deleteEl.innerText='X';
taskActionsEl.appendChild(editEl);
taskActionsEl.appendChild(deleteEl);
taskElement.appendChild(taskActionsEl);
input.value='';
editEl.addEventListener('click', (e) => {
if(editEl.innerText.toLowerCase() == "edit"){
editEl.innerText="Save";
taskInputEl.removeAttribute("readonly");
taskInputEl.focus();
}
else {
editEl.innerText="Edit";
taskInputEl.setAttribute("readonly","readonly");
}
});
doneEl.addEventListener('click', (e) => {
if(doneEl.innerText.toLowerCase()=='done?'){
doneEl.innerText='✔';
taskContentEl.classList.add('checked');
}
else{
doneEl.innerText="Done?"
taskContentEl.classList.remove('checked');
}
});
deleteEl.addEventListener('click', (e) => {
listTask.removeChild(taskElement);
todos.pop(task);
localStorage.setItem('todos', JSON.stringify(todos));
})
localStorage.getItem('todos');
});
});
I tried using JSON.parse like this, but I'm not sure why it's not working, or where to put it.
JSON.parse(localStorage.getItem('todos'));
When I run my rails application and enter likeButton into the console it gives me Uncaught ReferenceError: likeButton is not defined
at :1:1
(anonymous) # VM1591:1
I tried moving the script in html to head and body. I am currently trying to use DOMContentLoaded but it seems I'm missing something. My overall goal is to change the color of the button once pressed and also keep the color after page refresh. I am using sessionStorage for this process. I just want to make sure that likeButton variable is declared after html is loaded. If its possible to done in javascript only.
//first js file
const BASE_URL = "http://localhost:3000"
const GPUS_URL = `${BASE_URL}/gpus`
const USERS_URL = `${BASE_URL}/users`
const gpuCollection = document.querySelector('#gpu-collection')
let wish = sessionStorage.getItem('wish');
class Gpu {
constructor(gpuAttributes) {
this.title = gpuAttributes.title;
this.price = gpuAttributes.price;
this.features = gpuAttributes.features;
this.link = gpuAttributes.link;
this.image = gpuAttributes.image;
this.id = gpuAttributes.id;
}
render() {
let div = document.createElement('div');
div.classList.add('card');
let h = document.createElement('h2');
let t = document.createTextNode(`${this.title} ($${this.price})`);
h.appendChild(t);
div.appendChild(h);
let h1 = document.createElement('h1');
h1.classList.add('gpu-cat');
h1.innerHTML = `${this.features}`;
div.appendChild(h1);
let button = document.createElement('button');
button.classList.add('list_btn');
button.innerHTML = '♡';
div.appendChild(button);
let a = document.createElement('a');
let img = document.createElement('img');
a.href = `${this.link}`;
a.target = '_blank';
img.src = `${this.image}`;
img.classList.add('gpu-image');
a.appendChild(img);
div.appendChild(a);
gpuCollection.appendChild(div);
}
}
//second js file
document.addEventListener("DOMContentLoaded", function (){
let likeButton;
SignUp();
logInUser();
logOutUser();
function putGpusOnDom(gpuArray){
gpuArray.forEach(gpu => {
let newGpu = new Gpu(gpu)
newGpu.render()
});
likeButton = document.querySelector("button");
}
function fetchGpus(){
fetch(GPUS_URL)
.then(res => res.json())
.then(gpus => putGpusOnDom(gpus))
}
const enableWish = () => {
console.log(likeButton)
sessionStorage.setItem('wish', 'red')
}
gpuCollection.addEventListener('click', function (){
wish = sessionStorage.getItem('wish');
if(wish !== 'red'){
enableWish();
}else{
disableWish();
}
});
})
//html file
...
<body>
<div id = "gpu-collection"></div>
<script type="text/javascript" src="src/Gpu.js"></script>
<script type="text/javascript" src="src/index.js" ></script>
</body>
</html>
As I mentioned in a comment the like button is not available on DOMContentLoaded if it is added dynamically. You need to wait until the button has been placed in the DOM
Use something like the following, I'm making some guesses here as there are some gaps in your code
document.addEventListener("DOMContentLoaded", function (){
//document.querySelector("button"); not yet available
//NOTE: The likeButton variable will ONLY be in scope INSIDE the event listener function
// You will not be able to access directly in the console.
let likeButton;
SignUp();
logInUser();
logOutUser();
function putGpusOnDom(gpuArray){
gpuArray.forEach(gpu => {
let newGpu = new Gpu(gpu)
newGpu.render()
});
//Now you have rendered the button it is available
//CAUTION: querySelector("button") will grab the first button on the page
// and ONLY the first button
likeButton = document.querySelector("button");
//Log like button to console while it is still in scope.
console.log(likeButton);
}
function fetchGpus(){
fetch(GPUS_URL)
.then(res => res.json())
.then(gpus => putGpusOnDom(gpus))
}
const enableWish = () => {
console.log(likeButton)
sessionStorage.setItem('wish', 'red')
}
})
I'm currently trying create a drag and drop file uploader with the standard option to just use the regular input. I'm not sure what to be targeting to write if the user clicked the upload or dropped a file in.
My first thought was to check if the FileList is empty but both ways produce a FileList. Second thought was just write two functions one for the input and one for the drop but that seems like I would be repeating. Last thought was writing an if statement in the read_file function. However, I'm not sure what to target exactly.
Any ideas would be greatly appreciated!! thanks!!
https://jsfiddle.net/nick1572/b4xzt8oh/3/
var uploader = document.querySelector('.uploader');
var output = document.getElementById('output');
var file = document.getElementById('file');
file.addEventListener('change', function(event) {
read_file(event);
});
function read_file(event) {
file = event.target;
var reader = new FileReader();
reader.onload = function() {
var data_url = reader.result;
output.src = data_url;
};
// This will read when the image is dropped.
//reader.readAsDataURL(event.dataTransfer.files[0]);
reader.readAsDataURL(file.files[0]);
/*
Something like this
if () {
reader.readAsDataURL(file.files[0]);
} else if() {
reader.readAsDataURL(event.dataTransfer.files[0]);
}
*/
};
uploader.addEventListener('dragover', function(e) {
console.log('drag over');
e.preventDefault();
});
uploader.addEventListener('dragenter', function(e) {
console.log('drag enter');
e.preventDefault();
});
uploader.addEventListener('dragleave', function() {
console.log('drag leave');
});
uploader.addEventListener('drop', function(event) {
console.log('drop');
event.preventDefault();
read_file(event);
});
Check the type property of the event object to see which event has been used.
function read_file(event) {
file = event.target;
var reader = new FileReader();
reader.onload = function() {
var data_url = reader.result;
output.src = data_url;
};
if (event.type === 'change') {
reader.readAsDataURL(file.files[0]);
} else if(event.type === 'drop') {
reader.readAsDataURL(event.dataTransfer.files[0]);
}
};
using local storage and onclick with javascript
I have a html file with 2 job descriptions :
html file 1
<li><Job Reference Number: wru01</li>
<li><Job Reference Number: wru01</li>
I need to create a link (using javascript) that when each job description is clicked it auto fills out the form where the job description should be entered (this form is on another html page)
html file 2:
<legend>Job Application Information: </legend>
<label> Job Reference Number: </label>
<input id="refnumber" type="text" name="refnumber" required="required" />
so basically i need it that, when, and depending on which job number is clicked wru01 or wru02, it auto fills the job reference number in the form on the next page using local storage.
I have already tried this
js file 1
function onclick1() {
var anchor = document.getElementById('link');
anchor.addEventListener('click', function(event) {
event.preventDefault();
const jobCode = event.target.getAttribute('data-job');
localStorage.setItem('job-code', jobCode);
//need redirect user to apply page
//console.log(event.target)
window.location = event.target.getAttribute('href');
})
}
function onclick2() {
var anchor = document.getElementById('link2');
anchor.addEventListener('click', function(event) {
event.preventDefault();
const jobCode = event.target.getAttribute('data-job');
localStorage.setItem('job-code', jobCode);
//need redirect user to apply page
//console.log(event.target)
window.location = event.target.getAttribute('href');
})
}
function init() {
document.getElementById("link").onclick = function() {
onclick1()
};
document.getElementById("link2").onclick = function() {
onclick2()
}
window.onload = init;
}
js file 2
function LoadJobCode() {
var code = localStorage.getItem('job-code');
if (code) {
var input = document.getElementById('refnumber');
// disable text being entered
input.value = code;
input.disabled = true;
}
}
Excuse me,that's not a good idea to do it.I think you can use setTimeout to solve the problem.that's my code:
function onclick1() {
var anchor = document.getElementById('link');
anchor.addEventListener('click', function (event) {
event.preventDefault();
const jobCode = event.target.getAttribute('data-job');
console.log(jobCode)
localStorage.setItem('job-code', jobCode);
setTimeout(() => {
window.location.href = event.target.getAttribute('href');
},1000)
})
}
why did I do that?That's order to make sure to save the data(data-job) before entering another html page.Likewise,you can use async/await,such as below:
function onclick1() {
var anchor = document.getElementById('link');
anchor.addEventListener('click', function (event) {
event.preventDefault();
const jobCode = event.target.getAttribute('data-job');
console.log(jobCode)
localStorage.setItem('job-code', jobCode);
async function locate() {
await new Promise(() => {
window.location.href = event.target.getAttribute('href');
})
}
locate();
})
}