Bookmarklet to briefly flash a message - javascript

Trying to develop a Bookmarklet to copy contents of a specific field on webpage AND then briefly flash a confirmation message. Already have both parts working separately. Can't figure out how to combine them to be able to then put that code into URL field of Bookmarklet.
javascript: (function(){var copyText = document.getElementById("mergeFields-input-text");copyText.select();document.execCommand("Copy");
function tempAlert(msg,duration)
{
var el = document.createElement("div");
el.setAttribute("style","position:absolute;top:5%;left:20%;background-color:white;");
el.innerHTML = msg;
setTimeout(function(){
el.parentNode.removeChild(el);
},duration);
document.body.appendChild(el);
}
var d = document.getElementById('mergeFields-input-text');
d.onclick = function(){ tempAlert("Copied",5000); })();

No need to add the 'onclick' event. Try this bookmarklet:
javascript:(function() {
var copyText = document.getElementById("mergeFields-input-text");
copyText.select();
document.execCommand("Copy");
tempAlert("Copied", 5000);
function tempAlert(msg, duration) {
var el = document.createElement("div");
el.setAttribute("style","position:absolute;top:5%;left:20%;background-color:white;");
el.innerHTML = msg;
document.body.appendChild(el);
setTimeout(function(){
el.parentNode.removeChild(el);
}, duration
);
}
})();

Above code from Shugar answers my question for copying, and this code below, also from him, does same except pasting:
javascript:(function() {
var pasteText = document.getElementById("mergeFields-input-text").select();
document.execCommand("Paste");
tempAlert("PASTED SUBJECT", 500);
function tempAlert(msg, duration) {
var el = document.createElement("div");
el.setAttribute("style","position:absolute;top:2%;left:45%;background-color:yellow;");
el.innerHTML = msg;
document.body.appendChild(el);
setTimeout(function(){
el.parentNode.removeChild(el);
}, duration
);
}
})();

Related

Fixing Issue in a simple text field value changer using basic HTML and JS

Need help making a simple text editor :
Text is displayed on screen
Click on Text to change it
Click change button to see the changes
but program goes in an infinite oop
var creators = {
hTag :function(textToInput){
var h1 = document.createElement('h1');
var div = document.getElementById('main');
div.innerHTML = '';
h1.id = 'userText';
h1.textContent = textToInput;
div.appendChild(h1);
console.log(div);
listeners.hTagListener();
//document.querySelector('h1');
//hTag.addEventListener('click',this.);
},
changeField :function(){
var input = document.createElement('input');
var button = document.createElement('button');
var div = document.getElementById('main');
div.innerHTML='';
button.id = 'changeButton';
button.textContent = 'Change';
input.id = 'input';
input.type = 'text';
div.appendChild(button);
div.appendChild(input);
listeners.changeButtonListener();
}
};
var listeners = {
hTagListener : function(){
var h1Print = document.querySelector('h1');
h1Print.addEventListener('click',creators.changeField());
console.log('added event listener');
},
changeButtonListener : function(){
var but = document.getElementById('changeButton');
var inputText = document.getElementById('input');
console.log(inputText.value);
but.addEventListener('click',creators.hTag(inputText.value));}
};
creators.hTag('initialValue');
and my Main HTML is
<body>
<br>
<br>
<div id="main">
</div>
<script src="/script.js" defer></script>
Expected :
In the last line of javascript, a header tag is appended to div
which has textContent 'initialValue'.
After Clicking on it :
A text Field and change button should appear,on clicking change, new Value must be displayed as Header!
Actual :
Program goes in an infinite loop!
While adding event listener you are calling actual function instead of that you should just bind the event the modified code is below
var listeners = {
hTagListener : function(){
var h1Print = document.querySelector('h1');
h1Print.addEventListener('click',creators.changeField);
console.log('added event listener');
},
changeButtonListener : function(){
var but = document.getElementById('changeButton');
var inputText = document.getElementById('input');
but.addEventListener('click',function(){creators.hTag(inputText.value)},false);
}
Currently addEventListener click methods are directly executing onload of the screen. Due to this execution is going for the infinite loop. To avoid this bind the method as below
var listeners = {
hTagListener : function(){
var h1Print = document.querySelector('h1');
h1Print.addEventListener('click',creators.changeField.bind(this), false);
console.log('added event listener');
},
changeButtonListener : function(){
var but = document.getElementById('changeButton');
var inputText = document.getElementById('input');
console.log(inputText.value);
but.addEventListener('click',creators.hTag.bind(this, inputText.value));
}
};

Remove dynamically created elements by class name Javascript

So, in plain terms I am creating a Chrome Extension that so far can only save links from the internet but not delete them. What I want to add is a "remove" button for deleting unwanted links. So far I haven't got that to work.
The buttons I want to remove are added using JavaScript. Each new block of HTML features a "remove" button but clicking that button does nothing. I have tried binding listeners to each element using a for loop but that doesn't seem to work.
The code runs without errors and I'm certain that the issue is a slight oversight but I have only just started using JavaScript so I'm lost for solutions at the moment.
I have included all the code because I don't want to leave out anything that might be imperative to finding a solution.
It starts with the code for adding a link, followed by removing a single link and then removing all links at once. Thank you all for any help, really want to get this working.
https://github.com/mmmamer/Drop Repository for the rest of the code. Mainly popup.html and popup.css.
var urlList = [];
var i = 0;
document.addEventListener('DOMContentLoaded', function() {
getUrlListAndRestoreInDom();
// event listener for the button inside popup window
document.getElementById('save').addEventListener('click', addLink);
});
function addLink() {
var url = document.getElementById("saveLink").value;
addUrlToListAndSave(url);
addUrlToDom(url);
}
function getUrlListAndRestoreInDom() {
chrome.storage.local.get({
urlList: []
}, function(data) {
urlList = data.urlList;
urlList.forEach(function(url) {
addUrlToDom(url);
});
});
}
function addUrlToDom(url) {
// change the text message
document.getElementById("saved-pages").innerHTML = "<h2>Saved pages</h2>";
var newEntry = document.createElement('li');
var newLink = document.createElement('a');
var removeButton = document.createElement('button');
removeButton.textContent = "Remove";
//removeButton.createElement('button');
removeButton.type = "button";
removeButton.className = "remove";
newLink.textContent = url;
newLink.setAttribute('href', url);
newLink.setAttribute('target', '_blank');
newEntry.appendChild(newLink)
newEntry.appendChild(removeButton);
newEntry.className = "listItem";
document.getElementById("list").appendChild(newEntry);
}
function addUrlToListAndSave(url) {
urlList.push(url);
saveUrlList();
//}
}
function saveUrlList(callback) {
chrome.storage.local.set({
urlList
}, function() {
if (typeof callback === 'function') {
//If there was no callback provided, don't try to call it.
callback();
}
});
}
// remove a single bookmark item
document.addEventListener('DOMContentLoaded', function() {
getUrlListAndRestoreInDom();
var allButtons = document.getElementsByClassName('remove');
function listenI(i) {
allButtons[i].addEventListener('click', () => removeMe(i));
}
for (var i = 0; i < allButtons.length; i++) {
listenI(i);
}
});
function removeMe(i) {
var fullList = documents.getElementsByClassName('listItem');
listItem[i].parentNode.removeChild(listItem[i]);
}
//remove all button
document.addEventListener('DOMContentLoaded', function() {
document.getElementById("remove-all").addEventListener('click', function() {
var removeList = document.getElementsByClassName("listItem");
while(removeList[0]) {
removeList[0].parentNode.removeChild(removeList[0]);
}
})
});
chrome.storage.local.get() is asynchronous. So when you try to add the event listeners to the Remove buttons, they're not in the DOM yet.
You can add the listener in the addUrlToDom() function instead. That way you'll also add the event listener when you create new buttons.
function addUrlToDom(url) {
// change the text message
document.getElementById("saved-pages").innerHTML = "<h2>Saved pages</h2>";
var newEntry = document.createElement('li');
var newLink = document.createElement('a');
var removeButton = document.createElement('button');
removeButton.textContent = "Remove";
//removeButton.createElement('button');
removeButton.type = "button";
removeButton.className = "remove";
newLink.textContent = url;
newLink.setAttribute('href', url);
newLink.setAttribute('target', '_blank');
newEntry.appendChild(newLink)
newEntry.appendChild(removeButton);
removeButton.addEventListener("click", function() {
var anchor = this.previousElementSibling;
var url = anchor.getAttribute("href");
removeUrlAndSave(url);
this.parentNode.remove();
});
newEntry.className = "listItem";
document.getElementById("list").appendChild(newEntry);
}
function removeUrlAndSave(url) {
var index = urlList.indexOf(url);
if (index != -1) {
urlList.splice(index, 1);
saveUrlList();
}
}

Javascript onclick() show and onclick() hide

I wanted to make a function with onclick where if I press the div the content should be displayed. If I click on that content it will give me the "starting"-form.
Let me show you the code:
HTML:
<div id="demo">click</div>
Javascript:
var div = document.getElementById("demo");
var info = "This is the information for the user.";
var status = true;
if(status){
div.onclick = function() { div.innerHTML = info };
status=false;
}
else {
div.onclick = function() { div.innerHTML = "click" };
status=true;
}
So I made a variable status that checks what is being shown.
I hope i could express myself good enough. :)
The if statement is not going to magically run again. You need to do the check inside the click. Do not try to bind separate click events.
(function () {
var div = document.getElementById("demo");
var info = "This is the information for the user.";
var status = false;
div.addEventListener("click", function() {
status = !status;
div.innerHTML = status ? info : "click";
});
}());
<div id="demo">click</div>

javascript - replace text with tags

i do not know much about javascript searched long, but didn't get the reslut i need.
i want to replace on page load this
<p>---SOMERANDOMTEXT:::</p>
with
<strong>SOMERANDOMTEXT</strong>
played with this an many other snippets..
<script type="text/javascript">
window.onload = function() {
function myscript() {
input = '---';
output='New Text';
document.body.innerHTML = document.body.innerHTML.replace(input,output);
}
}
</script>
Here is the fast and fool proof way of replacing <p> tags with <strong> tags:
var ps = document.getElementsByTagName('p');
for (var i = ps.length; i--;) {
var strong = document.createElement('strong'),
p = ps[i];
while (p.firstChild) {
strong.appendChild(p.firstChild);
}
p.parentNode.insertBefore(strong, p);
p.parentNode.removeChild(p);
}
If you need to change the text accordingly, place something like that in the while loop:
if (p.firstChild.nodeType === 3) {
p.firstChild.nodeValue = p.firstChild.nodeValue.replace(/[-:]{3}/g, '');
}
DEMO: http://jsfiddle.net/5m9Qm/1/
You need to call your myscript function like this -
window.onload = function() {
myscript();
}
function myscript() {
var input = '---';
var output='New Text';
document.body.innerHTML = document.body.innerHTML.replace(input,output);
}
You are declaring a function myscript but never invoking it. Try this (untested) code:
<script>
window.onload = function(){
var p = document.querySelector('p');
var strong = document.createElement('strong');
strong.innerHTML = 'replaced';
p.parentNode.replaceChild(strong,p);
})
</script>
Note this requires modern browsers.
You can use a regex.
Try:
output = document.body.innerText.replace(/[-:]{3}/g, '');
document.body.innerHTML = document.body.innerHTML.replace(/<p>---.*:::<\/p>/, '<strong>' + output + '</strong>');
DEMO

