In Laravel 9 I've got 2 tables, one inside of another.
To avoid second table from taking too much space, by default, it's display is set to none and can be "rolled out" when button is pressed
<button
type="button"
class="btn btn-warning"
id="hidden{{ $buttonIndex }}"
onclick="
$('.items{{ $buttonIndex }}').slideToggle(function() {
$('#hidden{{ $buttonIndex }}')
.html(
$('.items{{ $buttonIndex }}').is(':visible')
? 'Roll'
: 'Rollout'
);
});"
>Rollout</button>
but when I refresh the page or do any CRUD operation, opened tabs are getting closed again.
Is there any way to keep them opened after page refresh?
I tried my way with AJAX, but if I would like to use it, I will need to rebuild whole CRUD operations and view, so I would prefer to avoid it.
Other way I'm about to try is to send button ID data on request, so in case it would be clicked, it will appear in the request(or url), but I've got no idea how to achieve it yet.
How can I keep second table opened on page refresh/reload
It sounds like the Session Storage is perfect for your use case
From Mozilla's documentation:
Window.sessionStorage
The read-only
sessionStorage
property accesses a sessionStorage
object for the current origin.sessionStorage
is similar tolocalStorage
; the difference is that while data inlocalStorage
doesn't expire, data insessionStorage
is cleared when the page session ends.
- Whenever a document is loaded in a particular tab in the browser, a unique page session gets created and assigned to that particular tab. That page session is valid only for that particular tab.
- A page session lasts as long as the tab or the browser is open, and survives over page reloads and restores.
- Opening a page in a new tab or window creates a new session with the value of the top-level browsing context, which differs from how session cookies work.
- Opening multiple tabs/windows with the same URL creates
sessionStorage
for each tab/window.- Duplicating a tab copies the tab's
sessionStorage
into the new tab.- Closing a tab/window ends the session and clears objects in
sessionStorage
.
Let's say your table is in a div like this.
<div id="hidden-table-{{ $index }}" class="hidden-table">
</div>
In your jquery, you get set its display based on some sessionStorage
key.
$(() => {
$('.hidden-table').each(element => {
(sessionStorage.getItem('should-show-'+$(element).attr('id')) !== null)
? $(element).show()
: $(element).hide();
});
})
For this to work, you need to set this sessionStorage item whenever you're showing the table.
// show table with id 'table-id'
sessionStorage.setItem('should-show-table-id', true); // or anything that isn't null really.
And remove the key when you're hiding it
// hide table with id 'table-id'
sessionStorage.removeItem('should-show-table-id'); // removes the key. Using getItem on a key that doesn't exist returns null, so that works just fine.