I created a table with the ability to edit with popup.
This part of the code, which includes:
- the ability to send URL to other users with the subsequent opening of the same state (the popup window is empty or with data to be edited) I get the current URL and then I get data from the server. And if the URL includes ID of the data to be editing, I open popup with this data or the empty popup.
- the ability to work the browser using the buttons "back" and "forward". I used the history.pushState method.
I use the Fetch API for requests to the server. To build the table and the popup, I used jQuery. But in the part of the code with browser history I can't find a way to use jQuery, only pure JS.
I will appreciate any advice about code.
const getLink = window.location.hash.slice(1) // to get the current URL witout hash
fetch('http://localhost:3000/names') // to get the data from the server
.then((response) => response.json())
.then((_names) => {
names = _names //the data
drawTable() // update table according to data
if (getLink != 0 && getLink != 'add-new'){ //if URL includes ID of the data
idEdit = getLink //assign ID from URL as an ID to edit
addEditValue() // function for popup opening with the data to be editing
}
})
if (getLink == 'add-new') {openAddForm()} //open the empty popup
top.addEventListener('click', function(e){ // listen a click on the page
if(e.target == $('#add-new') || e.target.className == 'edit-btn'){
//if a click on the button for opening empty popup or popup with the data to be editing
e.preventDefault()
const data = e.target.id
const url = "/#" + data
e.target.setAttribute('href', url)
history.pushState(data, null, url)
} else if(e.target.className != 'input-form-body') {
//if you click after closing the pop-up window, then clear the URL
window.location.hash = ""
}
e.stopPropagation()
}, false)
window.addEventListener('popstate', function(e){
const character = e.state
if(character == null){
closeForm() // close popup
} else {
idEdit = character
addEditValue() //open popup with the data to be editing
}
})