Changing colour of the text font - javascript

I am trying to create a text font colour drop down button where it gives you an option of multiple colour to pick from and then it would change the colour of the text. I am not sure on how to approach this and I am not meant to use jQuery. Any help would be appreciated. In the code below it shows other examples of other button where they change the user input entered into the contenteditable. I want the font colour button to do the same but just change the colour of the text
const TAB_KEY = 9;
const ENTER_KEY = 13;
const SHIFT_KEY = 16
const editor = document.querySelector('.editor');
editor.appendChild(document.createElement('li'));
editor.addEventListener('keydown', (e) => {
let code = e.keyCode || e.which;
if (code == TAB_KEY) {
e.preventDefault();
let parent = e.target;
let ul = document.createElement('ul');
let li = document.createElement('li');
ul.appendChild(li);
parent.appendChild(ul);
moveCursorToEnd(li);
} else if (code == ENTER_KEY) {
e.preventDefault();
let parent = e.target;
let li = document.createElement('li');
parent.appendChild(li);
moveCursorToEnd(li);
} else if (code == TAB_KEY * TAB_KEY){
e.preventDefault();
let parent = e.target;
let ol = document.createElement('ol');
let li = document.createElement('li');
ol.appendChild(li);
parent.appendChild(ol);
moveCursorToEnd(li);
}
});
function moveCursorToEnd(el) {
el.focus();
document.execCommand('selectAll', false, null);
document.getSelection().collapseToEnd();
}
/*editor.addEventListener('click', (x) => {
x = document.getElementById("b");
if(x.style.fontWeight == "bolder"){
x.style.fontWeight = "normal";
} else {
x.style.fontWeight = "bolder";
}
});*/
function bold(){
if(document.execCommand("bold")){
document.execCommand("normal");
}else{
document.execCommand("bold");
}
}
/*function underline(){
let x = document.getElementById("text");
if(x.style.textDecoration == "underline"){
x.style.textDecoration = "none";
}else{
x.style.textDecoration = "underline";
}
}*/
function underline(){
if(document.execCommand("underline")){
document.execCommand("none");
}else{
document.execCommand("underline");
}
}
/*Turns the font of the text to Italic*/
function italic(){
if(document.execCommand("italic")){
document.execCommand("normal");
}else{
document.execCommand("italic");
}
}
function highlighSelectedText(){
let sel = window.getSelection().getRangeAt(0);
let selText = sel.extractContents();
let span = document.createElement("span");
span.style.backgroundColor = "yellow";
span.appendChild(selText);
sel.insertNode(span);
}
/*function printPage(){
let printButton = document.getElementById("ul");
printButton.style.visibility = 'hidden';
window.print();
printButton.style.visibility = 'visible';
}*/
body{
margin-top:1em;
margin-bottom: 10em;
margin-right: 1em;
margin-left: 1em;
border: solid;
border-color: #0033cc;
background-color: #f6f6f6;
}
div button{
padding: 1em 2em;
color: white;
background-color: #0000cc;
}
div input{
padding: 1em 2em;
color: white;
background-color: #0000cc;
}
div{
list-style-type:square;
list-style-position: inside;
margin-left: 0.25em;
margin-bottom: 5em;
}
section {
padding: 1em 2em;
color: white;
background-color: #0000cc;
}
.editor {
font-weight: normal;
}
div contenteditable{
margin-bottom: 10em;
}
<!DOCTYPE html>
<meta charset="utf-8">
<body>
<head>
<title>Outliner</title>
<link href="style.css" rel="stylesheet" title="Style">
<div>
<button id="b" onclick="bold()"> B </button>
<button onclick="underline()"> U </button>
<button onclick="italic()"> I </button>
<input type="button" onclick="highlighSelectedText()" value="Highlight"/>
<div id="text" class="editor" contenteditable="true" draggable="true"></div>
</div>
<section>
<input id="saveAs"></input>
<button onclick="saveTextFile()">Download</button>
<input type="file" id="load"/>
<button onclick="loadFile()">Load</button>
</section>
<section>
<button class="btn btn-primary" onclick="saveChanges()">Save Text</button>
<button class="btn btn-warning" onclick="clearStorage()">Reset</button>
</section>
</head>
<script type= "text/javascript" src='setting.js'></script>
</body>

