Copy default value to clipboard - javascript

I want to copy a default value to clipboard, without using input. Thats something wrong with my function, but I don't know what it is.
var copyText = "Default value";
const showText = document.querySelector(".copied");
const copyMeOnClipboard = () => {
copyText;
document.execCommand("copy")
showText.innerHTML = `Copied!`
setTimeout(() => {
showText.innerHTML = ""
}, 1000)
}
<button class="submitBtn" onclick="copyMeOnClipboard();">Copy link</button>
<p class="copied"></p>

From MDN's page on execCommand, emphasis added:
Copies the current selection to the clipboard. Conditions of having this behavior enabled vary from one browser to another, and have evolved over time.
You'll want to use the Clipboard API's writeText instead, like so:
var copyText = "Default value";
const showText = document.querySelector(".copied");
const copyMeOnClipboard = () => {
navigator.clipboard.writeText(copyText).then(() => {
showText.innerHTML = `Copied!`
setTimeout(() => {
showText.innerHTML = ""
}, 1000)
})
}
<button class="submitBtn" onclick="copyMeOnClipboard();">Copy</button>
<p class="copied"></p>

Related

Cant Copy Text To Clipboard

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>

Make function delete

I recently tried to make a page that saves the input and displays it on the page. Everything works but i want to add a delete button at every input, which deletes only one input. I tried so many different ways, but none of them worked. If you have any idea how to solve this, I would be grateful.
Here is the code:
let savedinput = []
Localstoragesaves = localStorage.getItem("Zaznamki")
const Predpomnjenipodatki = JSON.parse(Localstoragesaves)
const DeleteButtonHTML = document.getElementById("izbrisi-gumb")
const userinput = document.getElementById("vnos-pr")
const inputsavebutton = document.getElementById("vnos-gumb")
const LabelHTML = document.getElementById("seznamzaznamkov")
const SaveTab = document.getElementById("zavihek-gumb")
const DeleteLast = document.getElementById("pocisti-zadnjo")
if (Localstoragesaves) {
savedinput = Predpomnjenipodatki
Render(savedinput)
}
DeleteLast.addEventListener('click', function(){
savedinput.pop()
Render(savedinput)
})
SaveTab.addEventListener('click',
function(){
browser.tabs.query({active: true, currentWindow: true}, function(tabs){
savedinput.push(tabs[0].url)
localStorage.setItem("Zaznamki", JSON.stringify(savedinput))
Render(savedinput)
console.log( localStorage.getItem("Zaznamki") )
})
})
function Render(parameter) {
let tabslabel = ""
for (i = 0; i < parameter.length; i++) {
tabslabel += `
<li>
<a href='${parameter[i]}' target='_blank'>${parameter[i]}</a>
</li>
`
}
LabelHTML.innerHTML = tabslabel
}
DeleteButtonHTML.addEventListener('dblclick',
function() {
localStorage.clear()
savedinput = []
LabelHTML.textContent = ''
})
inputsavebutton.addEventListener("click", function(){
const Vsebinavnosa = userinput.value
savedinput.push(Vsebinavnosa)
localStorage.setItem("Zaznamki", JSON.stringify(savedinput))
Render(savedinput)
userinput.value = ""
console.log( localStorage.getItem("Zaznamki") )
})
I solved this problem myself. I'm quite proud 😁. I want to thank you for your really quick responses even if I didnt get the solution here.
If someone has the same problem I had, I will tell you what I did.
In function render, I added a button with onclick function with argument, so that this new function which will be called will know which item from array needs to remove:
<button id="${parameter[i]}" onclick="Delete(${i})">Delete</button>
and then somewhere in this document I added this function which gets value from button click and knows which item from the array savedinput and localstorage needs to remove:
function Delete(parameter) {
mojizaznamki.splice(parameter, 1)
console.log(savedinput)
localStorage.setItem("Zaznamki", JSON.stringify(savedinput))
Render(savedinput)
}
Hope this helps others.
Greetings from Slovenia

How can I run javascript file after dom manipulation made in another js file?

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')
}
})

Is there a way to subscribe to changes in window.getSelection?

We are able to get a selection range via window.getSelection().
I'm wondering whether there is a way to subscribe to window.getSelection changes.
The only way which came to me is to use timeouts (which is obviously bad) or subscribe to each user's key \ mouse press event and track changes manually.
ANSWER UPD: You are able to use this library, I've published it, as there are no more suitable ones: https://github.com/xnimorz/selection-range-enhancer
Use the onselect event.
function logSelection(event) {
const log = document.getElementById('log');
const selection = event.target.value.substring(event.target.selectionStart, event.target.selectionEnd);
log.textContent = `You selected: ${selection}`;
}
const textarea = document.querySelector('textarea');
textarea.onselect = logSelection;
<textarea>Try selecting some text in this element.</textarea>
<p id="log"></p>
For specific cases such as span contenteditable, you can make a polyfill:
function logSelection() {
const log = document.getElementById('log');
const selection = window.getSelection();
log.textContent = `You selected: ${selection}`;
}
const span = document.querySelector('span');
var down = false;
span.onmousedown = () => { down = true };
span.onmouseup = () => { down = false };
span.onmousemove = () => {
if (down == true) {
logSelection();
}
};
<span contenteditable="true">Try selecting some text in this element.</span>
<p id="log"></p>
if Im undesrting in right way you want to know when user start selection on page you can use DOM onselectstart.
document.onselectstart = function() {
console.log("Selection started!");
};
more info MDN

Why doesn't my input onChange work in Edge?

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.

Categories