favorite script with local storage don't work - javascript

I want to add data-id from a button in favorite list.
I tried few solution but the click action is never detected in console .
html code is
<button class="icon-plus-circle i-circled i-small addToCart" date-id="myId" data-name="myName"></button>
js code is
button.addEventListener('click', function (){
var id = $(this).attr('data-id');
var name = $(this).attr('data-name');
console.log(id);
let Fav = {
id : id ,
name : name
};
let liste_json = JSON.stringify(Fav);
localStorage.setItem('listeFavoris', JSON.stringify(liste_json));
} )

You need to select the button
const button = document.querySelector('button');
const button = document.querySelector('button');
button.addEventListener('click', function() {
console.log('click detected');
});
<button>Click Me</button>
PS - You have added click listener using javascript and have jQuery code inside. Don't mix up two, stick with one.

Related

Button Text not updating within eventListener

Button text is not updating when the event is triggered. This is a submit event but I've also tried a click event. I've also tested the code outside of the event listener and it works correctly. So the problem seems to be within the event listener.
Here is the code:
let addToCartForms = document.querySelectorAll(".bundle-builder--add-to-bundle-form");
addToCartForms.forEach((el)=>{
let btn = el.querySelector('.add-to-cart');
let btnText = btn.innerText;
el.addEventListener("submit",(e)=>{
btn.innerText = "added"
});
})
Both click and submit work. Maybe the form is submitted so you can't see the effect?
let addToCartForms = document.querySelectorAll(".bundle-builder--add-to-bundle-form");
addToCartForms.forEach((el) => {
let btn = el.querySelector('.add-to-cart');
let btnText = btn.innerText;
el.addEventListener("submit", (e) => {
btn.innerText = "added"
});
})
<form class="bundle-builder--add-to-bundle-form">
<button class="add-to-cart">click</button>
</form>
Maybe this jQuery solution could work.
$('body').on('submit', '.bundle-builder--add-to-bundle-form .add-to-cart', function(e){
(e).preventDefault();
(this).text('added');
setTimeout(function() {
(this).submit()},500)
})

Javascript - Creating event listener that returns id of dynamically generated content

my main project is too complicated to show here so I created a small script demonstrating the problem I am working on. In simple terms, I need to create a button that once clicked, generates a button that also has an event listener that returns that button's id to the console.
See code below:
button_number = 0
create_buttons = document.getElementById('create_buttons')
div = document.getElementById('div')
create_buttons.addEventListener('click', e=>{
button_number += 1
new_button = document.createElement('button')
new_button.setAttribute('id', 'button'+button_number)
new_button.innerHTML = 'What number am I?'
new_button.addEventListener('click', show_button_number)
div.appendChild(new_button)
})
function show_button_number () {
let number = button_number
button = document.getElementById('button' + number)
console.log(button.id)
}
<div id="div">
<button id="create_buttons">Create a button!</button>
</div>
As written, all generated buttons return the button id of the most recently generated button versus their own id. Is there anyway I can change the anonymous function to return the button id of the button that was clicked? In order to integrate this into my main project, I need to create the event listener for the dynamically generated buttons using an anonymous function.
You could make a higher-order function, one that takes the current button number as an argument and returns a function using it:
const makeListener = num => () => {
const button = document.getElementById('button' + num)
console.log(button.id)
};
new_button.addEventListener('click', makeListener(button_number))
Or, you may not need the ID at all, just pass the element itself:
create_buttons.addEventListener('click', e=>{
const btn = div.appendChild(document.createElement('button'));
btn.textContent = 'What number am I?'
btn.addEventListener('click', () => {
console.log(new_button);
});
});
The major way to do that is to use event delegation mechanim
const divParent = document.getElementById('div')
var button_number = 0
divParent.addEventListener('click', e =>
{
if (!e.target.matches('button')) return // ignore clicks from other things
if (e.target.id === 'create_buttons')
{
let new_button = document.createElement('button')
new_button.id = 'button' + ++button_number
new_button.textContent = 'What number am I?'
divParent.appendChild(new_button)
}
else
{
console.clear()
console.log( e.target.id )
}
})
<div id="div">
<button id="create_buttons">Create a button!</button>
</div>

Javascript alert not displaying at all

I have this function that should I think trigger an alert whenever one of the buttons in my page gets clicked, however nothing happens and if I open the console on the webpage, no errors show. why is it?
document.addEventListener('DOMContentLoaded' , () => {
document.querySelectorAll('.new-button').forEach (button => {
button.onclick = () => {
const buttonName = button.innerHTML;
alert(`you have selected the button! ${buttonName}`);
}
});
});
I am using the ES6 version of JavaScript if that's any help.
If you dynamically add elements, you have to attach the eventListener to some ancestor element that was statically added. documentworks, but you can add more specific elements for performance. This concept is called delegate listener.
document.addEventListener('click',function(e){
if(e.target && e.target.matches('.new-button')){
const buttonName = e.target.innerHTML;
alert(`you have selected the button! ${buttonName}`);
const newButton = document.createElement('button');
newButton.classList.add('new-button');
newButton.innerHTML = 'click me!!';
document.getElementById('container').append(newButton);
}
});
<div id="container">
<button class="new-button">click me!</button>
</div>

