Js scroll to view only when the submit complete - javascript

Hello I'm trying to scroll into the div only when the submit finishes with promisses
function submitForm(form) {
console.log("submitForm: ", form);
return Promise.resolve(() => form.submit());
}
async function submitFm (form) {
console.log("submitFm: ", form);
await submitForm(form);
};
submitButton.addEventListener("click", () => {
submitFm(form).then(() => {
console.log("should display after submit is done!");
});
});
The promise is suppose to work like this, does anyone knows what's missing ?
Thanks in advance

The submit() method on a form triggers form submission (and navigation to the result).
As soon as that is triggered, the submit() function finishes.
Then the promise resolves.
Then the then function executes.
Then the browser navigates to the new page.
There is no way for JavaScript running in a web page to directly cause JavaScript to run in the next page the viewport navigates to.
Unloading the current page will kill any JavaScript running in it. The next page, whether it be on the other end of a link, or a form submission or a call to location.reload(), etc. is a blank slate. Any JS in that page runs from scratch.
If you want to cause an effect in it you need to do so by passing a message through something that will persist between page loads.
Examples include a query string on the URL or the Session Storage API.
Then you need JavaScript in the next page to check for that message, act on it, and possibly clean it up so it doesn't effect the next page load.

If you submit a form base on form action, you need to pass the state to the next page. The simpler way is that use an anchor in the URL, URL with a hashtag will scroll to the element that id is the hashtag.
e.g.
<form action="/post/data#id" method="post"></form>
If you submit based on ajax or fetch, you redirect the URL when submitted, you also use hashtags. or you can persistence your data by Storage API, and control the scroll action on the next page.
If you use SPA frameworks like Vue React or others. You can use the router API to handle URL changes on submit. or handle scroll directly when form submits success.

Related

Click on button after page reload

I have some links on the page and when user click on link, page is reloaded.
All links have some ID and all have the one same class.
I need to click on some other link after page is reloaded, but only if user click on some of the link with particular class (not anywhere, like menu link).
How I can do something like this using JS or jQuery?
It sounds like you are attempting to build a single page application, ie the application is mostly run by JavaScript instead of server side rendering. In this case page reloads are you enemy. A page reload is basically a restart of your page, and while you can keep state using cookies or localStorage, this will provide you with a rather poor user experience.
In this case, you would just add event handlers to any actions your user would take, and simply handle them in javascript without reloading the page from the server. If you need to get more data in response to the user's actions, you can use AJAX to pull that data from the server.
If you have to use links with urls (still unclear to me why that would be necessary), I would recommend using hash urls like so '#some-action' which will not reload the page when clicked. You can then attach an event handler to the link, or even listen for the url hash to change using the hashchange event. In this way you can know what link the user pressed.
If you are not trying to build a single page application, you will need to add code on the server to store the information you need in the page.
I did it.
So, I created function:
/**
* Click on delivery link after page reload
*
* #return {boolean} [loacalStorage is available]
*/
$.fn.openDelivery = function(){
if (localStorage) {
var addedToCart = localStorage["addCart"];
if (addedToCart) {
setTimeout(function() {
$('#showRight').trigger('click');
}, 1500);
localStorage.removeItem("addCart");
}
$(this).click(function(e) {
localStorage["addCart"] = true;
});
return true;
}
return false;
};
And then called that function:
$(document).ready(function () {
// Trigger delivery click
$('.class-of-my-link').openDelivery();
});
In my case, page reloads after user add some item in shopping cart. With this function I click on link (with 1.5s delay) that opens cart of the user that is shown on the right side of the screen.

Fire a Javascript function after submitting a Gravity Form

I have a multi-page form where the url remains the same when moving between pages.
I am trying to change some HTML after the submit button has been clicked.
I can run this in the console and the result is as I want it.
How can I get this run after submit?
I've tried window.onload and document.onload functions but they are not working. I've also tried an onclick function but it seems moving to the next page stops this working?
var confirm = document.getElementById('gform_confirmation_message_14');
if(confirm) {
document.getElementsByClassName("entry-title")[0].innerHTML = "PAYE Worker";
}
Thanks
Perhaps the gform_page_loaded event? From the documentation it:
Fires on multi-page forms when changing pages (i.e. going to the next or previous page).
$(document).on('gform_page_loaded', function(event, form_id, current_page) {
// do stuff
});
There are a bunch of javascript events available, and if not this one, maybe another serves your purpose, e.g. gform_post_render.
I removed the Javascript completely and created a confirmation in Gravity Forms that redirects to a new page upon submission.
Created a title for this new page "PAYE worker"
Problem solved

