how to add css in innerText - javascript

I have a function in JavaScript that generates an error message, but I would like to add CSS to it. For example: a yellow background and a red color.
//ciblage
let btn = document.getElementsByClassName("buttons");
let D = document.getElementsByClassName("div_text");
let errorMessage = document.createElement("div");
stringLength = document.getElementById('username');
const regex = /\W/;
errorMessage.id = 'warning';
D[0].appendChild(errorMessage);
stringLength.addEventListener('input', function (evt) {
if (stringLength.value.length > 10) {
document.getElementById('warning').innerText = "le nombre de caractères maximum autorisés est de 10"
btn[0].disabled = true;
}
});

document.getElementById('warning').style.backgroundColor="yellow";
document.getElementById('warning').style.color="red";

JS under let errormessage
errorMessage.classList.add("error");
CSS:
.error {
background-color: yellow;
color: red;
}
Or all in JS
// add css styles to the error message
errorMessage.style.backgroundColor = "yellow";
errorMessage.style.color = "red";

document.getElementById('warning').style.backgroundColor = "yellow";
document.getElementById('warning').style.color = "red";

Related

On image click hide the image and display a div with transition

I'm working on a search bar. First, the user will only be able to see the search icon. When the user clicks on the search icon then that search icon gets replaced with a div that contains a new search bar. I want that when the user click on the search icon the new div with a transition of 1 second in such a way that it looks like the new div was the expanded version of the search icon.
<img src="https://populusww.com.au/wp-content/uploads/2023/01/search.png" id="Search-Collapse" style="cursor: pointer;" onclick="toggle_div_fun();">
<br/><br/>
<script>
function toggle_div_fun() {
debugger;
document.getElementById("Search-Collapse").style.transition = "all 2s";
debugger;
var divelement = document.getElementById("Search-Collapse");
var searchelement =document.getElementById("Search-Expand");
var menusection =document.getElementById("menu-section");
var searchsection =document.getElementById("search-section");
if(divelement.style.display == 'none'){
divelement.style.display = 'block';
searchelement.style.display = 'none';
menusection.style.width = '65%';
searchsection.style.width = '15%';
searchsection.style.marginTop = '30px';
}
else{
divelement.style.display = 'none';
searchelement.style.display = 'block';
menusection.style.width = '65%';
searchsection.style.width = '15%';
searchsection.style.marginTop = '50px';
}
}
</script>
Display did not work with transition, you can use divelement.style.opacity = 0; to hide your div with effect
and do not forget set opacity for initiate set divelement.style.opacity = 1;
something like this:
<img src="https://populusww.com.au/wp-content/uploads/2023/01/search.png" id="Search-Collapse" style="cursor: pointer;" onclick="toggle_div_fun();">
<br/><br/>
<script>
document.onload = () => {
document.getElementById("Search-Expand").style.transition = "all 2s";
document.getElementById("Search-Collapse").style.transition = "all 2s";
document.getElementById("Search-Collapse").style.opacity = 1;
document.getElementById("Search-Expand").style.opacity = 1;
}
function toggle_div_fun() {
var divelement = document.getElementById("Search-Collapse");
var searchelement =document.getElementById("Search-Expand");
var menusection =document.getElementById("menu-section");
var searchsection =document.getElementById("search-section");
if(divelement.style.display == 'none'){
divelement.style.display = 'block';
searchelement.style.display = 'none';
menusection.style.width = '65%';
searchsection.style.width = '15%';
searchsection.style.marginTop = '30px';
}
else{
divelement.style.display = 'none';
searchelement.style.display = 'block';
menusection.style.width = '65%';
searchsection.style.width = '15%';
searchsection.style.marginTop = '50px';
}
}
</script>
You can do that using CSS opacity in JavaScript simple event listener;
Check this detailed code below if you don't understand any things let me know and I'll try to explain it to you :D
HTML:
<img src="https://populusww.com.au/wp-content/uploads/2023/01/search.png" id="Search-Collapse" style="cursor: pointer;">
<br>
<input type="text" id="Search-Input" placeholder="search query" />
CSS:
body {
background: red;
}
img {
width: 50px;
}
JS:
var searchIcon = document.querySelector('img');
var inputSearch = document.getElementById('Search-Input');
inputSearch.style.opacity = 0;
inputSearch.style.transition = "opacity 1s"
searchIcon.addEventListener('click', function(){
if(inputSearch.style.opacity == 0 || inputSearch.style.opacity == ''){
inputSearch.style.opacity = 1;
}
else {
inputSearch.style.opacity = 0;
}
});
and here is a working example on JSFIDDLE

