I’m making a note-taker app.
The problem is….when I click the ‘view detail’ button which I created, no matter what button I click among these, it shows me the modal of last content that I made.
I believe it shows me the content from the last object I created from the class function. And the class function keeps refreshing the object.
I want it to show me the content depends on the ‘view detail’ button I clicked.
Can you help me? Thank you (I marked up ❓ on the code for I what I think the issue is so that you can read more easily)
class Note {
constructor(a,b){
this.title = a;
this.body = b;
}
}
submitBtn.addEventListener('click',run);
function run(e) {
e.preventDefault();
let newNote = new Note(titleInput.value,noteInput.value);❓
addNoteToList(newNote);
titleInput.value = "" ;
noteInput.value = "" ;
}
function addNoteToList(newNote) {
let note = document.createElement('div');
note.classList.add('note_new_container');
noteNew.append(note);
note.innerHTML=
<span hidden >${newNote.id}</span>
<h2 class="note_title">${newNote.title.substring(0,20)}</h2>
<div class="note_content">${newNote.body.substring(0,30)}</div>
<button class="myButton2 detail">view detail</button>
<button class="myButton2 delete">delete</button>
;
noteNew.addEventListener('click', (e) => {
if (e.target.classList.contains('detail')) {
activeModal(newNote);
modalDetailContainer.classList.add('modal_show');
}
});
}
function activeModal(a) {
document.querySelector('.modal_title').innerHTML= ${a.title};❓
document.querySelector('.modal_content').innerHTML = ${a.body};❓
}
Advertisement
Answer
Your class
code is fine, there is nothing wrong with the instances, and nothing is shared.
The problem is that you are attaching the listener – all listeners – to the noteNew
container that holds all the notes, not to the invidual new note
divs. Clicking on one .detail
button will fire them all, and the last one will win.