First off we will use a CSS variable. Lets declare a value at :root
:root {
--font-color: #000;
}
Now we will use that value to style the font color of our P tags.
p {
color: var(--font-color);
}
Now when somebody clicks one of the color names, we want to change the value of --font-color. (Notice we are using the data- attribute model to store the color we want to change too).
document.documentElement.style.setProperty('--font-color', target.dataset.color);
And presto we can now change color easily. This works for other values also.
Here is a great article
document.addEventListener('click', ({ target }) => {
if(target.matches('p')) {
document.documentElement.style.setProperty('--font-color', target.dataset.color);
}
});
:root {
--font-color: #000;
}
p {
width: 30%;
border: 2px solid #00000030;
border-radius: 7px;
margin: 0.25rem;
padding: 0.25rem;
color: var(--font-color);
}
<h2>Click a color</h2>
<p data-color="#f00">Red</p>
<p data-color="#0f0">Green</p>
<p data-color="#00f">Blue</p>
<p data-color="#000">Reset</p>

You can manipulate the style variable:
<div id="text">
Choose a color
</div>
<input id="color" type="color">
<button onclick="document.getElementById('text').style.color = document.getElementById('color').value;">Change Color</button>

Related

How to prevent adding another SPAN element?

I'm struggling with a to-do app. I want to cross out a LI element and add a span with an x sign. It's easy by toggling class. However, when I "untoggle" the class by clicking again. The "x" remains and when I click on the item again the "x" is duplicated. How can I prevent adding another "x" or make the "x" disappear when the items is "untoggled".
const addButton = document.querySelector("#add");
const input = document.querySelector("input[name='input-item'");
const ul = document.querySelector("ul");
const allItems = document.querySelectorAll("li");
for (let i = 0; i < allItems.length; i++) {
allItems[i].addEventListener("click", myList);
}
function myList() {
let temp = this.classList.toggle("red");
if (temp) {
let span = document.createElement("span");
span.innerHTML = "×";
span.addEventListener("click", function() {
this.parentElement.remove();
});
this.appendChild(span);
} else if (this.classList.contains("red")) {
this.getElementByTagName("span").remove();
}
}
.red {
text-decoration: line-through;
color: red;
}
span {
background-color: white;
padding: 0 0.3rem;
color: black;
margin: 0 0.2rem;
display: inline-block;
}
<div class="container">
<ul>
<li>banana</li>
<li>orange</li>
<li>grapes</li>
</ul>
<input type="text" name="input-item" placeholder="Enter a new item" /><button id="add">Add Item</button>
</div>

Function not working after push() elements in html file

