I have a link that loads a page and calls a javascript function on click. Problem is the javascript function can't finish before the page redirects. Is there anyway to ensure it does ?
You will notice there's an alert()
that is commented out in the javascript function, and if I uncomment it, the function is able to complete. However, I obviously don't want an alert popup to actually take place.
Here is the link :
<a href="p.php?p=$randString&s=$postCat" onclick="setYSession();">
Here is the javascript function that can't finish in time :
function setYSession() {
var YposValue = window.pageYOffset;
$.get('yPosSession.php?yValue=' + YposValue);
//alert(YposValue);
return false;
}
onclick does trigger first, the href only goes once onclick has returned!
This is a type of JavaScript link - the onclick attribute defines a JavaScript action when the 'onclick' event for the link is triggered (i.e. when a user clicks the link) - and there is a URL present itself in the onclick attribute.
To disable href if onclick is executed with JavaScript, we call preventDefault to stop the default navigation action. document. getElementsById("ignore-click"). addEventListener("click", (event) => { event.
In JavaScript, you can call a function or snippet of JavaScript code through the HREF tag of a link. This can be useful because it means that the given JavaScript code is going to automatically run for someone clicking on the link. HREF refers to the “HREF” attribute within an A LINK tag (hyperlink in HTML).
Try changing the onclick
to return the result of your function:
echo "<a href='p.php?p=$randString&s=$postCat' onclick='return setYSession();'>";
Or explicitly return false:
echo "<a href='p.php?p=$randString&s=$postCat' onclick='setYSession();return false'>";
Given that your function returns false
, either way will stop the default event behaviour, i.e., it will stop the link navigating at all. Then within your function you can add code to do the navigation after your Ajax finishes:
function setYSession() {
var YposValue = window.pageYOffset;
$.get('yPosSession.php?yValue=' + YposValue, function() {
window.location.href = 'p.php?p=$randString&s=$postCat';
});
return false;
}
Ideally, especially since you seem to be using jQuery for the $.get()
, I'd remove the inline onclick and do something like this:
echo "<a href='p.php?p=$randString&s=$postCat' id='myLink'>";
$("#myLink").click(function() {
var YposValue = window.pageYOffset,
myHref = this.href;
$.get('yPosSession.php?yValue=' + YposValue, function() {
window.location.href = myHref;
});
return false;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With