Manipulating HTML in Javascript

I am trying to manipulate the text that is already inside the div and replace it with another strings from JavaScript, creating a basic animating effect by replacing particular character from strings present inside the div element, more precisely position based replacement of string. However when I wrote down the following code it doesn't work. What I wanted to do is that store the original text in one variable and when the dom replacement of text occurs then setting certain interval replace by the old text and again replace by the new randomize text creating text replacement animation in certain position of the text.
code :
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var all ="ABCDEFGHIJKLMNOPQRSTUVWXYZa{}[];:></?bcdefghijklmnopqrstuvwxyz0123+_)(*&^%$##!~`456789";
var old_text = document.getElementById("text").innerText;
function randChar() {
"use strict";
return all.charAt(Math.floor(Math.random()*all.length));
}
function main() {
"use strict";
var $_inter = setInterval(function() {
var text = document.getElementById("text");
text.innerHTML = text.innerHTML.substring(0, 5) + randChar() + text.innerHTML.substring(5);
setTimeout(function(){
text.innerHTML = old_text;
},200);
}, 350);
}
window.onload = main;
</script>
</head>
<body>
<div id="text">Hello World!</div>
</body>
</html>
So in order to make it work for a while I used the original string as
setTimeout(function(){
text.innerHTML = "Hello World!";
},200);
Which is not possible as the text in page might have been generated dynamically. When I did run the first code it says innerText of Null.
The exact error it throws is:
Uncaught TypeError: Cannot read property 'innerText' of null
What does that mean, because text and element is there why can't it grab the text from dom?
Cannot read property 'innerText' of null
Your problem is being cause because you're getting #text before it is defined.
var old_text = document.getElementById("text").innerText;
You should include this in your window.onload function as it will exist then.
Uncaught ReferenceError: flag is not defined
Once you do that you will receiving another error:
Uncaught ReferenceError: flag is not defined
For the line:
flag = flag+1;
This is because you have not defined your flag variable, this can be fixed by defining var flag; at the top of your first.
Demo
jsFiddle
var all ="ABCDEFGHIJKLMNOPQRSTUVWXYZa{}[];:></?bcdefghijklmnopqrstuvwxyz0123+_)(*&^%$##!~`456789";
var old_text;
var flag = 0;
function randChar() {
"use strict";
return all.charAt(Math.floor(Math.random()*all.length));
}
function main() {
"use strict";
old_text = document.getElementById("text").innerText;
var counter = Math.floor(Math.random()*document.getElementById("text").innerText.length);
var $_inter = setInterval(function() {
var text = document.getElementById("text");
text.innerHTML = text.innerHTML.substring(0, 5) + randChar() + text.innerHTML.substring(5);
setTimeout(function(){
text.innerHTML = old_text;
},200);
flag = flag+1;
}, 350);
}
window.onload = main;
Error in Firefox
With the above code we're still receiving the original error in Firefox. This is because Firefox doesn't implement innerText. This can be fixed by using either .textContent or .innerHTML.
jsFiddle
old_text = document.getElementById("text").textContent;
var counter = Math.floor(Math.random()*document.getElementById("text").textContent.length);
// or
old_text = document.getElementById("text").innerHTML;
var counter = Math.floor(Math.random()*document.getElementById("text").innerHTML.length);
var all ="ABCDEFGHIJKLMNOPQRSTUVWXYZa{}[];:></?bcdefghijklmnopqrstuvwxyz0123+_)(*&^%$##!~`456789";
var old_text;
function randChar() {
"use strict";
return all.charAt(Math.floor(Math.random()*all.length));
}
function main() {
"use strict";
old_text = document.getElementById("text").innerText;
var $_inter = setInterval(function() {
var text = document.getElementById("text");
text.innerHTML = text.innerHTML.substring(0, 5) + randChar() + text.innerHTML.substring(5);
setTimeout(function(){
text.innerHTML = old_text;
},200);
}, 350);
}
window.onload = main;
Just get rid of flag and counter. Initialize old_text in the onload listener.

Categories

Resources