I want to create a to do list that will add elements typed in <input type="text"> and delete when clicked on button with class .delete. When ever I push elements in an array. And innerHTML it in html page, the delete button stops working. The delete button works for elements that are written into Html code. If someone can help me I will be very thankful.
`
const itemsLIst = document.querySelector('.item-list'); // where we want to add our list
const addText = document.querySelector('.submit'); // add button
let deleteText = document.querySelectorAll('.delete'); // delete button
// const list = JSON.parse(localStorage.getItem('items')) || [];
let list = [];
function addItem(e) {
let text = document.querySelector('.input_bar').value; //text typed in input bar
if (text.length != 0) {
list.push(`<div>
<p>${text}</p>
<button class="delete" onclick='deleteItem'>🗴</button>
<button class="edit">Edit</button>
</div><hr>`);
itemsLIst.innerHTML = list.join('');
text = '0';
document.getElementById("myText").value = "";
} else {
return;
}
}
function deleteItem(e) {
this.parentElement.style.display = 'none';
}
for (var i = 0 ; i < deleteText.length; i++) {
deleteText[i].addEventListener('click', deleteItem);
}
addText.addEventListener('click', addItem);
<style>
body {
width: 100%;
height: 100vh;
background-color: rgb(115, 115, 197);
margin: 0;
padding: 0;
position: relative;
}
.container {
width:50%;
height:70%;
position: absolute;
background-color: rgb(241, 241, 241);
font-family: Arial, Helvetica, sans-serif;
border-bottom-left-radius: 25px;
border-bottom-right-radius: 25px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
overflow-y: scroll;
}
.heading {
width: 100%;
height: 122px;
background-color: #5B45B9;
display: flex;
align-items: center;
justify-content: center;
}
.heading h1 {
color: white;
font-size: 40px;
}
.item-list {
width: 100%;
padding: 0 0 30px 0;
}
.item-list div {
width: auto;
height: 60px;
}
p {
width: 60%;
float: left;
font-size: 25px;
padding-left: 30px;
margin-top: 12px ;
}
.item-list button {
width: 60px;
height: 60px;
font-size: 18px;
float: right;
}
.delete {
font-size: 30px;
color: red;
}
.input_form {
width: 100%;
padding: 30px 0 30px 0;
position: absolute;
bottom: 0;
text-align: center;
}
.input_form .input_bar {
width: 80%;
height: 50px;
font-size: 18px;
border: none;
}
.input_form button {
width: 10%;
height: 50px;
float: right;
margin-right: 30px;
}
</style>
<html>
<head>
</head>
<body>
<div class="container">
<div class="heading">
<h1>TO-DO LIST</h1>
</div>
<div class="item-list">
<div>
<p>TEEXT2</p>
<button class="delete">🗴</button>
<button class="edit">Edit</button>
</div>
<div>
<p>TEEXT1</p>
<button class="delete">🗴</button>
<button class="edit">Edit</button>
</div>
<div>
<p>TEEXT3</p>
<button class="delete">🗴</button>
<button class="edit">Edit</button>
</div>
<div>
<p>TEEXT4</p>
<button class="delete">🗴</button>
<button class="edit">Edit</button>
</div>
</div>
<div class="input_form">
<input type="text" class="input_bar" id="myText" placeholder="Add ITEM">
<button class="submit">+ADD ITEM</button>
</div>
</div>
</body>
</html>
<button class="delete">🗴</button>
<button class="edit">Edit</button>
</div>
<div>
<p>TEEXT1</p>
<button class="delete">🗴</button>
<button class="edit">Edit</button>
</div>
<div>
<p>TEEXT3</p>
<button class="delete">🗴</button>
<button class="edit">Edit</button>
</div>
<div>
<p>TEEXT4</p>
<button class="delete">🗴</button>
<button class="edit">Edit</button>
</div>
</div>
<div class="input_form">
<input type="text" class="input_bar" id="myText" placeholder="Add ITEM">
<button class="submit">+ADD ITEM</button>
</div>
<script src="script.js"></script>
</div>
</body>
</html>`
You actually only trigger DOM "original" delete button (button loaded with your HTML code) with the line :
let deleteText = document.querySelectorAll('.delete'); // delete button
Your others .delete are loaded after the first DOM loading and are not even listed in "deleteText" array !
You have to refresh deleteText every time you add a new item. Something like :
const itemsLIst = document.querySelector('.item-list'); // where we want to add our list
const addText = document.querySelector('.submit'); // add button
let deleteText = document.querySelectorAll('.delete'); // delete button
// const list = JSON.parse(localStorage.getItem('items')) || [];
let list = [];
function addItem(e) {
let text = document.querySelector('.input_bar').value; //text typed in input bar
if (text.length != 0) {
list.push(`<div>
<p>${text}</p>
<button class="delete" onclick='deleteItem'>🗴</button>
<button class="edit">Edit</button>
</div><hr>`);
itemsLIst.innerHTML = list.join('');
text = '0';
document.getElementById("myText").value = "";
} else {
return;
}
}
function deleteItem(e) {
this.parentElement.style.display = 'none';
}
function triggerDeleteButton(){
deleteText = document.querySelectorAll('.delete'); // delete button
for (var i = 0 ; i < deleteText.length; i++) {
deleteText[i].addEventListener('click', deleteItem);
}
}
addText.addEventListener('click', function(){
addItem() ;
triggerDeleteButton() ;
}
);
Without refreshing, you can add and edit data by using local storage
For example, like below, you can try once!
<script>
let customerData = [];
// Inserting new customer record into local storage
function insert() {
let company = document.getElementById("company").value;
let obj = {company};
customerData.push(obj);
synData(customerData);
let customerDetails = JSON.parse(localStorage.getItem("customerString"));
clearFileds();
displayelements(customerDetails);
}
function displayelements(customerDetails) {
let html = "<table id='customer_data' border='1'><tr><th>Sl No</th><th>Company</th><th>Delete</th></tr>";
if(customerDetails == '') {
html+="<tr>No record found!</tr>";
} else {
customerDetails.map((values, index) => {
html+="<tr id='row_data'>";
html+="<td>"+index+"</td>";
html+="<td>"+values.company+"</td>";
html+="<td onclick='deleteRow(" + index + ")'>Delete</td>";
html+="</tr>";
} )
}
html+="</table>";
document.getElementById("display").innerHTML = html;
clearFileds();
}
// Delete the specific customer record from local storage
function deleteRow(deleteKey) {
let customerDetails = JSON.parse(localStorage.getItem("customerString"));
customerDetails.map((values, index) => {
if (index == deleteKey) {
customerDetails.splice(index, 1);
}
})
customerData = customerDetails;
synData(customerDetails);
displayelements(customerDetails);
}
// Clearing the form input field data
function clearFileds() {
document.getElementById("company").value = '';
}
// Updating local storage data
function synData(customerDetails) {
localStorage.setItem('customerString', JSON.stringify(customerDetails));
}
</script>
<html>
<head>
<title>Save</title>
</head>
<script ></script>
<body id="format_background">
<div id="customerAction" >
<h1>Customer data</h1>
<label>Company Name </label>
<input id="company" type="text" />
<button type="button" value="Save&Show" onclick="insert()" id="insert">Save</button>
</div>
<div id="display"></div>
</body>
</html>

