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
Related
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.
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");
I'm trying to change an existing element on click but I'm struggling to find the logic (very new to this)
I'm trying to switch the below span innerHTM on click. I have "minus" when the filter is not click and I want to add a plus when it is active, see below:
<section class="section-center" id="products-filter">
<div class="products">
<h1>SHOP THE <br />FLAVOURS</h1>
</div>
<button class="toggle-filter" id="toggle-category-filters">
filter
<span id="filter-btn-span"><i class="far fa-minus-square"></i></span>
</button>
</section>
JS:
const toggleFilterBt = document.getElementById('toggle-category-filters');
const categoriesHolder = document.getElementById('categories-holder');
const filterText = document.getElementById('filter-btn-span');
toggleFilterBt.addEventListener('click', () => {
categoriesHolder.classList.toggle('categories-show');
filterText.innerHTML = '<i class="far fa-plus-square"></i>';
});
When clicked the button does change to the plus sign, but how do I make it go back to minus when the button is clicked again?
You can check element classList
toggleFilterBt.addEventListener('click', () => {
categoriesHolder.classList.toggle('categories-show');
filterText.innerHTML = categoriesHolder.classList.contains('categories-show') ? '<i class="far fa-plus-square"></i>' : '<i class="far fa-minus-square"></i>';
});
$(".filter-btn-span").html('<i class="...."></i>');
is how i did it with jQuery (you put it in your event listener) and fill the i class with the one you want)
Add an id to your icon.
Get the icon element by id.
Add and remove between icon classes by checking that icon's class.
Here is the working example:
const toggleFilterBt = document.getElementById('toggle-category-filters');
const toggleIcon = document.getElementById('toggleIcon');
toggleFilterBt.addEventListener('click', () => {
if (toggleIcon.classList.contains('fa-minus-square')) {
toggleIcon.classList.remove('fa-minus-square');
toggleIcon.classList.add('fa-plus-square');
} else {
toggleIcon.classList.remove('fa-plus-square');
toggleIcon.classList.add('fa-minus-square');
}
});
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css"
integrity="sha512-+4zCK9k+qNFUR5X+cKL9EIR+ZOhtIloNl9GIKS57V1MyNsYpYcUrUeQc9vNfzsWfV28IaLL3i96P9sdNyeRssA=="
crossorigin="anonymous" />
<section class="section-center" id="products-filter">
<div class="products">
<h1>SHOP THE <br />FLAVOURS</h1>
</div>
<button class="toggle-filter" id="toggle-category-filters">
filter
<span id="filter-btn-span"><i class="far fa-minus-square" id="toggleIcon"></i></span>
</button>
</section>
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.
I have a page that is essentially dynamically created (this is key), and in this page I have divs, and each div is supposed to play/pause a song.
The code works if I put alert, so that led me to believe that there is an asynchronous issue. So I tried to add a timeout to when I call play/pause, but that didn't work either.
How the code behaves right now is the first div functions flawlessly, but any other div does not work unless I put an alert.
Has anyone had experience with such an issue?
This is my code, I'm using livequery to pick up the dynamic elements.
EDIT:
The problem now is that only the first song is being played, nothing happens when I click play/pause buttons for the other songs.
function callAction(url) {
if (url == "music.html") {
var believe = new Audio('/assets/music/believe.mp3');
var hope = new Audio('/assets/music/hope.mp3');
var alf = new Audio('/assets/music/alf.mp3');
var thatnight = new Audio('/assets/music/thatnight.mp3');
var lostlove = new Audio('/assets/music/lostlove.mp3');
var time = new Audio('/assets/music/time.mp3');
$("body").on("click", ".pausebutton", function(){
var song = $(this).attr('name');
if (song != null && song == "believe") {
believe.pause();
}
if (song != null && song == "hope") {
hope.pause();
}
if (song != null && song == "alf") {
alf.pause();
}
if (song != null && song == "thatnight") {
thatnight.pause();
}
if (song != null && song == "lostlove") {
lostlove.pause();
}
if (song != null && song == "time") {
time.pause();
}
});
$("body").on("click", ".playbutton" ,function(){
var song = $(this).attr('name');
if (song != null && song == "believe") {
believe.play();
}
if (song != null && song == "hope") {
hope.play();
}
if (song != null && song == "alf") {
alf.play();
}
if (song != null && song == "thatnight") {
thatnight.play();
}
if (song != null && song == "lostlove") {
lostlove.play();
}
if (song != null && song == "time") {
time.play();
}
});
}
}
Not that html would really make a difference, but here is the html:
<div id="music">
<h1>Music</h1>
<br><br>
<div class="row">
<div class="musicEntry red">
<center><p class="musicTitle">Believe</p></center>
<center><p class="musicDate">July 27th 2014</p></center>
<div class="audio-controls">
<center><i name="believe" class="fa fa-play-circle fa-3x playbutton"></i></center>
<center><i name="believe" class="fa fa-pause fa-3x pausebutton"></i></center>
</div>
</div>
<div class="musicEntry red">
<center><p class="musicTitle">A Little Hope</p></center>
<center><p class="musicDate">March 8th 2014</p></center>
<div class="audio-controls">
<center><i name="hope" class="fa fa-play-circle fa-3x playbutton"></i></center>
<center><i name="hope" class="fa fa-pause fa-3x pausebutton"></i></center>
</div>
</div>
<div class="musicEntry red">
<center><p class="musicTitle">Alf Layla</p></center>
<center><p class="musicDate">April 23rd 2014</p></center>
<div class="audio-controls">
<center><i name="alf" class="fa fa-play-circle fa-3x playbutton"></i></center>
<center><i name="alf" class="fa fa-pause fa-3x pausebutton"></i></center>
</div>
</div>
</div>
<div class="row">
<div class="musicEntry red">
<center><p class="musicTitle">That Night</p></center>
<center><p class="musicDate">March 21th 2013</p></center>
<div class="audio-controls">
<center><i name="thatnight" class="fa fa-play-circle fa-3x playbutton"></i></center>
<center><i name="thatnight" class="fa fa-pause fa-3x pausebutton"></i></center>
</div>
</div>
<div class="musicEntry red">
<center><p class="musicTitle">Lost Love</p></center>
<center><p class="musicDate">July 30th 2012</p></center>
<div class="audio-controls">
<center><i name="lostlove" class="fa fa-play-circle fa-3x playbutton"></i></center>
<center><i name="lostlove" class="fa fa-pause fa-3x pausebutton"></i></center>
</div>
</div>
<div class="musicEntry red">
<center><p class="musicTitle">Time (Cover)</p></center>
<center><p class="musicDate">July 26th 2012</p></center>
<div class="audio-controls">
<center><i name="time" class="fa fa-play-circle fa-3x playbutton"></i></center>
<center><i name="time" class="fa fa-pause fa-3x pausebutton"></i></center>
</div>
</div>
</div>
</div>
This is only playing and pausing the first song. Do you have any idea why?
The issue is your click event and dynamically loaded page. When there are dynamically added elements on your DOM, use $(selector).on('click', function(e){}) instead of click events. Below is the modified handler:
$(".playbutton").on("click", function(){
// Your code goes here
});
Have a look at this jsfiddle
http://jsfiddle.net/cVjg9/1/
If you use the method Inder described in the JSFiddle it doesn't work either. For some reason you have to attach it like this:
$("#container").on("click",".pausebutton",function(e){...});
The first selector can be any containing element, for example $("body").
Thinking about it...
The explanation is most likely because you're attaching the event to the top element, not the dynamic element. Every time you click on the surrounding container, the event will be caught and a check will be done whether you clicked on a ".pausebutton" sub-element. In other words, it's more performant to use a dedicated div which closely encapsulated the dynamically loaded elements, instead of just attaching it to the body. Otherwise it will throw events all over the place.
Attaching events like this doesn't work:
$(".pausebutton").on("click",function(e){...});
http://jsfiddle.net/J2LYX/
$(".pausebutton").click(function(e){...});
http://jsfiddle.net/X2rbJ/
Related question:
In jQuery, how to attach events to dynamic html elements?
I solved some of the problem by taking livequery out.
While I am getting my dynamic content using $.get(url), I made a function that acts as a switch. So something like this:
//Get the page here
$.get(url, function() {
//replace content of the page here
callAction(url);
});
// This acts as a switch statement, the javascript is being called just fine, and the code works perfectly now.
function callAction(url) {
if (url == "music.php"){
// do the following here
}
if (url == "blog.php"){
// do the following here
}
}
This worked for me. I didn't have to use livequery anymore. That plugin is terrible.