How to create element onclick which removes the element's parent node?

I'm trying to make a box copier that creates boxes which each contain a button to delete itself. Each box is a duplicate of a hidden template box, and each has an id starting at box1:
This is what I have so far:
let boxcount = 0;
function removebox() {
this.parentNode.remove();
}
function addbox() {
var container = document.getElementById("container"),
box = document.getElementById("boxoriginal");
var boxcopy = box.cloneNode(true);
boxcount += 1;
boxcopy.id = "box" + boxcount;
container.appendChild(boxcopy);
var remover = document.createElement("DIV");
remover.innerHTML = "x";
remover.onclick = removebox;
document.getElementById(boxid).appendChild(remover);
}
The problem is that if I click on the X in box1 for instance, it removes the last box just added, rather than box1. I've tried something similar using EventListener but with the same result.
I'm brand new to JS, so I can only guess that I'm misunderstanding how this works.
Maybe not a perfect solution for what you are trying to achieve, but you might want to create a structure more like:
let doc, bod, M, I, SimpleBoxMaker; // for use on other loads
addEventListener('load', ()=>{
doc = document; bod = doc.body; M = tag=>doc.createElement(tag); I = id=>doc.getElementById(id);
SimpleBoxMaker = function(appendTo = bod){
this.container = M('div');
this.addBox = contentNode=>{
const container = this.container, box = M('div'), x_div = M('div');
box.className = 'box_div'; x_div.className = 'x_div'; x_div.innerHTML = '×';
box.appendChild(x_div);
if(contentNode)box.appendChild(contentNode);
x_div.onclick = ()=>{
box.remove();
}
container.appendChild(box);
return this;
}
appendTo.appendChild(this.container);
}
// below code can be put on a separate page using a `load` Event (besides // end load line)
const bigBox = new SimpleBoxMaker, addBox = I('add_box');
addBox.onclick = ()=>{
const div = M('div');
div.textContent = 'Before adding this node there were '+bigBox.container.children.length+' children in the container';
bigBox.addBox(div);
}
}); // end load
*{
box-sizing:border-box:
}
.box_div{
min-height:30px; border:1px solid #000; margin-top:2px;
}
.x_div{
cursor:pointer; display:flex; justify-content:center; align-items:center; width:30px; height:30px; background:#900; color:#fff; font:bold 24px san-serif; text-align:center; float:right;
}
<button id='add_box'>Add Box</div>

How to assign color to Javascript variable and use it throughout the Javascript code