Making ajax call on navigating away from page

I am working on a site that has multiple links to other sites. What I want is to send an ajax call to report that the user is going away when someone clicks and navigates away from the page. I put an alert on click of the links, which works but for some reason the controller never gets the ping.
Any assistance will be appreciated on how to achieve it.
Can't be done.
When you go to navigate away, there is only one event that can catch that, the onbeforeunload event, and that is quite limited in what it can do.
Not to mention there are other ways of leaving the page without navigating away:
Losing network connection
Closing the browser.
Losing power.
The only thing you can do is to set up a heartbeat kind of thing that pings the server every so many milliseconds and says 'I'm Alive.'
Depending on what you are trying to do, there is usually a better option, however.
You can try to simply set click event handler which will check the href attribute of every link before navigating. If it goes to another website, the handler sends AJAX request and then (after server responding) redirects to the page.
var redirect = '';
$('a').click(function() {
if (this.href.host != document.location.host) {
if (redirect) return false; // means redirect is about to start, clicking other links has no effect
redirect = this.href;
$.ajax({
url: '/away',
success: function(){document.location.href = redirect;}
});
return false;
});
However it can't work properly, if user has opened your page in multiple tabs.
The only reliable way to do this these days is by hooking (i.e. add event listener) your code in so called sendBeacon method from Beacon API on beforeunload event (i.e. when user tries to navigate away from page).
The navigator.sendBeacon() method asynchronously sends a small amount of data over HTTP to a web server. It’s intended to be used for sending analytics data to a web server, and avoids some of the problems with legacy techniques for sending analytics, such as the use of XMLHttpRequest:
<script>
var URL = 'https://your.domain/your-page.php';
// on 'beforeunload'
window.addEventListener('beforeunload', function (event) {
navigator.sendBeacon(URL);
// more safely is to wait a bit
var wait_until = new Date().getTime() + 500;
while (new Date().getTime() <= wait_until);
});
</script>
You can try:
$(window).on('beforeunload', function(){
return "This should create a pop-up";
});
You can achieve it by capturing clicks on all the links on the page (or all the relevant links) and then call ev.preventDefault() on it to prevent the browser from navigating directly to that page.
Instead, you can make an AJAX call to your server and when that call returns, you can set window.location to the URL the user was trying to navigate to.
Here is a workaround you could try.
At the loading of the page, use jquery to move all href attributes to tempHref attribute. Then, attach a method to catch the click event.
This way, clicking on the links will not automatically move to the intended destination.
When the click occurs, simply perform the ajax call, and then using javascript, move to the other page.
$('a').each(function () {
var link = $(this);
link.attr('tempHref', link.attr('href'));
link.removeAttr('href');
});
$(document).on('click', 'a', function ()
{
//perform ajax call;
location.href = $(location).attr('tempHref');
});

Stealing the redirect URL of a button

Is it possibe to change the return URL of a button whose job is submitting a form to the server? The main deal here is that I don't have the script that controls the button, hence the word "stealing."
If you are curious about the use case, I have a Salesforce Visualforce page that has an embedded Flow in it. I want to jump out of the Flow when the user is half way through and a certain condition is met.
Assuming the button is not in an iFrame...
$('#some_button').click(function (e) {
e.preventDefault();
// Do stuff here then submit the form..
$('#some_form').submit();
});
You could also use this method for $('#some_form').submit().... You can read more about it here.

how to detect (all) mouse clicks?

I use such code to catch users clicks:
Event.observe(document, 'click',function(e){
var x = Event.pointerX(e);
var y = Event.pointerY(e);
//exec data storage over ajax
}
The problem is when the user click some link, the next function don't have time to execute entirely and I can't save the click data before redirect to the clicked link.
I saw some jquery implementation, but I don't use jquery.
If you must execute a function before the redirect you need to override the default action of the link, once your function finishes executing then call the redirect manually.
Im guessing its the ajax that needs to complete before redirecting? If so then you need to add the redirect in the callback function of your ajax.

Categories

Resources