execCommand copy async alternative for Firefox - javascript

document.execCommand('copy') can be used inside the resolve function of a Promise except for Firefox.
Every modern browsers like Chrome, Opera, and even Safari allow async copy up to 1 second.
I want to improve the user experience and copy data following a calculation in the clipboard.
Is there a solution to copy the result of a Promise with Firefox in one click?
Here a snippet working with Chrome
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Test</title>
</head>
<body>
<button onclick="copy(genPwd)">copy</button>
<script>
function genPwd() {
return new Promise(function(resolve) {
resolve('toto')
})
}
function copy(p) {
p().then(function(result) {
console.log('create fake text area');
var fakeTextArea = document.createElement('textarea');
fakeTextArea.setAttribute('readonly', '');
fakeTextArea.value = result;
document.body.appendChild(fakeTextArea);
fakeTextArea.select();
document.execCommand('copy');
});
}
</script>
</body>
</html>

Related

rotating a square on the click of a button in javascript

I made a program to rotate a square made with h1 tag on the click of a button. but it is not working. could anybody take a look at this code and say what is wrong here.
// storing a button which has the id rotate1 in a variable
let button = document.querySelector("#rotate1");
// storing the square which has an id 'square' in a variable
let square = document.querySelector("#square");
let degree = 0;
// calling a function rotate on every 10 milliseconds
let a = setInterval(rotate , 10);
// defing rotate function
function rotate(){
button.onclick = ()=>{
//stop calling when the variable degree is greater than or equal to 360deg. I am doing this for stopping the square from rotating when it has comnpleted a rotation.
if(degree>=360){
clearInterval(a);
}
// else incrementing degree and rotating the square.
else{
degree++;
rotate1.style.transform = "rotateX("+degree+"deg)"
}
}
}
when i click the button the square is not rotating. Why is it not rotating. I tried my best to explain the question. could anybody tell me whats wrong here and how to solve it.
html:
<!DOCTYPE html>
<html lang="en">
<head>
<link rel = "stylesheet" href = "practise.css">
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1 id="square"></h1>
<button id="rotate1">Rotate</button>
<script src="practise.js"></script>
</body>
</html>
currently you rotate the button #rotate1 not h1 then it rotate the element based on click not setInterval, but you can write it like below
// storing a button which has the id rotate1 in a variable
let button = document.querySelector("#rotate1");
// storing the square which has an id 'square' in a variable
let square = document.querySelector("#square");
let degree, interval;
// defing rotate function
function rotate() {
//stop calling when the variable degree is greater than or equal to 360deg. I am doing this for stopping the square from rotating when it has comnpleted a rotation.
if (degree >= 360) {
clearInterval(interval);
}
// else incrementing degree and rotating the square.
else {
degree++;
square.style.transform = "rotateX(" + degree + "deg)"
}
}
button.onclick = () => {
degree = 0;
interval = setInterval(rotate, 10);
}
h1{display: block;width: 100px;height: 100px;background: red;}
<h1 id="square"></h1>
<button id="rotate1">Rotate</button>
Beat me to it but here's my solution...
// storing a button which has the id rotate1 in a variable
let button = document.getElementById("rotate1");
// storing the square which has an id 'square' in a variable
let square = document.getElementById("square");
let degree = 0;
button.onclick = function(event) {
degree += 360;
square.style.transform = "rotate("+degree+"deg)";
}
#square {
height:50px;
width:50px;
background-color:red;
transition:0.4s ease all;
}
<!DOCTYPE html>
<html lang="en">
<head>
<link rel = "stylesheet" href = "practise.css">
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button id="rotate1">Rotate</button>
<div id="square"></div>
<script src="practise.js"></script>
</body>
</html>

why Graph is not showing until i minimize window. (using chart.js )

