I am writing copy button for code-blocks, but the button can not handle "copy" event.
The buttons are created with createElement method, and event added to the buttons with addEventListener to the buttons, before appending to the blocks, through foreach loop.
JSFiddle Link of the blocks
Create Button code:
const textspan = document.createElement("SPAN");
const bgbutton = document.createElement("BUTTON");
bgbutton.classList.add("btnCopy", "badge");
bgbutton.innerText = "copy";
bgbutton.addEventListener('click', copytextHandle);
textspan.appendChild(bgbutton);
const codeSyn = document.querySelectorAll("pre");
codeSyn.forEach(function(el) {
el.insertAdjacentElement('afterbegin', textspan);
})
In my text, I have three blocks, but only one button is visible(last), first two blocks has no button.
Also, the click event, and functionality can not implemented with click hook. The problem is straight about, click event, please mention which causing the error.
window.addEventListener('load', function() {
var y = document.querySelectorAll("pre code");
for(var i = 0; i < y.length; i++) {
y[i].innerHTML = y[i].innerHTML.replace(/^\r?\n/, "");
}
const textspan = document.createElement("SPAN");
const bgbutton = document.createElement("BUTTON");
bgbutton.classList.add("btnCopy", "badge");
bgbutton.innerText = "copy";
bgbutton.addEventListener('click', copytextHandle);
textspan.appendChild(bgbutton);
const codeSyn = document.querySelectorAll("pre");
codeSyn.forEach(function(el) {
el.insertAdjacentElement('afterbegin', textspan);
})
})
const copytextHandle = (e) => {
const codeBlock = document.querySelectorAll(".hljs-ln")[e.target.dataset.idx];
const text = codeBlock
.innerText
.trim()
.replace(/\s+/g, " ")
.replace(/}/g, "}\n")
.replace(/{ /g, "{\n ")
.replace(/;/g, ";\n ")
copySuccess.classList.remove('hide');
navigator.clipboard.writeText(text).then(() => setTimeout(() => bgbutton.innerHTML("Copied"),200),
(e) => {
console.log('Error writing to the clipboard', e.message);
copySuccess.classList.add('hide');
}
);
};
span > button.btnCopy {
position: absolute;
right: 0;
margin-top: 0.6rem;
}
pre {
position: relative;
}
.btnCopy{border:none; background-color: #e8e8e8;}
/*background-color:a5a5a5, 9c9c9c*/
.btnCopy:hover{background-color: #585858}
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Testing HighlightJS</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta2/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.6.0/styles/routeros.min.css">
</head>
<body>
<h3>Testing HighlightJS Multiple blocks</h3>
<h4>First Code block</h4>
<pre><code class="language-css">
.class{
font-size: 0.85rem;
font-weight: 600;
font-family: monospace;
}
h1 .header{
font-size: 1.5rem;;
font-family: Arial;
}
</code></pre>
<h4>Second Code block</h4>
<pre><code class="language-css">
.class{
font-size: 0.85rem;
font-weight: 600;
font-family: monospace;
}
h1 .header{
font-size: 1.5rem;;
font-family: Arial;
}
</code></pre>
<h4>Third Code block</h4>
<pre><code class="language-css">
.class{
font-size: 0.85rem;
font-weight: 600;
font-family: monospace;
}
h1 .header{
font-size: 1.5rem;;
font-family: Arial;
}
</code></pre>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta2/dist/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.6.0/highlight.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.6.0/languages/css.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlightjs-line-numbers.js/2.6.0/highlightjs-line-numbers.min.js"></script>
<script>hljs.highlightAll(); hljs.initLineNumbersOnLoad();</script>
</body>
</html>
After clicking the button copy you can get to a <table> element which is inside one of your <code> elements with this code:
const codeBlock = e.target.parentNode.nextSibling.children[0];
Once that is applied, the text within <code> gets copied to the variable text which we can see by running the code below and checking the console output.
The copy buttons now appear on all <code> blocks. I've added the code to create the button and span inside the codeSyn.forEach(function(el) { ... }, so that new elements are created for every <pre> that you are iterating through.
Another problem that arises is:
Uncaught ReferenceError: copySuccess is not defined
To resolve this error you should assign an HTML element that has class hide to the variable copySuccess so that this works:
copySuccess.classList.remove('hide');
Check the below code:
window.addEventListener('load', function() {
var copySuccess = document.getElementById("copySuccess");
var y = document.querySelectorAll("pre code");
for(var i = 0; i < y.length; i++) {
y[i].innerHTML = y[i].innerHTML.replace(/^\r?\n/, "");
}
const codeSyn = document.querySelectorAll("pre");
codeSyn.forEach(function(el) {
const textspan = document.createElement("SPAN");
const bgbutton = document.createElement("BUTTON");
bgbutton.classList.add("btnCopy", "badge");
bgbutton.innerText = "copy";
bgbutton.addEventListener('click', copytextHandle);
textspan.appendChild(bgbutton);
el.insertAdjacentElement('afterbegin', textspan);
})
})
const copytextHandle = (e) => {
const codeBlock = e.target.parentNode.nextSibling.children[0];
const text = codeBlock
.innerText
.trim()
.replace(/\s+/g, " ")
.replace(/}/g, "}\n")
.replace(/{ /g, "{\n ")
.replace(/;/g, ";\n ");
navigator.clipboard.writeText(text).then(() => setTimeout(() => e.target.innerHTML = "copied",2000),
(e) => {
console.log('Error writing to the clipboard', e.message);
}
);
};
span > button.btnCopy {
position: absolute;
right: 0;
margin-top: 0.6rem;
}
pre {
position: relative;
}
.hide {
display: none;
}
.btnCopy{border:none; background-color: #e8e8e8;}
/*background-color:a5a5a5, 9c9c9c*/
.btnCopy:hover{background-color: #585858}
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Testing HighlightJS</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta2/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.6.0/styles/routeros.min.css">
</head>
<body>
<h3>Testing HighlightJS Multiple blocks <span id="copySuccess" class="hide">Copied...</span></h3>
<h4>First Code block</h4>
<pre><code class="language-css">
.class{
font-size: 0.85rem;
font-weight: 600;
font-family: monospace;
}
h1 .header{
font-size: 1.5rem;
font-family: Arial;
}
</code></pre>
<h4>Second Code block</h4>
<pre><code class="language-css">
.class{
font-size: 0.85rem;
font-weight: 600;
font-family: monospace;
}
h1 .header{
font-size: 1.5rem;
font-family: Arial;
}
</code></pre>
<h4>Third Code block</h4>
<pre><code class="language-css">
.class{
font-size: 0.85rem;
font-weight: 600;
font-family: monospace;
}
h1 .header{
font-size: 1.5rem;
font-family: Arial;
}
</code></pre>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta2/dist/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.6.0/highlight.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.6.0/languages/css.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlightjs-line-numbers.js/2.6.0/highlightjs-line-numbers.min.js"></script>
<script>hljs.highlightAll(); hljs.initLineNumbersOnLoad();</script>
</body>
</html>
What is happeninig is you're moving the same button in a loop all the way to last pre. Use eg. cloneNode to make a new button per pre element.
simple move scenario (https://jsfiddle.net/jtg6fczd/)
document.querySelector("div").append(button) // adds button to div
document.body.append(button) // moves button out of div
Related
Hello lately i've been working with APIs to get the hang of them through the usual weather app project BUT i'm pretty much still a beginner in javascript and i was wondering how to add a background image that matches the weather report of the city selected by the user.
I wanted to create many classes in css, each called like the weather (ex: .clear, .clouds,.rain etc...) and then use a classList.add() method to change it each time depending on the openWeatherMap data. I tried adding something like document.getElementsByTagName("body")[0].classList.add(weatherValue); inside the .then promise but it doesn't work. Can somebody help me? If there's a much simpler way i'd like to hear about it too :) Thank you so much
var button = document.querySelector(".button");
var inputValue = document.querySelector(".inputValue");
var cityName = document.querySelector(".name");
var weather = document.querySelector(".weather");
var desc = document.querySelector(".desc");
var temp = document.querySelector(".temp");
var humi = document.querySelector(".humi");
button.addEventListener("click", function() {
fetch("https://api.openweathermap.org/data/2.5/weather?q="+inputValue.value+"&appid={myapikey}")
.then(response => response.json())
.then(data => {
var nameValue = data['name'];
var weatherValue = data['weather'][0]['main'];
var tempValue = data['main']['temp'];
var descValue = data['weather'][0]['description'];
var humiValue = data['main']['humidity'];
cityName.innerHTML = nameValue;
weather.innerHTML = weatherValue; // this gives "clear" "clouds" etc to <p> element
desc.innerHTML = descValue;
temp.innerHTML = "Temperature: " + tempValue;
humi.innerHTML = "Humidity: " + humiValue;
})
.catch(err => alert("Wrong city name!"))
})
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: "Nunito", sans-serif;
background-repeat: no-repeat;
background-size: cover;
}
.input {
text-align: center;
margin: 100px 0;
}
input[type="text"] {
height: 50px;
width: 600px;
background: #e7e7e7;
font-family: "Nunito", sans-serif;
font-weight: bold;
font-size: 20px;
border: none;
border-radius: 2px;
padding: 10px 10px;
}
input[type="submit"] {
height: 50px;
width: 100px;
background: #e7e7e7;
font-family: "Nunito", sans-serif;
font-weight: bold;
font-size: 20px;
border: none;
border-radius: 2px;
}
.display {
text-align: center;
}
.clear {
/* background image here */
}
.clouds {
/* another background image here */
}
<!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>Document</title>
<link rel="stylesheet" href="weather_app.css">
</head>
<body>
<div class="input">
<input type="text" class="inputValue" placeholder="Enter a city">
<input type="submit" value="Submit" class="button">
</div>
<div class="display">
<h1 class="name"></h1>
<p class="weather"></p>
<p class="desc"></p>
<p class="temp"></p>
<p class="humi"></p>
</div>
<script src= "weather_app.js"></script>
</body>
</html>
I did a project like this not long ago, https://github.com/Kroplewski-M/Weather-App , I used the openWeater API. I did this:
function setBackground(weather) {
if (weather == "Rain") {
background.src = "./resources/rainy-weather.jpg";
} else if (weather == "Snow") {
background.src = "./resources/snowy-weather.jpg";
} else if (weather == "Clear") {
background.src = "./resources/sunny-weather.jpg";
} else if (weather == "Clouds") {
background.src = "./resources/cloudy-weather.jpg";
}
}
The openWeather API returns what condition the weather is so you can just if statement on what the condition is and set the background accordingly
I am trying to add a space between the line item text when added and the remove button in a to-do-list. JavaScript has the remove button appearing next to each line item when they are added. I don't know how to add a space between the item added and the remove button for better appearance. Also, what additional changes, if any, would you make to streamline this code and to-do-list functionality. Thanks
var button = document.getElementById("enter");
var input = document.getElementById("userinput");
var ul = document.querySelector("ul");
var list = document.querySelectorAll('ul>li');
function inputLength() {
return input.value.length;
}
function createListElement() {
var li = document.createElement("li");
li.appendChild(document.createTextNode(input.value));
ul.appendChild(li);
input.value = "";
// Delete Button
var deleteButton = document.createElement("button");
deleteButton.setAttribute("class", "btn")
deleteButton.appendChild(document.createTextNode(" Remove "));
ul>li.appendChild(deleteButton).addEventListener("click", removeItem);
// Strike-through
ul.appendChild(li).addEventListener("click", toggleList);
}
function addListAfterClick() {
if (inputLength() > 0) {
createListElement();
}
}
function addListAfterKeypress(event) {
if (inputLength() > 0 && event.keyCode === 13) {
createListElement();
}
}
function removeItem() {
this.parentNode.remove();
}
function toggleList () {
this.classList.toggle("done");
}
button.addEventListener("click", addListAfterClick);
input.addEventListener("keypress", addListAfterKeypress);
// If you click on the list item, it toggles the .done class on and off.
// Add buttons next to each list item to delete the item when clicked on
// its corresponding delete button.
// BONUS: When adding a new list item, it automatically adds the delete
// button next to it (hint: be sure to check if new items are clickable too!)
body {
font-family: 'Permanent Marker', cursive;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
background-color: #f5d020;
background-image: linear-gradient(180deg, #f5d020 0%, #f53803 74%);
background-attachment: fixed;
}
.done {
text-decoration: line-through;
}
h1 {
font-size: 40px;
}
p {
font-size: 30px;
}
input {
font-size: 25px;
font-family: 'Permanent Marker', cursive;
}
button {
font-size: 15px;
font-family: 'Permanent Marker', cursive;
}
ul {
font-size: 25px;
cursor: pointer;
display: flex;
flex-direction: column;
}
<!DOCTYPE html>
<html>
<head>
<title>Javascript + DOM</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Permanent+Marker&display=swap" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h1>Shopping List</h1>
<p id="first">Get it done today !</p>
<input id="userinput" type="text" placeholder="enter items">
<button id="enter">Enter</button>
<ul>
</ul>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
Just add margin property in css to button element inside li.
li button { margin-left:5px;}
that's it.
var button = document.getElementById("enter");
var input = document.getElementById("userinput");
var ul = document.querySelector("ul");
var list = document.querySelectorAll('ul>li');
function inputLength() {
return input.value.length;
}
function createListElement() {
var li = document.createElement("li");
li.appendChild(document.createTextNode(input.value));
ul.appendChild(li);
input.value = "";
// Delete Button
var deleteButton = document.createElement("button");
deleteButton.setAttribute("class", "btn")
deleteButton.appendChild(document.createTextNode(" Remove "));
ul>li.appendChild(deleteButton).addEventListener("click", removeItem);
// Strike-through
ul.appendChild(li).addEventListener("click", toggleList);
}
function addListAfterClick() {
if (inputLength() > 0) {
createListElement();
}
}
function addListAfterKeypress(event) {
if (inputLength() > 0 && event.keyCode === 13) {
createListElement();
}
}
function removeItem() {
this.parentNode.remove();
}
function toggleList () {
this.classList.toggle("done");
}
button.addEventListener("click", addListAfterClick);
input.addEventListener("keypress", addListAfterKeypress);
// If you click on the list item, it toggles the .done class on and off.
// Add buttons next to each list item to delete the item when clicked on
// its corresponding delete button.
// BONUS: When adding a new list item, it automatically adds the delete
// button next to it (hint: be sure to check if new items are clickable too!)
body {
font-family: 'Permanent Marker', cursive;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
background-color: #f5d020;
background-image: linear-gradient(180deg, #f5d020 0%, #f53803 74%);
background-attachment: fixed;
}
.done {
text-decoration: line-through;
}
h1 {
font-size: 40px;
}
p {
font-size: 30px;
}
input {
font-size: 25px;
font-family: 'Permanent Marker', cursive;
}
button {
font-size: 15px;
font-family: 'Permanent Marker', cursive;
}
li button {
margin-left:5px;
}
ul {
font-size: 25px;
cursor: pointer;
display: flex;
flex-direction: column;
}
<!DOCTYPE html>
<html>
<head>
<title>Javascript + DOM</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Permanent+Marker&display=swap" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h1>Shopping List</h1>
<p id="first">Get it done today !</p>
<input id="userinput" type="text" placeholder="enter items">
<button id="enter">Enter</button>
<ul>
</ul>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
Looks like you can just add
.btn { margin-left: 5px; }
to your css.
As to how to improve the code, here is the pattern I use to generate html with javascript.
const outputElem = document.querySelector('#output');
let html = '';
html += '<ul>';
for (let i = 0; i < 3; i++) {
html += '<li>';
html += 'item ' + i;
html += '</li>';
}
html += '</ul>';
outputElem.innerHTML = html;
<div id="output"></div>
This can be used to replace
// Delete Button
var deleteButton = document.createElement("button");
deleteButton.setAttribute("class", "btn")
deleteButton.appendChild(document.createTextNode(" Remove "));
li.appendChild(deleteButton).addEventListener("click", removeItem);
with
let html = '';
html += '<button class="btn">';
html += ' Remove ';
html += '</button>';
li.innerHTML += html;
li.querySelector('.btn:last-child').addEventListener('click' removeItem);
I am pretty new to web development and I am making this little project that consists in a little site that allows a user to add and remove their goals(kinda like a to do list)
I want to implement a last feature that allows the browser to save the content of the page, so that if the user reloads the page, he/she does not lose track of their goals. I tried using local storage but it's not working.
Any suggestion/tips on how to tackle such problem?
Thank you very much and I apologise, in advance for the code smell.
var i = 0
var j =0
var parentElement = document.getElementById('new-goals')
function addGoal(){
var userGoal = window.prompt('Enter goal: ')
var divTag = document.createElement('div')
divTag.className = 'goalsSection'
divTag.id = 'goal- ' + i
i++
var goal = document.createElement('p')
goal.innerHTML = userGoal
goal.className= 'usergoal'
goal.id = 'UserGoal'+j
var del = document.createElement('button')
del.className = 'deleteButton'
del.innerHTML = 'Delete Goal'
del.id = j
var com = document.createElement('button')
com.className = 'completedButton'
com.innerHTML = 'Not Completed'
com.id = j
j++
com.onclick = function(e){
if (com.innerHTML == 'Not Completed' ){
var dec = window.prompt('Are you sure? this action can not be undo type y/n')
if (dec == 'y'){
com.innerHTML = 'Completed'
var ele = e.target.id
var fin = 'UserGoal'+ele
document.getElementById(fin).style.textDecoration='line-through'
}
}
}
divTag.appendChild(goal)
divTag.appendChild(del)
divTag.appendChild(com)
parentElement.appendChild(divTag)
del.onclick = function(e){
var id_toDelete = e.target.id
var id_section = 'goal- ' + id_toDelete
alert(id_section)
parentElement.removeChild(divTag)
}
}
body{
background-color: #003f5c;
}
h1{
display: flex;
justify-content: center;
font-size: 60px;
font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
}
.btnConatiner{
display: flex;
justify-content: center;
align-items: center;
margin-bottom: 40px;
}
#newGoalBtn{
display: flex;
justify-content: center;
align-items: center;
width: 200px;
height: 50px;
font-size: 30px;
border-radius: 15px;
border: solid 5px black;
cursor: pointer;
}
.goalsSection{
border: solid 6px white;
width: 200px;
height: 100px;
border-radius: 20px;
background-color: white;
margin: 10px;
float: left;
}
.usergoal{
text-align: center;
font-size:20px;
}
.deleteButton{
cursor: pointer;
}
.completedButton{
cursor: pointer;
}
<!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">
<link rel="stylesheet" href="style.css">
<title>Goal Tracker</title>
</head>
<body>
<h1>Goal Tracker</h1>
<div class="btnConatiner">
<button id="newGoalBtn" onclick="addGoal()">New Goal</button>
</div>
<section class="add-goals">
<div id="new-goals">
</div>
</section>
<script src="app.js"></script>
</body>
</html>
Inside the function addGoal, you can get all the goals that are already on the localstorage, and then push a new goal into the array and store.
// const goals = localStorage.getItem("goals") || []; // you can declare here too.
function addGoal() {
const goals = localStorage.getItem("goals") || [];
const userGoal = window.prompt("Enter goal:")
goals.push(userGoal)
localStorage.setItem('goals', JSON.stringify(goals)) // you need to transform into string
...
And then you can create a function to render the goals that are on the localstorage, like:
function renderGoals() {
const goals = JSON.parse(localStorage.getItem("goals")); // parsing back
// Then you can iterate on these goals (forEach for example) to render.
...
}
You can use localStorage, but not to store all the HTML you're creating, rather to store the essential data. And from that data, you can easily rebuild your html.
First keep track of your data, and set up your addGoal function to accept an argument for the rebuilding (after page refresh)
let userGoals = [] // leave this empty for the moment
function addGoal(userGoal){
if (!userGoal) { // this is a new one, so we'll store it in the array and localStorage
userGoal = window.prompt('Enter goal: ')
userGoals.push(userGoal);
localStorage.setItem('userGoals', JSON.stringify(userGoals)); // localStorage stores everything as strings so we stringify it
}
//... the rest of this function
Then at the bottom of your script, create a window.onload function that runs once, when the page first loads. If there is data in localStorage, this will create your User Goals list
window.onload = function() { // this runs after the page has loaded
if (localStorage.getItem('userGoals') ) { // if we have localStorage values waiting for us, parse them and iterate through them
JSON.parse(localStorage.getItem('userGoals')).forEach(goal => {
userGoals.push(goal)
addGoal(goal)
});
}
}
...
I'm trying to make a background change dynamically using Javascript using event listeners that are listening to "input" on input type="color" fields.
When I click on the color input fields after I choose a color from the pallet, the background color changes properly. But, I'd like the background to change dynamically as the user scrolls the pallet, and not only when he chooses the final color. Hope I was clear, and thanks in advance!
/* Variables Caching */
var h3 = document.querySelector("h3");
var input_left = document.querySelector("#color_selector_1");
var input_right = document.querySelector("#color_selector_2");
/* Function Declerations */
function colorChange()
{
// edit body style accordingally
var newStyle = changeBodyStyle();
// edit h3
editH3(newStyle);
}
function editH3(new_body_style)
{
h3.textContent = "";
h3.textContent = new_body_style;
}
function changeBodyStyle()
{
var new_background = "linear-gradient(to right, " + input_left.value.toString() + ", " + input_right.value.toString() + ")";
document.body.style.background = new_background;
return new_background;
}
/* Adding Event Listeners */
input_left.addEventListener("input", colorChange);
input_right.addEventListener("input", colorChange);
body{
font: 'Raleway', sans-serif;
color: rgba(0,0,0,.5);
text-align: center;
text-transform: uppercase;
letter-spacing: .5em;
top: 15%;
background: linear-gradient(to right, red, yellow);
}
h1{
font: 600 3.5em 'Raleway' , sans-serif;
color: rgba(0,0,0,.5);
text-align: center;
text-transform: uppercase;
letter-spacing: .5em;
width: 100%;
}
h3 {
font: 900 1em 'Raleway' , sans-serif;
color: rgba(0,0,0,0.5);
text-align: center;
text-transform: none;
letter-spacing: 0.01em;
}
<!DOCTYPE html>
<html>
<head>
<title>Gradient Background</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h1>Background Generator</h1>
<h2>Current CSS Background</h2>
<h3>
<h4>this is a test</h4>
</h3>
<input type="color" id="color_selector_1" value="#00ff00">
<input type="color" id="color_selector_2" value="#ff0000">
<!-- JavaScript -->
<script type="text/javascript" src="script.js">
</script>
</body>
</html>
You'll need to build your own color picker, or use a third-party one, rather than relying on the one built in to the browser. The one built in to the browser doesn't communicate the user's choice back to the page until the user clicks OK, so it's impossible to do what you want with it.
My code knowledge is very limited, comes from CodeHS and Codecademy so bear with me.
So I am trying to make a list of numbers, that can be deleted on click. So far so good with the number list, but I still can't figure how to remove them when I click the div box.
I know theres JSFiddle, but I think this is best I could do:
http://www.codecademy.com/rfabrega/codebits/xZ61aJ
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=203">
<title>Lista Mundial</title>
<style>
.divContainer {
width: 35px;
height: 25px;
border: solid 1px #c0c0c0;
background-color: #e1e1e1;
font-family: verdana;
color: #000;
float: left;
}
.text {
font-size: 15px;
font-family: verdana;
color: black;
margin-top: 4px;
}
</style>
</head>
<body>
<script type="text/javascript">
for(var i = 1; i <= 639; i++){
var divTag = document.createElement("div");
divTag.id = i;
divTag.className = "divContainer";
document.body.appendChild(divTag);
var pTg = document.createElement("p");
pTg.setAttribute("align", "center");
pTg.className = "text";
pTg.innerHTML = (i);
document.getElementById(i).appendChild(pTg);
}
</script>
</body>
</html>
you have to create a function on click that deletes the target div tag:
so in your code, after creating the div element. insert this:
divTag.onclick = function(){this.parentNode.removeChild(this)};
$(document).ready(function(){
$('p').hide();
$("body").on("click",".divContainer",function(){
$(this).remove();
});
});