Im using a javascript function to change color on some icons with dataset.
i cant find out how i can make the color that i change with a click, to stay that way.
this is the javascript function:
window.onload = oppdater;
function oppdater() {
const clickHandler = function () {
this.style.color =
this.style.color != this.dataset.activeColor ?
this.dataset.activeColor :
this.dataset.disabledColor;
};
for (const element of document.querySelectorAll(".active-color-aware")) {
element.onclick = clickHandler;
}
}
<div>
<img src="img/mug_test.png" height="200px" width="200px">
<p>fillifjonka grå</p>
<div id="icon_colors" class="center_icon_text">
<i data-active-color="green" data-disabled-color="#6080a0" class="fas fa-home fa-3x active-color-aware"></i>
<i data-active-color="yellow" data-disabled-color="#6080a0" class="fas fa-grin-hearts fa-3x active-color-aware"></i>
<i data-active-color="red" data-disabled-color="#6080a0" class="fas fa-heart-broken fa-3x active-color-aware"></i>
</div>
</div>
If you want to save the info event after user closes the browser, you can leverage the localstorage
// Save
localStorage.setItem("activeColor", "red");
// Get
var activeColor = localStorage.getItem("activeColor");
Related
I need a setTimeout that add a new class to the icon that you can see in my code, but I don't know how to create the DOM element for
<i class="fa fa-check-double" id='icon'></i>
inputText.addEventListener("keypress", event => {
if (event.key === "Enter") {
event.preventDefault();
chat.innerHTML += `<div class="ballon">
<div>${inputText.value}</div>
<span class="time">
${today.getHours()}:${today.getMinutes()}
<i class="fa fa-check-double" id='qui'></i>
</span>
</div>
`
inputText.value = ''
}
})
I don't know how to create the DOM variable that I need, I'm a newbie of course
this is html
i'm a complete beginner as i started learning js since last two month,
please help me to solve this problem
<h1>Best Song Collection</h1>
<div class="songItem">
<span class="songName">love you zindagi</span>
<span class="btn"><i class="far fa-play-circle playbtn"></i></span>
<span class="btn"><i class="far fa-pause-circle pausebtn"></i></span>
</div>
<div class="songItem">
<span class="songName">love you zindagi</span>
<span class="btn"><i class="far fa-play-circle playbtn"></i></span>
<span class="btn"><i class="far fa-pause-circle pausebtn"></i></span>
</div>
</div>
</div>
js
let pausebtn = document.querySelector(".pausebtn");
let playbtn = document.querySelector(".playbtn")
let btn = document.querySelectorAll(".btn");
function change(element){
if(element.classList==="fa-play-circle"){
element.classList.remove("fa-play-circle");
element.classList.add("fa-pause-circle");
}
}
btn.addEventListner('click',change());
First of all, if you pass a callback function, do not call it. There you need to do it as so btn.addEventListner('click', change);. (Also, there is a typo in addEventListener)
Second of all, I would change the logic of both your HTML and JS. There is no need to keep two spans inside each .songItem div, you can keep only one and just change the class that is responsible for the icon when a user clicks on the button. You will have less code and it will be more readable. Also, you don't need to put a i tag inside a span, you can pass the icons class directly to the span. What is more, it is more convenient to use const instead of let, because you do not intend to change the value of the variables.
You can achieve it by the code written below, I also attach a codepen with a working example.
const pauseIconClassName = 'fa-pause-circle'
const playIconClassName = 'fa-play-circle'
const btns = document.querySelectorAll('.btn')
function onChange (event) {
// get the button elememt from the event
const buttonElement = event.currentTarget
// check if play button class is present on our button
const isPlayButton = buttonElement.classList.contains(playIconClassName)
// if a play button, remove the play button class and add pause button class
if (isPlayButton) {
buttonElement.classList.remove(playIconClassName)
buttonElement.classList.add(pauseIconClassName)
// if a pause button, remove pause button class and add play button class
} else {
buttonElement.classList.remove(pauseIconClassName)
buttonElement.classList.add(playIconClassName)
}
// You can also use .toggle function on classList as mentioned by the person in other answer
}
// query selector all returns a list of nodes, therefore we need to iterate over it and attach an event listener to each button seperatly
btns.forEach(btn => {
btn.addEventListener('click', onChange)
})
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" rel="stylesheet"/>
<h1>Best Song Collection</h1>
<div class="songItem">
<span class="songName">love you zindagi</span>
<span class="btn far fa-play-circle"></span>
</div>
<div class="songItem">
<span class="songName">love you zindagi</span>
<span class="btn far fa-play-circle"></span>
</div>
You probably want to toggle the button so I made an example for that. When you press the play button it will show the pause and when you press the pause button it shows play.
When the button is clicked both fa-play-circle and fa-pause-circle are toggled to alter the button icon when clicked.
You made a few mistakes in your code.
The addEventListner() contains a typo. It should be addEventListener()
You store the result of the change() function (which does not exist since it does not return anything) instead of attaching the function as an event handler. So dont call the function.
Your element variable does not contain an element but the event object so you need to call the target or currentTarget property first.
document.querySelectorAll(".btn").forEach(element => element.addEventListener('click', (event) => {
let iElement = event.currentTarget.querySelector('i');
iElement.classList.toggle("fa-play-circle");
iElement.classList.toggle("fa-pause-circle");
}));
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" rel="stylesheet"/>
<div class="songItem">
<span class="songName">love you zindagi</span>
<span class="btn"><i class="far fa-play-circle playbtn"></i></span>
</div>
<div class="songItem">
<span class="songName">love you zindagi</span>
<span class="btn"><i class="far fa-play-circle playbtn"></i></span>
</div>
pass change to click listener, don't call change function.
btn.addEventListner('click', change);
const pausebtn = document.querySelector(".pausebtn");
const playbtn = document.querySelector(".playbtn");
const btn = document.querySelectorAll(".btn");
function change(element) {
if (element.classList === "fa-play-circle") {
element.classList.remove("fa-play-circle");
element.classList.add("fa-pause-circle");
}
}
btn.addEventListner("click", change);
At first glance, it looks like a syntax issue.
Try to not invoke a function and as args, you should receive an event.
So it will look something like this:
let pausebtn = document.querySelector(".pausebtn");
let playbtn = document.querySelector(".playbtn")
let btn = document.querySelectorAll(".btn");
function change(event){
if(event.target.classList==="fa-play-circle"){
event.target.classList.remove("fa-play-circle");
event.target.classList.add("fa-pause-circle");
}
}
btn.addEventListner('click', change);
EDIT: In HTML you have both buttons for play and pause, you should have just one and change the icon with js toggle.
Semantic tip, use button tag for buttons.
Only first element getting clicked not all, how to get alert on all elements.
Jsfiddle
var btn = document.querySelector(".box i");
btn.onclick = function () {
alert('hello');
}
<div class="box">
<i class="fa fa-address-book-o" aria-hidden="true"></i>
<i class="fa fa-address-book-o" aria-hidden="true"></i>
<i class="fa fa-address-book-o" aria-hidden="true"></i>
<i class="fa fa-address-book-o" aria-hidden="true"></i>
</div>
Try querySelectorAll for select all then attract onclick to all element
var btnlist = document.querySelectorAll(".box i");
btnlist.forEach(element =>{element.onclick = function () {
alert('hello');
}});
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
<div class="box">
<i class="fa fa-address-book-o" aria-hidden="true"></i>
<i class="fa fa-address-book-o" aria-hidden="true"></i>
<i class="fa fa-address-book-o" aria-hidden="true"></i>
<i class="fa fa-address-book-o" aria-hidden="true"></i>
</div>
Despite the title of the question, you don't currently use jQuery in your code. So, I provide 2 solutions:
jQuery:
jQuery('.box i').click(function() {
alert('hello');
});
Pure JS
window.addEventListener('click', function(e) {
// or e.target.classList.contains('fa-address-book-o')
if (e.target.className === 'fa fa-address-book-o') { // Better to add some additional class to identify element, like "fireAlert" for instance.
alert('hello');
}
});
Alternatively, you could select icons with query selector and add individual event listeners to all of them in a loop, but it's bad for performance & generally not considered a good thing to do.
The reason why it only work on the first element is that using .querySelector() method will select only the first element the meet your selector criteria, to be able to select all the elements you have to use .querySelectorAll() which will return a NodeList which can iterate through like this:
var btns = document.querySelectorAll(".box i");
btns.forEach((el, i) => {
el.onclick = function () {
console.log(`Hello! ${i}`);
}
});
<div class="box">
<i class="fa fa-address-book-o" aria-hidden="true">1</i>
<i class="fa fa-address-book-o" aria-hidden="true">2</i>
<i class="fa fa-address-book-o" aria-hidden="true">4</i>
<i class="fa fa-address-book-o" aria-hidden="true">5</i>
</div>
I have a probleme with my code. Now if I click the first element, all elements will become red, if I click second time they will become green. I would like have two independent events for each element with class fa-heart. I will explain better: If I click the first time the first element DOM, only this element will become red, and if I click it second time, it will become green, and so for all the others. I apologize if my request is not clear. Thank you so much for your help.
<script src="https://kit.fontawesome.com/a1d70a0cda.js"></script>
<a onclick="change()"><i class="fas fa-heart"></i></a>
<a onclick="change()"><i class="fas fa-heart"></i></a>
<a onclick="change()"><i class="fas fa-heart"></i></a>
<script>
function change(){
var a = document.querySelectorAll('.fa-heart');
var qty = a.length;
var i = 0;
for(i; i<qty; i++){
if(a[i].style.color !== 'red'){
a[i].style.color = 'red';
}else{
a[i].style.color='green';
}
}
}
</script>
Add an individual listener to each <i> instead, and in the listener, check the current .style of the clicked element to figure out what to assign next:
document.querySelectorAll('.fa-heart').forEach((i) => {
i.addEventListener('click', () => {
i.style.color = i.style.color !== 'red'
? 'red'
: 'green';
});
});
<script src="https://kit.fontawesome.com/a1d70a0cda.js"></script>
<a><i class="fas fa-heart"></i></a>
<a><i class="fas fa-heart"></i></a>
<a><i class="fas fa-heart"></i></a>
Or, with event delegation:
document.addEventListener('click', (e) => {
if (!e.target.matches('.fa-heart')) {
return;
}
e.target.style.color = e.target.style.color !== 'red'
? 'red'
: 'green';
});
console.log('start');
setTimeout(() => {
console.log('adding dynamic elements');
document.body.innerHTML += `<a><i class="fas fa-heart"></i></a>
<a><i class="fas fa-heart"></i></a>
<a><i class="fas fa-heart"></i></a>`;
}, 1000);
<script src="https://kit.fontawesome.com/a1d70a0cda.js"></script>
If you must use inline handlers (which you shouldn't), pass the this (the clicked element) to the listener:
function change(i) {
i.style.color = i.style.color !== 'red'
? 'red'
: 'green';
}
<script src="https://kit.fontawesome.com/a1d70a0cda.js"></script>
<a onclick="change(this)"><i class="fas fa-heart"></i></a>
<a onclick="change(this)"><i class="fas fa-heart"></i></a>
<a onclick="change(this)"><i class="fas fa-heart"></i></a>
Here you go. This will change the clicked one to green and others to red.
function change(clicked) {
document.querySelectorAll('a').forEach(el => el.setAttribute("style", "color:red"));
clicked.style.cssText ="color:green;";
}
<script src="https://kit.fontawesome.com/a1d70a0cda.js"></script>
<a onclick="change(this)"><i class="fas fa-heart"></i></a>
<a onclick="change(this)"><i class="fas fa-heart"></i></a>
<a onclick="change(this)"><i class="fas fa-heart"></i></a>
I am just wondering about how can I emulate an ENTER key clicking a button. It is designed as this image, as it is an input field, its working with the enterkey and its inserting the text correctly.
But the button designed has to work as if the "enter" key has been pressed.
For example:
Text: "Hi there"+ENTER KEY --> WORKS WELL;
Text: "Hi there"+ Click button as ENTER KEY PRESSED --> I dont know how to implement it.
The code is the below:
<div class="message-input">
<input name="message" id="textEle" placeholder="Escribe aquí...">
<button class="sendMsg">
<span id="sendBtn" class="fa-stack fa-2x visible-xs">
<i class="fa fa-circle fa-stack-2x" style="color:#0f2638"></i>
<i class="fa fa-paper-plane-o fa-stack-1x fa-inverse"></i>
</span>
</button>
</div>
I have already the following javascript code, where is cheking every single input key and when its the ENTER one it makes the insert action:
Template.channel.events({
'keyup [name="message"]' ( event, template ) {
handleMessageInsert( event, template );
}
}
Please let me know if there is any way to do it.
Thanks a lot!
So with native JS:
// buttonEle would be your button, textEle would be your text input
buttonEle.addEventListener('click', function (e) {
var event = document.createEvent('KeyBoardEvent');
event.initEvent('keypress', true, false);
event.key = 'Enter';
event.keyCode = 13;
// now dispatch the event from whichever element your other listener is bound on im gonna assume this is the text input
textEle.dispatchEvent(event);
});
Or with jquery
$(buttonEle).on('click', function (e) {
var event = jQuery.event('keypress', {'keyCode': 13, 'key': 'Enter'});
$(textEle).trigger(event);
});
#prodigitalson's answer in the meteor way:
template.html
<template name = "magic">
...
...
<div class="message-input">
<input name="message" placeholder="Escribe aquí...">
<button class="sendMsg">
<span id="sendBtn" class="fa-stack fa-2x visible-xs">
<i class="fa fa-circle fa-stack-2x" style="color:#0f2638"></i>
<i class="fa fa-paper-plane-o fa-stack-1x fa-inverse"></i>
</span>
</button>
...
...
</template>
template.js
Template.magic.events({
// when you click the button
'click .sendMsg' (event){
event.preventDefault();
// same #prodigitalson's code
var e = jQuery.Event("keypress");
e.which = '13';
$(textEle).trigger(e);
}
});
Edit : Check out this answer for simulating a keypress.