Reputation: 1138
I'm making a clipboard history extension that stores the user's clipboard data in localStorage
. I've finished working on the background
so that data would be stored in the following format:
{list: [{text: <text that was copied>,
date: <date when it was copied by ms>,
current: <boolean; if the value is currently copied>]}
I coded popup.html
and managed to create a list of copied items.
There is a set of buttons in each box, that can be used to delete and copy each data.
When the button is pressed, I need to run a function deleteItem(ind)
, with the ind
value set as the index of the item.
Each box is created in forEach
by using cloneNode
, so I do not know how many buttons there will be.
I've tried:
document.getElementsByClassName("delete")[numOfRows-1].addEventListener('click', deleteItem(numOfRows-1))
// The button element is currently not in HTML
document.getElementsByClassName("button_container")[numOfRows-1].innerHTML = "<button onclick='deleteItem(" + (numOfRows-1).toString() + ")'>Delete</button>"
document.getElementsByClassName("delete")[numOfRows-1].onClick = Function('deleteItem(" + (numOfRows-1).toString() + ")')()
The first one won't work because numOfRows
keep changing as forEach
is running, which makes it delete the wrong item.
The second one and third one won't work due to content security policy
.
Is there a way I can add event listeners to each item?
Upvotes: 1
Views: 291
Reputation:
After all your boxes are created, run an event listener for delete and copy on each delete/copy in box, using a loop.
Example:
// selects all delete buttons
var deletes = document.querySelectorAll('.delete');
// loops through each delete button
for (var i = 0; i < deletes.length; i++) {
// adds event listener to each delete button
deletes[i].addEventListener('click', function(event) {
// whatever you want to do when the delete button is clicked
// Note: event.target will be the button that was clicked, do not use deletes[i]
});
}
// same as the delete buttons, but for copying
var copies = document.querySelectorAll('.copy');
for (var i = 0; i < copies.length; i++) {
copies[i].addEventListener('click', function(event) {
// your code
});
}
Upvotes: 1