Getting the ID from a button created with JavaScript

So I am creating a few buttons dynamically via javascript.
function dobutton() {
for (i=0; i<eigenschaften; i++){
var btn = document.createElement("BUTTON");
btn.className = 'button black';
btn.id = eigenschaftsarray[i];
btn.name = 'pickbutton';
btn.innerHTML = eigenschaftsarray[i].split("_").join(" ");
document.getElementById('auswahl').appendChild(btn);
document.getElementById('auswahl').innerHTML += " ";
}
}
eigenschaften = 39
eigenschaftsarray = just some names
Now I want to get the ID of the button I click. I was not able to get anything from this JavaScript - onClick to get the ID of the clicked button running because of my method using js to create those buttons. Adding the onClick event to my code just instantly alerts 39 "unknown".
Can someone provide me some help, I am just using Javascript, no jQuery :)
Thanks!
When you create elements dynamically, you have to keep in mind that you can bind events to them only after they are available in the DOM.
Here is a working demo: jsfiddle demo
In the demo, we bind an event listener ("click") to the parent that contains the buttons. The parent is a static element, already available in the DOM.
The JavaScript code is:
var eigenschaften = 3;
var eigenschaftsarray = ["b0","b1","b2"];
// fn: detect if a button was clicked -> get id
function buttonClick(e){
// check if the clicked element is a button
if (e.target.tagName.toLowerCase() == "button") {
var btn = e.target;
// alert the user what button was clicked
alert("button id="+btn.id);
}
}
// fn: create buttons dynamically
function dobutton() {
// identify parent
var parent = document.getElementById('auswahl');
// create buttons dynamically
for (i=0; i<eigenschaften; i++){
var btn = document.createElement("button");
btn.className = 'button black';
btn.id = eigenschaftsarray[i];
btn.name = 'pickbutton';
btn.innerHTML = eigenschaftsarray[i].split("_").join(" ");
// append btn to parent
parent.appendChild(btn);
parent.innerHTML += " ";
}
// add "click" listener on parent
parent.addEventListener("click", buttonClick);
}
// create buttons
dobutton();
Step 1: Add Buttons Dynamically To DOM
HTML :
<body>
<h1>
HelloWorld HelloWorld
</h1>
<div id="stackMe"></div>
</body>
Javascript :
const data = [{'Name' : 'Hello', 'Id' : 1},
{'Name' : 'World', 'Id' : 2}];
window.addEventListener('DOMContentLoaded', function (){
console.log('DOM loaded');
generateButtons(data);
});
function generateButtons(data) {
const buttonResults = data.map(bt =>`<button id= "${bt.Id}" onClick="btClicked(${bt.Id})">Button ${ bt.Name }</button>`);
document.getElementById("stackMe").innerHTML = buttonResults;
}
Step 2: Add an event listener for the button clicked
function btClicked(currentId) {
let elementClicked = data.find(d => d.Id == currentId);
console.log(elementClicked);
}
Output: Out after the button is clicked

click event not triggered in the external file

I am trying to create a library code that can be used across all my html pages.
I am very new to JS and this is the first code that I am trying to write like a library function.
I have a text field and a button next to it, on click of the button this adds a another text field below and a button next to it, this also removes the button in previous line.
I managed to do a button in the same row and adding text field in next lines, but the button click for newly added methods are not working with pure JS so I tried to use jquery "on" click event. For some reason its not getting triggered in my case.
Not sure what I am missing.
Code in external file
var addAnother = {
addAnotherField: function (eventTrigger, fieldContainer, arrayField) {
console.log("called");
var eventTrigger = eventTrigger;
console.log("ready called", eventTrigger);
$(document).on('click', eventTrigger, function (e) {
console.log("click called");
var buttonText = this.value;
var div = document.getElementById(fieldContainer);
var element = document.getElementById(eventTrigger);
element.parentNode.removeChild(element);
var input = document.createElement("input");
input.type = "text";
input.name = arrayField;
div.appendChild(document.createElement("br"));
div.appendChild(input);
var button = document.createElement("input");
button.type = "button";
button.id = eventTrigger;
button.value = buttonText;
div.appendChild(button);
});
}
}
code in HTML
$(document).ready(function () {
addAnother.addAnotherField("addAnother", "addAnotherContainer", "fieldArray[]");
});
Working JS code:
http://jsfiddle.net/balasivagnanam/ekoob8f0/
next button non working code JS
http://jsfiddle.net/balasivagnanam/ukseeuak/
with Jquery:
http://jsfiddle.net/balasivagnanam/6ea2dk6m/
Is this what you want:
/** this part will be located in another file added as a js library */
function addAnother(elem) {
var text = $("#addAnotherField").clone();
$("<br/>").insertBefore($("#addAnother"));
text.insertBefore($("#addAnother"));
}
/* this part will be coded below the above code file in the html file*/
$(document).ready(function () {
$('#addAnother').click(function () {
addAnother(this);
});
});
Here is the JSFiddle demo

Categories