Would like to copy current URL to clipboard show a notice message and hide again after few seconds. I've seen this function online.
The animated gif shows how it should work. Javascript part is extracted from a website with a working example and the same HTML and CSS code used, but the javascript is not formatted correctly yet, because i extracted only the part this function needs. Can someone help me write the javascript correctly? Fiddle is ready to go:
Fiddle example
Extracted javascript
events: {
"click .share": "onShareClick"
},
onMouseEnter: function() {},
onShareClick: function(e) {
var t = this;
this.$el.find(".share").addClass("show-notice"), setTimeout(function() {
t.$el.find(".share").removeClass("show-notice")
}, 3e3);
var n = document.createElement("textarea");
n.value = location.href, document.body.appendChild(n), n.select(), document.execCommand("copy"), document.body.removeChild(n)
},
HTML
<div class="share">
<img src="images/share.svg">
<span class="share-notice">Link copied to clipboard</span>
<span class="mouseenter-notice">Share</span>
</div>
Assuming the div is the first of member of the 'share' class within the doc you could try:
const div = document.getElementsByClassName('share')[0];
const shareNotice = document.getElementById('share-notice');
const mouseoverNotice = document.getElementById('mouseover-notice');
div.onclick = () => {
window
.navigator
.clipboard
.writeText(window.location.href);
shareNotice.style.display = 'initial';
window.setTimeout(() => shareNotice.style.display = 'none', 1500);
};
div.onmouseover = () => mouseoverNotice.style.display = 'initial';
div.onmouseleave = () => mouseoverNotice.style.display = 'none';
.share { cursor: pointer }
#share-notice { display: none; }
#mouseover-notice { display: none; }
<div class="share">
x
<span id="share-notice">Link copied to clipboard</span>
<span id="mouseover-notice">Share</span>
</div>
Take a look at the clipboard API: https://developer.mozilla.org/en-US/docs/Web/API/Clipboard_API
For convenience you might want to use clipboard js: https://clipboardjs.com/
You can access the current url with window.location.href.
Related
this is my code:
const clcBtn = document.getElementById("calcButton");
let clcInput = document.getElementById("calcInput");
const result = document.getElementById('paragraph');
const loader = document.getElementById('spinner');
clcBtn.addEventListener("click", calcFunc);
function calcFunc() {
loader.classList.add("display")
fetch(`http://localhost:5050/fibonacci/`).then(function (response) {
return response.json().then(function (data) {
result.innerHTML = data.clcInput.value; // i want to get the input value from the input field and the server to calculate it and present it to the user.
});
});
}
basically what i want to do, is to add the value the user types in to the innerHTML paragraph id name.
and then i want to make the button react to the click and re-display the "loader" (which i gave it display:none in the CSS file)
and then, i need to make the button to display an error message if the input is higher than 50.
what i have tried to do:
inside the
clcBtn.addEventListener("click", calcFunc);
function calcFunc() {
i have tried to add:
loader.classlist.add("display")
and inside
return response.json().then(function (data) {
result.innerHTML = data.clcInput.value;
i have tried to add and change it to:
clcInput.value = innerHTML.result;
what am i doing wrong?
what is wrong with my syntax and what is the order i need to write everything?
thank you!!!
If i understand correctly what is you need, you should look at the small snippets I did below. It show a loader during the API Call and hide it when you get the result as well as updating the info paragraph depending on the value you typed.
The main thing I recommend you changing in order for your code to work properly is not adding or removing a class to your spinner element to hide it and show it, but simply changing directly it's style by using loader.style.display = "value"
Hope it helps.
const clcBtn = document.getElementById("calcButton");
let clcInput = document.getElementById("calcInput");
const result = document.getElementById('paragraph');
const loader = document.getElementById('spinner');
clcBtn.addEventListener("click", calcFunc);
function calcFunc() {
paragraph.innerText= "";
loader.style.display = "block";
// TimeOut to simulate API Call
setTimeout(function() {
loader.style.display = "none";
if (clcInput.value > 50) {
paragraph.innerText = clcInput.value + " - Error, value too high";
} else {
paragraph.innerText = clcInput.value + " - Value correct";
}
}, 2000);
}
#spinner {
width: 50px;
height: 50px;
border-radius: 50%;
background-color: white;
border: 5px solid black;
display: none;
}
<input type="number" id="calcInput" />
<button id="calcButton">calcButton</button>
<div id="spinner"></div>
<p id="paragraph"></p>
I have a popup modal in Shopify, I'm using text node instead of innerHtml for security concerns. However, everytime I open the popup modal, the text node keeps getting appended to my h1 tag. Is there any way to check if the node already has been appended? (I don't want to use a boolean value to check if text node has been appended)
html:
<h1 id="ProductHeading" class="product__title product__title--template"></h1>
<h2 id="ProductHeadingModal" class="product__title product__title--template product__title--modal"></h2>
javascript:
var title = document.createTextNode(product.title);
// Product heading is an element with h1 tag
var productHeading = document.getElementById("ProductHeading");
if(// how to check if element has no node?) {
productHeading.appendChild(title);
}
the entire javascript block:
window.onload = () => {
if (window.__shgProductInits.length) {
window.__shgProductInits.forEach((ele) => {
let proId = document.getElementById(ele.uuid);
proId.setAttribute('url', ele.productHandle);
proId.style.cursor='pointer';
proId.addEventListener('click', (e) => {
let productHandle = e.target.parentElement.parentElement.parentElement.getAttribute('url');
fetch('/products/'+productHandle+'.js')
.then((res) =>{return res.json()})
.then((product) => {
console.log(product)
var product = product;
document.getElementsByClassName("product-modal")[0].style.display = "block";
var title = document.createTextNode(product.title);
var productHeading = document.getElementById("ProductHeading");
var productHeadingModal = document.getElementById("ProductHeadingModal");
if(!(productHeading.hasChildNodes())) {
productHeading.appendChild(title);
productHeadingModal.appendChild(title);
var price = document.createTextNode("$" + parseInt(product.price).toFixed(2));
document.getElementById("product-price").appendChild(price);
}
document.getElementById("product-image").src = product.images[0];
});
});
});
}
ProductHeading itself is not a node (I think). And checking innerHtml for length doesn't work as it is always 0
Update:
I've added the conditional check, it still returns false everytime I open the modal.
My code:
My browser console:
My website displays:
Inspect element in browser:
A couple of ways:
if (element.firstChild) {
// It has at least one
}
or the hasChildNodes() function:
if (element.hasChildNodes()) {
// It has at least one
}
or the length property of childNodes:
if (element.childNodes.length > 0) { // Or just `if (element.childNodes.length)`
// It has at least one
}
So you can just write this
var title = document.createTextNode(product.title);
// Product heading is an element with h1 tag
var productHeading = document.getElementById("ProductHeading");
if(!(productHeading.hasChildNodes())) {
productHeading.appendChild(title);
}
Referring this answer
if (productHeading.hasChildNodes()) {
}
to put it simply, I am trying to add a hover effect onto my cv.
I want when someone hovers over my linkedin icon, for it to display a text underneath saying "LinkedIn"
However I need this to be in Javascript.
html part <i class="icon-linkedin"></i>
<div id="popup">LinkedIn</div>
js part
var e = document.getElementById('liIcon');
e.onmouseover = function() {
document.getElementById('popup').style.display = 'block';
}
e.onmouseout = function() {
document.getElementById('popup').style.display = 'none';
}
and css part
#popup {
display:none;
}
Any idea why it isn't working?
Thanks.
I noticed a few semicolons missing after the onmouseovers. I'm not an expert on JS, but an unterminated statement looks weird.
Also, I added a LinkedIn text to the button, cause there's no image link visible in the following code. This is how your code should be structured for your code to work (assuming your browser doesn't have JavaScript disabled):
<!DOCTYPE html>
<html>
<head>
<style>
#popup {
display: none;
}
</style>
</head>
<body>
<i class="icon-linkedin">LinkedIn</i>
<div id="popup">LinkedIn</div>
<script>
var e = document.getElementById('liIcon');
e.onmouseover = function () {
document.getElementById('popup').style.display = 'block';
};
e.onmouseout = function () {
document.getElementById('popup').style.display = 'none';
};
</script>
</body>
</html>
No hover:
Hover:
Sometimes selectors can get fussy, I've run into issues with tags nested in other elements similar to what you have here.
Have you tried adding an event listener to the icon tag as well?
var icon = document.getElementById('liIcon').getElementsByClassName('icon-linkedin');
// assuming there is only one element of class: icon-linkedin, access element by index 0
icon[0].onmouseover = function () {
document.getElementById('popup').style.display = 'block';
};
icon[0].onmouseout = function () {
document.getElementById('popup').style.display = 'none';
};
There is a prompt in the lower left corner When I put the mouse over the tag,
and can u tell me how to forbid this phenomenon.enter image description here
As commented, the behaviour that you wish to stop is a browser's feature.
To avoid this, you will have to simulate anchor's behaviour on your own but as you said you have many anchors and you cannot manually convert them to buttons, you can try following code:
function maskAnchors() {
var els = document.querySelectorAll('a[href]');
console.log("Anchors Found: ", els.length)
for (var i = 0; i < els.length; i++) {
els[i].setAttribute("data-url", els[i].getAttribute('href'));
els[i].removeAttribute("href");
els[i].addEventListener("click", handleClick)
}
}
function handleClick() {
var url = this.getAttribute('data-url');
window.open(url)
}
document.getElementById('btnAdd').addEventListener("click", function() {
var container = document.querySelector('.content');
var link = document.createElement('a')
link.href = "www.google.com";
link.textContent = "This is a newly added link";
container.append(link)
})
document.getElementById('btnMask').addEventListener("click", maskAnchors)
window.addEventListener('load', maskAnchors)
.maskedAnchor {
color: -webkit-link;
text-decoration: underline;
cursor: auto;
}
<div class="content">
Google
Facebook
StackOverflow
YouTube
Example
<a>blabla</a>
</div>
<button id="btnAdd">Add Anchor</button>
<button id="btnMask">Run masking</button>
Note:
Removing href will change styling. You will also have to do that manually.
This will not handle any anchors added dynamically after execution of this function. You will have to call this function again. I have optimised function to only fetch anchors that has href
Hope it helps!
Weave: http://kodeweave.sourceforge.net/editor/#5dbb5ce4a85bcaf4c5805e337c829e73
I have three textareas:
1 for HTML
1 for CSS
and 1 for JavaScript code
Whenever code is added in these textareas (I'm using keyup for the same of this post) I call a function called runEditor which adds the code into the iframe.
What I'm trying to figure out is how can I call the same function when CSS is added without adding the HTML or the JavaScript again?
var htmlEditor = document.querySelector(".html")
var cssEditor = document.querySelector(".css")
var jsEditor = document.querySelector(".js")
function runEditor() {
var previewFrame = document.querySelector(".preview")
var preview = previewFrame.contentDocument || previewFrame.contentWindow.document
preview.open()
preview.write("<style>"+ cssEditor.value +"</style>" + htmlEditor.value + "<scr"+"ipt>"+ jsEditor.value +"</scr"+"ipt>")
preview.close()
}
runEditor()
htmlEditor.onkeyup = function() {
runEditor()
}
cssEditor.onkeyup = function() {
runEditor()
}
jsEditor.onkeyup = function() {
runEditor()
}
textarea {
width: 30%;
height: 100px;
}
.preview {
width: 100%;
}
<textarea class="html">
<button>
Hello world
</button>
<div class="output"></div>
</textarea>
<textarea class="css">body {
background: #52b165;
}</textarea>
<textarea class="js">
var output = document.querySelector(".output")
var btn = document.querySelector("button")
var counter = 0
function addElm() {
var node = document.createElement("div")
var txt = document.createTextNode("hi " + counter++)
node.appendChild(txt)
output.appendChild(node)
}
btn.addEventListener("click", function() {
addElm()
})
</textarea>
<iframe class="preview" sandbox="allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts"></iframe>
When you set up the iframe, you have access to both window and document objects inside the iframe. You have access to methods like document.getElementById and friends.
To reload the CSS, suggesting you create a <style> element in the iframe. When CSS changes, wipe out the contents of that element and put in the new CSS. HTML can do the same, wiping out the HTML of <body> and replacing it with the new HTML. innerHTML will be your friend. JS will be a bit tricky. You will need to recreate the iframe from the beginning to start fresh.