I want to assign the #FFCB03 to a javascript variable and use it.
Below is my code
let btn_all = document.getElementById("btn_all");
let btn_A = document.getElementById("btn_A");
let btn_B = document.getElementById("btn_B");
let btn_C = document.getElementById("btn_C");
btn_A.style.backgroundColor = "red";
let allButtons = [btn_all, btn_A, btn_B, btn_C];
function changeColor(e) {
let currentColor = e.target.style.backgroundColor;
if (currentColor != "red") {
e.target.style.backgroundColor = "red";
}
else {
e.target.style.backgroundColor = "";
}
if (btn_A.style.backgroundColor == "red" && btn_B.style.backgroundColor == "red" && btn_C.style.backgroundColor == "red") {
btn_all.style.backgroundColor = "red";
} else {
btn_all.style.backgroundColor = "";
}
if (btn_A.style.backgroundColor == "" && btn_B.style.backgroundColor == "" && btn_C.style.backgroundColor == "") {
btn_A.style.backgroundColor = "red"
}
}
Instead of use "red" color I want to use this "#FFCB03" color by assign it to a varible. Like this: let bgColor = "#FFCB03"; and replace it in my function, but this make my function not working as when I use "red". Even I replace "#FFCB03" directly to where "red" is, it make my function not working too.
UPDATE
This code is work just like what I want it to. One thing that I want to add to the code is I want to make "red" color to another color just like "#FFCB03". but when I replace the "red" color with this "#FFCB03", it make my code not working as before.
It is very simple to accomplish this. I will use this code as an example.
<div class = "example-container"></div>
<script>
const red = "#FFCB03"; //store desired color in the variable
const div = document.querySelector(".example-div");
div.style.backgroundColor = red; //assign it
tada :)
You could use the code like this:
let red = "#FFCB03";
e.target.style.backgroundColor = red;
and here is the code changed from your code
let btn_all = document.getElementById("btn_all");
let btn_A = document.getElementById("btn_A");
let btn_B = document.getElementById("btn_B");
let btn_C = document.getElementById("btn_C");
let red = "#FFCB03";
btn_A.style.backgroundColor = red;
let allButtons = [btn_all, btn_A, btn_B, btn_C];
function changeColor(e) {
let currentColor = e.target.style.backgroundColor;
if (currentColor != red) {
e.target.style.backgroundColor = red;
}
else {
e.target.style.backgroundColor = "";
}
if (btn_A.style.backgroundColor == red && btn_B.style.backgroundColor == red && btn_C.style.backgroundColor == red) {
btn_all.style.backgroundColor = red;
} else {
btn_all.style.backgroundColor = "";
}
if (btn_A.style.backgroundColor == "" && btn_B.style.backgroundColor == "" && btn_C.style.backgroundColor == "") {
btn_A.style.backgroundColor = red
}
}
Could this code solve your problem?
Create a new file as colors.js or something and store and export the values from there
Multiple modules
export const red = `#FFCB03`;
other files
import { red } from './colors'
btn_A.style.backgroundColor = red
Same Module or file
In case of same file, just declare the variable and use it
<script>
const red = `#FFCB03`;
btn_A.style.backgroundColor = red
</script>

change array element value's style