I'm using chart.js for first time and I'm facing problem in drawing graph. When I run this code, Graph axis are shown only but bars are not shown until I minimize or change browser window size. This is happening every time. Maybe this has to do with responsiveness. Any help about what I'm doing wrong here. I'm using visual studio and chrome for rendering graph.
let labels=[]
let duration=[]
let file="assets/duration.csv";
d3.csv(file).then(
function (loaddata) {
for (let i = 0; i < loaddata.length; i++) {
//console.log(loaddata.hours)
if (loaddata[i].hours != 0)
{
duration.push(loaddata[i].hours)
labels.push(loaddata[i].Trend)
}
}
//console.log(labels)
//console.log(duration)
}
);
let options={
type: 'bar',
responsive: true,
title: {
display:true,
text:'Duration of Trending Tweets'
},
data: {
labels:labels,
datasets:[{
data: duration,
label: 'Hours',
backgroundColor:["#3e95cd"]
}]
}
};
let chart=new Chart(document.getElementById('canvas'),options);
<!DOCTYPE html>
<html lang="en">
<head>
<script src="chart.min.js"></script>
<script src ="https://cdn.jsdelivr.net/npm/chart.js#3.7.1/dist/chart.min.js">
</script>
<script src="http://d3js.org/d3.v5.min.js" charset="utf-8"></script>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My first website</title>
</head>
<body>
<h1>Hello world</h1>
<div>
<canvas id="canvas" style="position: relative; height:40vh; width:80vw">
</canvas>
</div>
<script src="index.js">
</script>
</body>
</html>
The problem is that you create the chart before the CSV data is loaded. Be aware that the d3.csv request is processed asynchronously.
This can be solved by creating the chart only once the CSV data is fully loaded (at the end and inside of d3.csv(file).then( ... ).
An alternative approach is described in this answer.

I dont know whats wrong with this simple javascript code, I have checked this over and over again but does not work

Simple image expanding on mouseover and opposite on mouseout, I checked the code over and over, putting alert messages at each line to see if its working, alert message work all the way to the end but there is no effect on the image. I am so confused, I dunno whats wrong.
var side = 200;
var a = 20;
var t = 0;
function expand() {
console.log("expand is ok");
clearInterval(t);
t = setInterval(grow, 20);
}
function grow() {
console.log("Entered grow");
if (side < 300) {
console.log("entered if loop");
side = side + a;
document.getElementById("new").style.width = side;
console.log("After statement")
} else
clearInterval(t);
console.log("clear")
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Zoom in Zoom out</title>
</head>
<body>
<img src="../images/women.jpg" id="new" alt="Women" onmouseover="expand()" width=2 00px>
</body>
</html>
To expand on my comment:
The issue is you're trying to assign a raw number such as 200 to the width CSS property.
If you look at CSS, you'd spell "200 pixels" as
foo {
width: 200px;
}
so similarly you'll need to endow the dynamic manipulation with an unit (pixels here):
foo.style.width = `${width}px`;

PWA in iOS 12 no longer re-executing Javascript when re-opening app

I have a PWA which essentially re-directs the user to the messages app on open using Javascript. With the roll-out of iOS 12 and changes to PWAs, the webpage no longer re-initializes and executes the Javascript when it is re-opened or when it re-gains focus. Instead, it now loads the previously saved state and won't re-execute the Javascript.
Does anyone have any ideas around this? Can I force Javascript execution every time the PWA has focus? Can I force the page to re-initialize on load?
Sample code below:
<html manifest="ios/scripts/offline.manifest">
<head>
<meta content="en-us" http-equiv="Content-Language" />
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>SMS</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="apple-mobile-web-app-title" content="SMS">
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<link rel="apple-touch-icon" sizes="180x180" href="ios/img/Icon-60x60#3x.png">
<link rel="apple-touch-startup-image" href="ios/img/LaunchImage-1125#3x~iphoneX-portrait_1125x2436.png" media="(device-width: 375px) and (device-height: 812px) and (-webkit-device-pixel-ratio: 3) and (orientation: portrait)">
</head>
<body>
<script>
if (window.navigator.standalone) {
document.write('<a id="url" href="sms:1111111111" name="url"></a>');
var e = document.getElementById('url');
var ev = document.createEvent('MouseEvents');
ev.initEvent('click', true, true);
e.dispatchEvent(ev);
}
</script>
</body>
</html>
I encountered the same problem. Here is what I did to force PWA to execute javascript at start:
Register page visibility event in your javascript that is embedded
between tags.
Within the event handler of page visibility event, execute javascript that you want to execute when subsequently open PWA.
Any time PWA is opened, it will trigger page visibility event and execute your script.
Example: in your html file:
<script>
registerPageVisibility()
</script>
function registerPageVisibility() {
let hidden;
let visibilityChange;
if (typeof document.hidden !== 'undefined') { // Opera 12.10 and Firefox 18 and later support
hidden = 'hidden';
visibilityChange = 'visibilitychange';
} else if (typeof document.msHidden !== 'undefined') {
hidden = 'msHidden';
visibilityChange = 'msvisibilitychange';
} else if (typeof document.webkitHidden !== 'undefined') {
hidden = 'webkitHidden';
visibilityChange = 'webkitvisibilitychange';
}
window.document.addEventListener(visibilityChange, () => {
if (!document[hidden]) {
//put your script here and it will be execute everytime when PWA is opened.
}
});
}
Take a look at this post re PWA 'state': Progressive Web App Progress in iOS 12.2 Beta 1 (Build 16E5181f)

How open a new tab in browser without blocking?

Haxe/OpenFL code:
import openfl.net.URLRequest;
import openfl.Lib;
Lib.getURL (new URLRequest (url), "_self");
// Opens the linked document in the same window or tab as it was clicked
Lib.getURL (new URLRequest (url), "_blank");
// Opens the linked document in a new window or tab. (this is default)
However, the second option generate popup that is blocked by Chrome.
How to open a link in another tab without being blocked?
With Javascript this work:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>OpenNewTab</title>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<meta name="apple-mobile-web-app-capable" content="yes">
</head>
<body>
<center>
<canvas id="myCanvas" width="200" height="200" style="border-style: solid; border-width: 1px"> </canvas>
</center>
<script>
var canvas;
var linkURL = "http://www.google.com";
createLink();
function createLink() {
canvas = document.getElementById("myCanvas");
canvas.addEventListener("click", Link_click, false);
}
function Link_click(e) {
window.open(linkURL,'_blank');
}
</script>
</body>
</html>
P.s: I use Stencyl and HTML/JavaScript.
I believe if the popup is opened from a user triggered event (like pointer down, click) no popupblocker should prevent opening it.
note: Personally I find it annoying that a developer decides how a window should be opened, why not let the user decide that theirselves?
While I do not find better solution I will use this:
import openfl.net.URLRequest;
import openfl.Lib;
class Web
{
public static function open(s:String, code:Int)
{
var type:String = "_self";
var s:String = s;
var code:Int = code;
if(code==1){
type = "_self";
}else if(code==2){
type = "_blank";
}
#if js
untyped __js__('
var canvas;
var linkURL = s;
var lock = 0;
if(lock==0){
lock =1;
createLink();
}
function createLink() {
canvas = document.getElementById("openfl-content");
canvas.addEventListener("click", Link_click, false);
}
function Link_click(e) {
window.open(linkURL,type);
}
');
#else
Lib.getURL (new URLRequest (s), type);
#end
}
}

Categories

Resources