.last.removeClass() on recently double clicked element

I have this program that allows the user to edit a div when the user double clicks it. I'm trying to only make the most recent double clicked div have a border. I'm doing this right now with the addClass method, I add the .selceted class with this function:
$(function () {
$("div").dblclick(function (e) {
clickedTD = event.target;
$(clickedTD).find(clickedTD).last.removeClass("selected").addClass("selected");
}
I'm trying to make the last selected div be deleted with this .find(clickedTD).last.removeClass("selected")
So that most recent double clicked div is the only one with the .selected class. But this didn't work and I'm unsure why.
Here is my full code:
var text;
var selectedText;
var blue = document.getElementById("blue");
var blue2 = document.getElementById("blue2");
var elementCounter = 0;
function addElement() {
var classN = event.target.id;
text = document.getElementById("input").value;
// create a new div element and give it a unique id
var newDiv = document.createElement("div");
newDiv.id = 'temp'+elementCounter;
newDiv.classList = "div";
elementCounter++
if (classN == "blue"){
newDiv.classList = "blue"
} else if (classN == "red"){
newDiv.classList = "red"
} else if (classN == "green"){
newDiv.classList = "green"
} else if (classN == "blue2"){
newDiv.classList = "blue2"
}
// and give it some content
var newContent = document.createTextNode(text);
// add the text node to the newly created div
newDiv.appendChild(newContent);
// add the newly created element and its content into the DOM
var currentDiv = document.getElementById("div1");
document.body.insertBefore(newDiv, currentDiv);
$(function() {
var currentlyDragged;
$("div").draggable({
drag: function (e) {
currentlyDragged = e.target.id
selectedText = event.target;
text = $(selectedText).html();
}
});
$(function () {
$("div").dblclick(function (e) {
clickedTD = event.target;
$(clickedTD).find(clickedTD).last.removeClass("selected").addClass("selected");
}
);
});
});
document.getElementById("input").value = " ";
}
#import url('https://fonts.googleapis.com/css2?family=Roboto:wght#300&display=swap');
import { library } from '#fortawesome/fontawesome-svg-core'
import { fas } from '#fortawesome/free-solid-svg-icons'
import { far } from '#fortawesome/free-regular-svg-icons'
import { fab } from '#fortawesome/free-brands-svg-icons'
// Add all icons to the library so you can use it in your page
library.add(fas, far, fab)
h1, body{
font-family: 'Roboto', sans-serif;
}
.selected {
border-style: dashed;
}
div {
text-align: center;
border: 1px solid #d3d3d3;
width: 150px;
height: 30px;
padding: 10px;
cursor: move;
z-index: 10;
background-color: white;
color: blue;
}
divWhite {
text-align: center;
border: 1px solid #d3d3d3;
width: 100px;
padding: 10px;
cursor: move;
z-index: 10;
background-color: white;
color: #fff;
}
.blue {
background: linear-gradient(87deg, #5e72e4 0, #825ee4 100%);
color: white;
}
.red {
background: linear-gradient(87deg, #f5365c 0, #f56036 100%);
color: white;
}
.green {
background: linear-gradient(87deg, #2dce89 0, #2dcecc 100%);
color: white;
}
.blue2 {
background: linear-gradient(87deg, #11cdef 0, #1171ef 100%);
color: white;
}
.white {
background: white;
color: white;
}
button{
font-size: .875rem;
border: none;
border-radius: 3px;
height: 40px;
width: 90px;
text-align: center;
position: relative;
transition: all .15s ease;
letter-spacing: .025em;
text-transform: uppercase;
will-change: transform;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>repl.it</title>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
<link href="style.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body style="font-family: 'Roboto', sans-serif;">
<body id="container">
<header id="inputAssignments">
<h1 id="mulAsi">Input Your Assignments for the week:</h1>
<h1 style="display:none" id="oneAsi">Input Your Assignment:</h1>
<input id="input" type="text" value="text">
<button class="blue" id="blue" onclick="addElement()" >Make it Purple</button>
<button class="red" id="red" onclick="addElement()" >Make it Red</button>
<button class="green" id="green" onclick="addElement()" >Make it Green</button>
<button class="blue2" id="blue2" onclick="addElement()" >Make it Blue</button>
<button style="display:none" id="blue2" onclick="addElement();" >input</button>
<h1 height="30px"></h1>
</header>
</header>
<script src="script.js"></script>
</body>
</html>
What you want is ...
div dbclick
Remove selected class from div (actually... div.selcted)
Add selected class to div what you dbclicked.
input[type=text] change
set input[type=text].value to div.selcted.innerHTML
When you use jQuery event,
there are two ways to get $this
Let me show you how to solve this problem.
Regular Function
$('#elementId').on('click', function(){
//1. Remove selected class from div
$('div.selected').removeClass('selected');
//2. Add selected class to $this
const $this = $(this);
$this.addClass('selected')
});
Arrow Function
$('#elementId').on('click', (_event) => {
//1. Remove selected class from div
$('div.selected').removeClass('selected');
//2. Add selected class to $this
const $this = $(_event.currentTarget); // important!
$this.addClass('selected')
});
Finally, Change event of input[type=text]
I will skip arrow function this time.
$('#someInput').on('change', function(){
const value = $(this).val();
$('div.selcted').html(value);
});
DONE!
I recommend you to set id or class to your HTML DOM.
If you set event to ['div', 'input' ...], you will get side effect
Not use div, input
Use #element001(best) or div.myElement001
bye bye

Dynamically setting background image on Grid cell with JS

The program I am creating is a meme generator. I have a div container set up with display:grid with a few tags inside of that which act as the top and bottom text for the meme. I'm trying to dynamically set the background image for the grid cell using plain vanilla JS. When I attach the link inside the CSS file it works perfectly, but using JS the background-image is never set when i check inside the browser. I put a big arrow so you can see where I am attempting to set the image
const imageLink = document.querySelector('#imageLink');
const topText = document.querySelector('#topText');
const bottomText = document.querySelector('#bottomText');
const memeDiv = document.querySelector('#meme');
//listener for submit
document.addEventListener("submit", function(e) {
e.preventDefault();
//if the user doesn't enter an image, or if they don't enter any text, don't generate the meme when they submit.
if (imageLink.value === "") {
return;
} else if (topText === "" && bottomText === "") {
return;
}
console.log(imageLink.value);
//create elements
var div = document.createElement("div");
//set attribute for div containing our memes
div.setAttribute("id", "meme");
//When the page loads apply the users photo to the background of the grid
window.addEventListener('DOMContentLoaded', function() {
memeDiv.style.backgroundImage = `url(${imageLink.value})`; // < -- -- -
});
//create text and remove button for the memes
const top = document.createElement("p"); //for top text
const bottom = document.createElement("p"); //for bottom text
const removeBtn = document.createElement("input");
//remove button attributes
removeBtn.setAttribute("id", "remove");
removeBtn.setAttribute("type", "image");
removeBtn.setAttribute("height", "200px");
removeBtn.setAttribute("width", "200px");
removeBtn.setAttribute(
"src",
"https://www.freeiconspng.com/uploads/x-png-33.png"
);
//set attributes for text
top.setAttribute("id", "top");
top.innerText = topText.value;
bottom.setAttribute("id", "bottom");
bottom.innerText = bottomText.value;
//put the top and bottom text with the remove button together with the same div
div.appendChild(top);
div.appendChild(bottom);
div.appendChild(removeBtn);
//append to the div
document.querySelector("#memeContainer").appendChild(div);
//reset
imageLink.value = "";
topText.value = "";
bottomText.value = "";
})
document.addEventListener("click", function(e) {
if (e.target.id === "remove") {
e.target.parentElement.remove();
} else {
return;
}
})
* {
margin: 0px;
}
#formContainer {
background-color: blue;
margin-bottom: 5px;
text-align: center;
}
h1 {
text-align: center;
background-color: blue;
margin: 0px;
}
#memeContainer {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-template-rows: repeat(3, 300px);
grid-gap: 5px;
}
#top,
#bottom,
#remove {
position: relative;
display: inline;
}
#top {
left: 225px;
z-index: 1;
font-family: Impact;
font-size: 40px;
/* color:white; */
}
#bottom {
top: 300px;
left: 225px;
z-index: 2;
font-family: Impact;
font-size: 40px;
/* color:white; */
}
#remove {
top: -150px;
left: 180px;
z-index: 3;
/* filter: opacity(1%); */
}
#remove:hover {
z-index: 3;
filter: opacity(25%);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Meme Generator</title>
<link rel="stylesheet" href="app.css">
</head>
<body>
<h1>MEME GENERATOR</h1>
<div id="formContainer">
<form>
<input id="imageLink" type="text" placeholder="please link to an image">
<input id="topText" type="text" placeholder="TOP TEXT">
<input id="bottomText" type="text" placeholder="BOTTOM TEXT">
<button type="submit">submit</button>
</form>
</div>
<div id="memeContainer"></div>
<script src="app.js"></script>
</body>
</html>
The DOMContentLoaded event is only called once whenever all HTML have been loaded. So you are only adding an event listener which never fires and thus nothing happens.
window.addEventListener('DOMContentLoaded', function() {
memeDiv.style.backgroundImage = `url(${imageLink.value})`;
});
Remove the event listener and correct the memeDiv variable name to div and your code will run.
div.style.backgroundImage = `url(${imageLink.value})`;
const imageLink = document.querySelector('#imageLink');
const topText = document.querySelector('#topText');
const bottomText = document.querySelector('#bottomText');
const memeDiv = document.querySelector('#meme');
//listener for submit
document.addEventListener("submit", function(e) {
e.preventDefault();
//if the user doesn't enter an image, or if they don't enter any text, don't generate the meme when they submit.
if (imageLink.value === "") {
return;
} else if (topText.value === "" && bottomText.value === "") {
return;
}
console.log(imageLink.value);
//create elements
var div = document.createElement("div");
//set attribute for div containing our memes
div.setAttribute("id", "meme");
//When the page loads apply the users photo to the background of the grid
div.style.backgroundImage = `url(${imageLink.value})`; // < -- -- -
//create text and remove button for the memes
const top = document.createElement("p"); //for top text
const bottom = document.createElement("p"); //for bottom text
const removeBtn = document.createElement("input");
//remove button attributes
removeBtn.setAttribute("id", "remove");
removeBtn.setAttribute("type", "image");
removeBtn.setAttribute("height", "200px");
removeBtn.setAttribute("width", "200px");
removeBtn.setAttribute(
"src",
"https://www.freeiconspng.com/uploads/x-png-33.png"
);
//set attributes for text
top.setAttribute("id", "top");
top.innerText = topText.value;
bottom.setAttribute("id", "bottom");
bottom.innerText = bottomText.value;
//put the top and bottom text with the remove button together with the same div
div.appendChild(top);
div.appendChild(bottom);
div.appendChild(removeBtn);
//append to the div
document.querySelector("#memeContainer").appendChild(div);
//reset
imageLink.value = "";
topText.value = "";
bottomText.value = "";
})
document.addEventListener("click", function(e) {
if (e.target.id === "remove") {
e.target.parentElement.remove();
} else {
return;
}
})
* {
margin: 0px;
}
#formContainer {
background-color: blue;
margin-bottom: 5px;
text-align: center;
}
h1 {
text-align: center;
background-color: blue;
margin: 0px;
}
#memeContainer {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-template-rows: repeat(3, 300px);
grid-gap: 5px;
}
#top,
#bottom,
#remove {
position: relative;
display: inline;
}
#top {
left: 225px;
z-index: 1;
font-family: Impact;
font-size: 40px;
/* color:white; */
}
#bottom {
top: 300px;
left: 225px;
z-index: 2;
font-family: Impact;
font-size: 40px;
/* color:white; */
}
#remove {
top: -150px;
left: 180px;
z-index: 3;
/* filter: opacity(1%); */
}
#remove:hover {
z-index: 3;
filter: opacity(25%);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Meme Generator</title>
<link rel="stylesheet" href="app.css">
</head>
<body>
<h1>MEME GENERATOR</h1>
<div id="formContainer">
<form>
<input id="imageLink" type="text" placeholder="please link to an image">
<input id="topText" type="text" placeholder="TOP TEXT">
<input id="bottomText" type="text" placeholder="BOTTOM TEXT">
<button type="submit">submit</button>
</form>
</div>
<div id="memeContainer"></div>
<script src="app.js"></script>
</body>
</html>

