Prevent page from reloading after JQuery triggers - javascript

I'm currently trying to load a web page where complementary data is loaded through ajax when clicking on a "read more" button, but when the script is finished the page reloads. Any tip on how to prevent the page from reloading?
I tried event.preventDefault and return false; but that doesn't seem to work.
Here's my code:
window.setInterval(function () {
$('div.getmore').trigger('click');
return false;
}
, 1000);

The issue is not in your jQuery code that you pasted. Try using firebug console and click persist to make sure you see the javascript error even after page is loaded, you will then be able to find the real issue.

Try this , this should work
window.setInterval(function (e) {
$('div.getmore').trigger('click');
e.preventDefault()
e.stopPropagation()
}
, 1000);

You should preventDefault click on an a element. Not the div if it's inside the a:
<a href="google.com">
<div class="getmore">Get more</div>
</a>
$('a').on('click', function(event) {
event.preventDefault();
});
// Your code

Related

Auto go back after clicking a link in Javascript

When a user click an href link with id="boo" I am trying to get the browser to automatically go 'back' after 2 seconds.
This isn't working and i'm reaching out for some help from you all. Thanks in advance!
document.getElementById("boo").addEventListener("click",
function a(event) {
setTimeout(function() {window.location = History.back},2000)}
);
Edit: (Adding this to clarify my goal)
so basically i want to do two things on click. navigate to a different page (time.is) and then automatically go back to the original page after 4 seconds.
I think you have to make the default function of <a> tag stop working. Please try adding .preventDefault().
document.getElementById("boo").addEventListener("click",
function (event) {
event.preventDefault();
setTimeout(function() {window.history.back()}, 2000);
}
);
If you want to do two things on one click, I suggest this:
Open the other website in a new tab
Go back to a previous page after 2 seconds in an initial tab
JavaScript:
document.getElementById("boo").addEventListener("click",
function (event) {
// Remove .preventDefault()
setTimeout(function() {window.history.back()}, 2000);
}
);
HTML:
<a id="boo" class="clock" href="https://time.is/" target="_blank"></a>
A part from a syntax error (history should be lower case), you are setting window.location with the back function, without executing it.
This should fix your code:
document.getElementById("boo").addEventListener("click",
function(event) {
setTimeout(function() {window.history.back()}, 2000);
});

jQuery working only upon reload

On this WordPress site, I use a site-wide script to add information to outgoing links.
However, it only works if the page is reloaded or the user navigates to any second page.
Assuming it was a jQuery loading time issue, I added a timer to wait for it, but it doesn't make any difference: the message "jQuery loaded!" appears but the click function seems not to be working.
When the page is reloaded, the click function works as expected.
Here is the code:
var jQloaded = setInterval(function() {
if (window.jQuery) {
console.log("jQuery Loaded!");
clearInterval(jQloaded);
jQuery(document).on('click', 'a[href*="/external/"]', (function(e) {
e.preventDefault();
alert('ok');
}));
}
}, 50);
I tried everything I could think of without success. Can you tell me what's wrong?
PS: to replicate the behavior it's necessary to open a fresh incognito/private window. Emptying the cache + hard reload isn't enough.
Try wrapping your code within the document.ready method
$(document).ready(function() {
// code here
});

load a page when close a popup page using "beforeunload"

I am trying to attach an event hanldler to beforeunload in javascript. Here is my code:
$(window).on("beforeunload", function() {
$("#popupin1").load("new.html");
})
I get the alert but the loading div is not happen. Is it possible to call a function on closing a page (popup page) in this way?
finally i got the answer .by done some change in this same code
$(window).on("beforeunload", function() {
window.opener.$("#popupin1").load("new.html");
})
also need
window.opener

How to avoid page refreshing on anchor (<a></a>) tag click?

