I am working in a project where I show some modals under certain conditions, after some work I realized that if I try to refresh the page while a modal is showing up, the modal vanishes.
I would like to know if there is a method that would let me render the modal when refreshing the page.
I tried this java script code:
// Get the modal
var modalBtn = document.getElementById("modalBtn");
// // Get the button that opens the modal
// var buttonModal = document.getElementById("buttonModal");
window.onbeforeunload = function (evt) {
buttonModal.click();
console.log("refresh")
}
// //hold modal
buttonModal.addEventListener('click', () => {
// //show error modal
$("#modal_error").modal()
})
In the case I click on buttonModal, I can see the modal, but when I refresh it vanishes.
If I refresh the page I can see the modal for an short period of time, but it does not hold itself.
would there be a way that let me hold the modal, if its being display, inclusive after refreshing?
Luis
Related
I am working on a web app using Node express mongoose and ejs.
I have a modal that shows when a user logs in or signs up and redirects to the dashboard page. The modal is basically a daily motivation quote that's being fetched from an quote API.
Here is my modal that is inside of my dashboard ejs file:
<div id="modal-container">
<div id="modal">
<h5>✨Motivation of The Day✨</h5>
<span class="quote"></span>
<div id="close-btn">close</div>
</div>
</div>
here is my js that manipulate the DOM:
let quote = document.querySelector('.quote')
let closeBtn = document.getElementById('close-btn')
let modalContainer = document.getElementById('modal-container')
window.addEventListener('load', async function() {
let quotes = []
const response = await fetch(`https://type.fit/api/quotes`)
const listOfQuotes = await response.json()
listOfQuotes.forEach(quote => quotes.push({quote: quote.text, author: quote.author}))
let random = Math.floor(Math.random() * quotes.length)
quote.innerText = quotes[random].quote
closeBtn.addEventListener('click', function() {
modalContainer.style.display = 'none'
})
})
the route for this dashboard is /dashboard. Every time I do something like edit a post it takes me to a new page to make the edits and when done I redirect back to the /dashboard route and the modal pops back up again.
how can I make sure the modal only shows once the user logs in/ signs up and only that one time and not every time a user gets redirected to the /dashboard route?
Can someone point me in the right direction?
Pretty sure this is happening because you have the modal set to appear every time the window loads and you're not checking if the user has met the condition for the modal to actually appear. The modal appears when the page loads, the user navigates to a different page and, when they return to the /dashboard route, the event listener on window fires again and the modal appears.
You can include a conditional check in the event listener to see if the user is logged in or not and then have the modal's display change based on that value. Basic example below.
HTML:
<body>
<div>
<h1>The text below will hide based on "login" state</h1>
<p class="login-text">The user is logged in</p>
</div>
</body>
JS:
const isLoggedIn = true;
const textToHide = document.querySelector(".login-text");
window.addEventListener("load", () => {
if (isLoggedIn === false) {
textToHide.style.display = "none";
} else {
textToHide.style.display = "block";
}})
As for handling the state of the user having logged in, you could save that state in localStorage or in cookies, depending on your needs.
Background: I'm displaying a list on a website. Each row in the list has an edit button that opens a Materialize CSS modal. Inside the modal is an HTML form that pulls the current values from that specific row in the list, which can be edited with new values.
Issue: Once the edits in the modal form are submitted, the modal will retain the values of that specific row, even when selecting a different row. This does not happen when the modal form is not submitted.
Temporary Solution: I reload the entire page when the modal is submitted. This way the modal contents are also refreshed, but the user experience suffers since the user needs to always wait for the page to reload.
Question: Is there a way to reload or refresh the contents of the modal or the modal form without reloading the whole webpage? Ideally, the modal would refresh and load the correct values for each row after submitting an edit. I am open to other ideas/solutions.
Code:
auth.onAuthStateChanged(user => {
if (user) {
const editForm = document.querySelector('#edit-form');
editForm.addEventListener('submit', (e) => {
e.preventDefault();
db.collection('users').doc(user.uid).collection('items').doc(editForm.itemID.value).collection('transactions').doc(editForm.transactionID.value).update({
amount_edit: (parseFloat(editForm.amountEdit.value)*-1).toFixed(2),
name_edit: editForm.nameEdit.value,
}).then(() => {
// close the edit-modal
const modaledit = document.querySelector('#modal-edit');
M.Modal.getInstance(modaledit).close();
editForm.reset();
location.reload()
}).catch(err => {
console.log(err.message);
});
})
} else {
}
});
A bit late to the party. You could reset and then dispatch a focus event for each field.
editForm.reset()
editForm.querySelectorAll(`[name]`).forEach(i => i.dispatchEvent(new Event('focus')));
i have a page with a form in it, the form data is then passed on to the next page which displays the respective items from a database. everything works fine, when i click on an item, it takes me to another page as expected. but when i go back to the page with the list items, it reloads the list. How can i stop that, i want the users to be go back and continue scrolling from where they stopped like instagram explore page.
exports.pageLoaded = function (args) {
const page = args.object;
const searchViewModel = new SearchViewModel();
page.bindingContext = searchViewModel;
searchViewModel.initDataItems();
searchViewModel.addMoreItemsFromSource(8);
}
The issue
i think the issue is because i used const searchViewModel = new SearchViewModel(); in pageLoaded function but i dont have an alternative for that, i did that because of the previous page that is sending data to the page that displays the list. if i don't do that it wont reload the list when the user searches.
My Aim
What i want is for the page to load new items when the user searches, and then when the user clicks on an item and goes back to the list, it shouldn't reload the list but continue.
My question
How can i navigate to another page onItemTap without deleting the items on the listview. or which page even can i use that will only fire the first time the page was opened
Playground sample
Playground
i have found a solution, using modal pages
Your item tap will open a modal page, therefore the listview items still remain. so the code will be:
const modalViewModule = "image/image";
exports.onImageTap = function (args) {
const view = args.view;
// const page = view.page;
const tappedItem = view.bindingContext;
const mainView = args.object;
const option = {
context: tappedItem,
fullscreen: true,
};
mainView.showModal(modalViewModule, option);
}
and then the modal page you're opening will be
<Page shownModally="onShownModally">
<!-- Your page content -->
</Page>
My playground sample
I am trying to work the bugs out of my modal. I am using Bootstrap, Angular and ng-Route. I recently noticed on mobile (and then on desktop) when I push the back button with the modal open it leaves a gray overlay and you cannot click anything. So the solution I found that partially fixes the problem is to add this script:
$(".modal").on("shown.bs.modal", function() { // any time a modal is shown
var urlReplace = "#/" + $(this).attr('id'); // make the hash the id of the modal shown
history.pushState(null, null, urlReplace); // push state that hash into the url
});
// If a pushstate has previously happened and the back button is clicked, hide any modals.
$(window).on('popstate', function() {
$(".modal").modal('hide');
});
This works great then the user presses the back button however when the user closes the modal by clicking outside of the modal or hitting escape the urlReplace remains in the browser address bar. I want to get it to change back to the previous when ever the modal is closed.
If that issue cannot be resolved I at least would like this other issue to be fixed which is this: When the user closes the modal by clicking outside or hitting escape the urlReplace remains in the browser address which is fine but when the user then goes to click a link in my nav bar it doesn't take them to the link it goes to a blank page with the urlReplace still in the address bar and then I can click a link in the nav bar again and it will go to the proper link which I find strange not sure how to resolve this issue.
Any ideas or insights into this would be awesome!
You can add a handler to watch for the modal close event, then push a new history with the hash removed:
$(".modal").on("hidden.bs.modal", function() { // any time a modal is hidden
var urlReplace = window.location.toString().split('#', 1)[0]
history.pushState(null, null, urlReplace); // push url without the hash as new history item
});
I have an odd issue in protractor.
All I need to do is test form thats in a modal. I can confirm that the modal is open, but then I want to sendKeys to the input(s).
element(by.id('modal')).click().then(function () {
var modal = $('.modal');
browser.wait(EC.visibilityOf(modal), 5000);
expect(modal.isDisplayed()).toBeTruthy();
element(by.model('userInput.firstName')).sendKeys('HELLO'); // <- this fails
})
This test will fail with ElementNotVisibleError. But when I set the modal to auto open once the page is hit (rather than via a button click), I make sure the modal is displayed and send the keys. This passes fine.
Any advice is appreciated.
Wait for the visibility of the input element instead:
var modal = $('.modal');
var modalInput = modal.element(by.model('userInput.firstName'));
browser.wait(EC.visibilityOf(modalInput), 5000);
modalInput.sendKeys('HELLO');