Detect if another button is pressed

i have a bunch of buttons with the id btn1, btn2 , btn3 etc. and i want to change the background when one button is clicked, for example if btn1 is pressed it gets black but when btn2 is pressed that gets black and btn1 goes back to its original state.
body {
background-color: #fff;
font-size: 62.5%;
}
#background-buttons { text-align: right; }
#background-buttons button {
background-color: #222;
font-family: Roboto Condensed;
color: #fff;
padding: 10px;
outline: none;
border: none;
width: 50px;
height: 50px;
border-radius: 50px;
}
#background-buttons #activated { background-color: #000; }
#background-buttons button:hover { background-color: #555; }
#background-buttons button:active { background-color: #333; }
<div id="background-buttons">
<button id="btn1" onclick="change()">1</button>
<button id="btn2" onclick="change()">2</button>
<button id="btn3" onclick="change()">3</button>
<button id="btn4" onclick="change()">4</button>
<button id="btn5" onclick="change()">5</button>
<button id="btn6" onclick="change()">6</button>
<button id="btn7" onclick="change()">7</button>
<button id="btn8" onclick="change()">8</button>
<button id="btn9" onclick="change()">9</button>
<button id="btn10" onclick="change()">10</button>
</div>
This code on JSFiddle
When a button is clicked loop through all buttons, set their backgroundColor to #222 and set the backgroundColor of the one that was clicked to something else.
Also, in the markup when you call the function change(), pass a parameter this,i.e, change(this).
Updated Fiddle
// el is the button that was clicked
function change(el) {
var all = document.getElementsByTagName('button');
// loop through all buttons
for (i = 0; i < all.length; i++) {
// if the current button is the one that was clicked change its color to 'plum', else '#222'
all[i].style.backgroundColor = all[i] == el ? 'plum' : '#222'
}
}
body {
background-color: #fff;
font-size: 62.5%;
}
#background-buttons {
text-align: right;
}
#background-buttons button {
background-color: #222;
font-family: Roboto Condensed;
color: #fff;
padding: 10px;
outline: none;
border: none;
width: 50px;
height: 50px;
border-radius: 50px;
}
#background-buttons button:hover {
background-color: #555 !important;
}
<div id="background-buttons">
<button id="btn1" onclick="change(this)">1</button>
<button id="btn2" onclick="change(this)">2</button>
<button id="btn3" onclick="change(this)">3</button>
<button id="btn4" onclick="change(this)">4</button>
<button id="btn5" onclick="change(this)">5</button>
<button id="btn6" onclick="change(this)">6</button>
<button id="btn7" onclick="change(this)">7</button>
<button id="btn8" onclick="change(this)">8</button>
<button id="btn9" onclick="change(this)">9</button>
<button id="btn10" onclick="change(this)">10</button>
</div>
Create a CSS class to style the selected button appropriately:
.selectedButton {
background-color: black;
}
Create some library functions to add and remove a class:
var util = {dom:{}};
util.dom.hasClassName = function(el, cName) {
if (typeof el == 'string') el = document.getElementById(el);
var re = new RegExp('(^|\\s+)' + cName + '(\\s+|$)');
return el && re.test(el.className);
}
util.dom.addClassName = function(el, cName) {
if (typeof el == 'string') el = document.getElementById(el);
if (!util.dom.hasClassName(el, cName)) {
el.className = util.trim(el.className + ' ' + cName);
}
}
util.dom.removeClassName = function(el, cName) {
if (typeof el == 'string') el = document.getElementById(el);
if (util.dom.hasClassName(el, cName)) {
var re = new RegExp('(^|\\s+)' + cName + '(\\s+|$)','g');
el.className = util.trim(el.className.replace(re, ''));
}
}
/* Remove leading and trailing whitespace and reduce
** multiple intermediate whitespaces to a single space
*/
util.trim = function(s) {
return s.replace(/(^\s+)|(\s+$)/g,'').replace(/\s+/g,' ');
}
Change the listeners so they passes a reference to the clicked button:
<button id="btn1" onclick="change(this)">1</button>
Now when a button is clicked you can do:
function change(target) {
var el = document.querySelector('button.selectedButton');
if (el) util.dom.removeClassName(el, 'selectedButton');
util.dom.addClassName(target, 'selectedButton');
}
It would be better to put a single listener on a parent element and use the related event's target property to find the button that was clicked. Also, you can remember the last button that the class was added to so you don't have to search for it next time. But that won't work if you are setting a selected button at the server.

Categories

Resources