I'm creating a dynamic website. My problem is when i click on the following tag:
<a class="s-inte" href="set_interesantes.php?n=Frank Melo&u=f6e79cfe9c0ecc4c08dac4c860c4802b&back=http://localhost:8085/Something/success/profile.php?search_user=f6e79cfe9c0ecc4c08dac4c860c4802b&p=12&sa=f6e79cfe9c0ecc4c08dac4c860c4802b&i=2345123&dl=&iv=1">Interesante</a>
The page gets refreshed, How do I avoid this page refresh?
What you want to accomplish is to update some counter of interestings w/o refreshing the page?
You should do it using AJAX techniques, this is what AJAX was invented for.
Consider the following code, it's top easy (jQuery library required):
Interesante
<script>
$(function(){
$("a.counter").click(function()
{
$.get("set_interesantes.php?n=Frank Melo&u=f6e79cfe9c0ecc4c08dac4c860c4802b&back=http://localhost:8085/Something/success/profile.php?search_user=f6e79cfe9c0ecc4c08dac4c860c4802b&p=12&sa=f6e79cfe9c0ecc4c08dac4c860c4802b&i=2345123&dl=&iv=1" );
.... // you can do some animation here, like a "Liked!" popup or something
return false; // prevent default browser refresh on "#" link
});
});
</script>
you need to prevent default action on the click event.
You can do a simple inline handler which will return false
<a class="s-inte" onclick="return false" href="set_interesantes.php?n=Frank Melo&u=f6e79cfe9c0ecc4c08dac4c860c4802b&back=http://localhost:8085/Something/success/profile.php?search_user=f6e79cfe9c0ecc4c08dac4c860c4802b&p=12&sa=f6e79cfe9c0ecc4c08dac4c860c4802b&i=2345123&dl=&iv=1">Interesante</a>
or write a jQuery handler which will do the same
$('.s-inte').click(function(e){
e.preventDefault()
})
If you are dynamically loading the content using ajax. You should probably call it in this way. This way it will work for every anchor with .s-inte class, no matter it's added dynamically or statically.
$(document).on('click', '.s-inte',function(e){
e.preventDefault();
// Do more stuff every anchor click here...
});
put href="javascript:void(0)"

'onbeforeunload' Fires Twice

I want to send an ajax request when a user leaves a page or closes the window.
Here is my code inside :
<script type="text/javascript">
function sendajax(){
$.ajax({
url: "someurl",
data: mydata,
async : false
});
}
</script>
<script type="text/javascript">
window.onbeforeunload=function(){sendajax();};
</script>
When the event occurs the event fires twice.
Why does in happen?
I know I can prevent it by adding a variable var ajaxSent=true; but may be there is a cleaner way to do it?
UPD:
I replaced the sendajax function content with some other code (without sending ajax) and found out that ajax is not the one causing the problem. It still enters the function twice.
Based on the code in your edit and comments, it looks like it could simply be caused by the broken link you are clicking to leave the page.
Given the following code:
<script>
function doSomething() { console.log('onbeforeunload fired'); }
window.onbeforeunload = doSomething;
</script>
link A
link B
If I click on link A, I get two console log entries, if I click on link B I only get one.
It looks like it could be a quirk of how the browsers handle their internal "This web page has not been found" pages, causing your page to be refreshed and closed again before showing the message, leaving you with two occurrences of the onbeforeunload event.
I had the same problem and it took a while to understand and resolve, sharing the case details:
There was a custom JS within our template that manipulated the menu.
It caused the unload to fire twice, only when clicking on the menu links, not on other links, and only in IE/EDGE.
We eventually stopped the propagation on these links and the problem was resolved.
$('.SELECTOR a[href^="http://"]').on('click', function(e){
e.stopPropagation();
});
It's a specific bug in your application, therefore you won't find too much information on google.
You could try the following code:
<script type="text/javascript"><br>
window.onbeforeunload=function sendajax(){<br>
$.ajax({<br>
url: "someurl",<br>
data: mydata,<br>
async : false<br>
});<br>
};<br>
</script>
or you can define sendajax() {} at some place and the use it like onbeforeunload = "sendajax()" not as onbeforeunload = "function () { sendajax() }"
beforeUnload is cancellable
I know this post is quite old but from the Chrome Pagelifecycle API documentation, browsers can occasionally partially unload pages to save resources. https://developers.google.com/web/updates/2018/07/page-lifecycle-api beforeUnload is not reliable to make sure that the page is closed. This especially happens on android devices when the screen is locked.
There is a jsfiddle that I found somebody wrote that you can test out https://jsfiddle.net/ov6b9pdL/. Keep the screen locked for 5-10 minutes on Chrome android and you'll see that beforeUnload is fired without even closing the tab.
$(document).ready(function() {
window.addEventListener('beforeunload', showLoader);
});
var showLoader = function() {
$('#loader').show();
};
Agree with AlonMichaeli's concept.
In my application there was anchor tag wrapped with in a div together with couple of spans. When Anchor was clicked on a dirty page, there was couple of 'Leave site' notifications.
It worked fine if any other part of menuItem (div or spans) are clicked.
So in custom javascript method I've added stopped propagation and preventDefault only if anchor tag is clicked. Somehow in this case preventDefault is necessary.
function menuItemClicked(event: JQueryEventObject) {
var item = $(event.target);
if (item.is(".anchor-item")) {
event.stopPropagation();
event.preventDefault();
}
href = item.closest(".anchor-item").attr("href");
if (!event.ctrlKey && href) {
window.location.href = href;
}
}

Categories

Resources