im building a to-do list but cant figure out how to keep my array values that have line-through decoration.
the moment render method is called, the array is built from the start. means that if i delete an li, all other li that have been marked by the checkbox with a line-through, losing the decoration.
what can i do to keep the line-through ?
i tried so far in the markTask method to replace the original value with the value that have line-through on it but it didn't work.
basically what im trying to accomplish is by inserting the value with line-through, to be able to check if this value have the line-through style and after the render to be able to keep the checked checkboxes as checked.
my code so far:
class Todo {
constructor() {
this.input = document.getElementById("input");
this.ul = document.getElementById("ul");
this.form = document.getElementById("form");
this.tasks = [];
this.registerEvent();
}
registerEvent() {
this.form.addEventListener("submit", (event) => {
event.preventDefault();
this.createTask(this.input.value);
this.form.reset();
});
}
createTask(task) {
if (task.trim().length === 0) {
return;
}
this.tasks.push(task);
this.render();
}
deleteTask(task) {
const myTask = task.target;
const parent = myTask.parentNode;
const taskToRemove = parent.childNodes[1].textContent;
const index = this.tasks.indexOf(taskToRemove);
this.tasks.splice(index, 1);
this.render();
}
markTask(task) {
const myTask = task.target;
const parent = myTask.parentNode;
if (myTask.checked) {
parent.style.textDecoration = "line-through";
} else {
parent.style.textDecoration = "none";
}
}
render() {
this.ul.innerHTML = "";
this.tasks.forEach((task) => {
const li = document.createElement("li");
const cb = document.createElement("input");
cb.type = "checkbox";
cb.addEventListener("click", (e) => {
this.markTask(e);
});
li.appendChild(cb);
li.append(document.createTextNode(task));
const btn = document.createElement("button");
li.appendChild(btn);
btn.textContent = "Delete";
btn.classList.add("remove");
btn.addEventListener("click", (e) => {
this.deleteTask(e);
});
this.ul.appendChild(li);
});
}
}
new Todo();
<form id="form">
<input id="input" />
<button id="add">Add</button>
</form>
<ul id="ul">
</ul>
it's because you're not tracking which tasks are done and you're just pushing strings. for your createTask method you need to push an object with a done property to indicate which tasks have been done like so
createTask(task) {
if (task.trim().length === 0) {
return;
}
this.tasks.push({title: task, done: false});
this.render();
}
update your render to account for tasks already done
render() {
this.ul.innerHTML = "";
this.tasks.forEach((task) => {
const li = document.createElement("li");
const cb = document.createElement("input");
cb.type = "checkbox";
cb.addEventListener("click", (e) => {
this.markTask(e);
});
li.appendChild(cb);
li.append(document.createTextNode(task.title));
const btn = document.createElement("button");
li.appendChild(btn);
btn.textContent = "Delete";
btn.classList.add("remove");
btn.addEventListener("click", (e) => {
this.deleteTask(e);
});
this.ul.appendChild(li);
if (task.done) {
cb.checked = true;
li.style.textDecoration = "line-through";
} else {
cb.checked = false;
li.style.textDecoration = "none";
}
});
}
in your constructor update your tasks variable to see this in effect
constructor() {
this.input = document.getElementById("input");
this.ul = document.getElementById("ul");
this.form = document.getElementById("form");
this.tasks = [{title: 'mill', done: true}, {title: 'jus', done: false}];
this.registerEvent();
}
hope you get the general idea. I won't do the entire implementation on markTask as this should be enough to give you a view of what the solution should be. good luck.
If I may, I have revised your code a bit.
The technique you need is event delegation:
any click on a child element is also a click on its parent elements. we plas the event listener on the parent and we see on which child element it occurred.
In your case, this only makes one event listerner for all your 'remove' buttons.
the other idea is not to ignore the DOM, it also keeps the list of tasks, you don't need to keep them in a table in memory, this is redundant.
here is the code: css is also helfull
class Todo
{
constructor()
{
this.form = document.getElementById('todo-form')
this.liste = document.getElementById('todo-list')
this.form.onsubmit = e => this.addTask(e)
this.liste.onclick = e => this.delTask(e)
}
addTask(e)
{
e.preventDefault()
if (this.form.task.value.trim() === '') return
let li = document.createElement('li')
, cb = document.createElement('input')
, sp = document.createElement('span')
, bt = document.createElement('button')
;
cb.type = 'checkbox'
sp.textContent = this.form.task.value
bt.textContent = 'Delete'
bt.className = 'remove'
li.appendChild(cb)
li.appendChild(sp)
li.appendChild(bt)
this.liste.appendChild(li)
this.form.reset()
}
delTask(e)
{
if (!e.target.matches('button.remove')) return // reject others clicks
e.target.closest('li').remove()
}
}
new Todo();
#todo-list li > span {
display : inline-block;
background-color : whitesmoke;
width : 20em;
}
#todo-list li input[type=checkbox]:checked + span {
text-decoration : line-through;
}
#todo-list li button.remove {
font-size: .6em;
}
<form id="todo-form">
<input name="task">
<button type="submit">Add</button>
</form>
<ul id="todo-list"></ul>
As you can see this code is shorter. You can also use a IIFE unstead of a class, like that :
(function() // IIFE
{
let form = document.getElementById('todo-form')
, liste = document.getElementById('todo-list')
;
form.onsubmit = e => // addTask
{
e.preventDefault()
if (form.task.value.trim() === '') return
let li = document.createElement('li')
, cb = document.createElement('input')
, sp = document.createElement('span')
, bt = document.createElement('button')
;
cb.type = 'checkbox'
sp.textContent = form.task.value
bt.textContent = 'Delete'
bt.className = 'remove'
li.appendChild(cb)
li.appendChild(sp)
li.appendChild(bt)
liste.appendChild(li)
form.reset()
}
liste.onclick = e => // delTask
{
if (!e.target.matches('button.remove')) return // reject others clicks
e.target.closest('li').remove()
}
}
)()
btTaskList.onclick = e =>
{
let tasks = [...document.querySelectorAll('#todo-list li')].map(li=>
{
let val = li.querySelector('span').textContent
, chk = li.querySelector('input[type=checkbox]').checked
;
return {val,chk}
})
console.clear()
console.log( tasks )
}
#todo-list li > span {
display : inline-block;
background-color : whitesmoke;
width : 20em;
}
#todo-list li input[type=checkbox]:checked + span {
text-decoration : line-through;
}
#todo-list li button.remove {
font-size: .6em;
}
<form id="todo-form">
<input name="task">
<button type="submit">Add</button>
</form>
<ul id="todo-list"></ul>
<button id="btTaskList">get task list</button>
I also added a get task list button...
After marking an element you are changing only the stayle and atrribute of element. But after delete you recreate with render whole list and in render you are not rendereing checked parameter.
Your render should be:
render() {
this.ul.innerHTML = "";
this.tasks.forEach((task) => {
const li = document.createElement("li");
const cb = document.createElement("input");
cb.type = "checkbox";
cb.addEventListener("click", (e) => {
this.markTask(e);
});
li.appendChild(cb);
// missed rendering checked
if (task.checked) {
li.style.textDecoration = "line-through";
cb.checked = 'checked';
}
li.append(document.createTextNode(task));
const btn = document.createElement("button");
li.appendChild(btn);
btn.textContent = "Delete";
btn.classList.add("remove");
btn.addEventListener("click", (e) => {
this.deleteTask(e);
});
this.ul.appendChild(li);
});
}

HTML + Javascript Button click again to undo

I was wondering how it is possible to make the button undo something too after clicking it. In my scenario just simple formatting of Text(Color,size etc), when you first click it, it formats the text as described in Javascript, but I would like to add a function, that when you click it again, that it undoes that.
`<script>
function myFunction(){
document.getElementById("demo").style.fontsize="25px";
document.getElementById("demo").style.color="#3AF702";
document.getElementById("demo").style.backgroundcolor="red";
}
</script>`
<button type="change" onclick="myFunction()">Change!</button>
I checked other articles already, which seemed to be related, but I did not get any smarter out of those, so my apologies in advance if it is a dup and thanks for your help!
<script>
var flag = true;
function myFunction(){
let el = document.getElementById("demo");
el.style.fontsize = flag ? "25px" : "";
el.style.color= flag ? "#3AF702" : "";
el.style.backgroundcolor=flag ? "red" : "";
flag = !flag;
}
</script>`
<button type="change" onclick="myFunction()">Change!</button>
The easiest way to do this is to add and remove a class
<style>
.change {
font-size: 25px;
color: #3AF702;
background-color="red"
}
</style>
<script>
var x = 0;
function myFunction() {
if (x == 0) {
document.getElementById("demo").classList.add("change");
x = 1;
} else {
document.getElementById("demo").classList.remove("change");
x = 0;
}
}
</script>
<button type="change" onclick="myFunction()">Change!</button>
Create an object that stores the initial values of your button and a variable which holds the state of it.
var state = 0;
var backup = {};
backup.fontSize = document.getElementById("demo").style.fontsize;
backup.color = document.getElementById("demo").style.color;
backup.background = document.getElementById("demo").style.backgroundcolor;
Now you can easily switch between the backup and the new values like this:
function myFunction() {
if (state == 0) {
document.getElementById("demo").style.fontsize = "25px";
document.getElementById("demo").style.color = "#3AF702";
document.getElementById("demo").style.backgroundcolor = "red";
state = 1;
} else {
document.getElementById("demo").style.fontsize = backup.fontSize;
document.getElementById("demo").style.color = backup.color;
document.getElementById("demo").style.backgroundcolor = backup.background;
state = 0;
}
}
var flag = true;
function myFunction(){
var x = document.getElementById("demo");
if (flag) {
x.style.backgroundColor = "red";
x.style.color="#3AF702";
x.style.fontSize="25px"
} else {
x.style.backgroundColor = "blue";
x.style.color="#dddddd";
x.style.fontSize="10px"
}
flag = !flag
}
function myFunction(){
demo.className = demo.className ? "" : "style"
}
.style {
font-size: 25px;
color: red;
background: blue;
}
<p id="demo">Hi!</p>
<button type="change" onclick="myFunction()">Change!</button>

Categories