Trying to trigger a function (let say an alert) with the press of the back button (every time).
Code goes as:
$(function() {
if (window.history && window.history.pushState) {
window.history.pushState('', null, './');
$(window).on('popstate', function() {
alert('Back button was pressed.');
});
}
});
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
However, the above code works but only once on page load, to make it work again, I have to reload the page again, hence the function runs again so that it detects the "back press".
To overcome this, I tried calling the function in the same function.
function call() {
if (window.history && window.history.pushState) {
window.history.pushState('', null, './');
$(window).on('popstate', function() {
alert('Back button was pressed.');
call();
});
}
}
$(document).ready(function() {
call();
});
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
This time, the on-page load, the call() gets called and triggers the alert on the back press. But the second time pressing on back, the alert gets called twice, on 3rd time press of a back button the alert gets triggered 4times and so on...
Here's the JSFiddle to play around.
There is some logic I seem to be missing. Any help is appreciated.
After some JSFiddling, I kinda manipulated my code to work the way I need.
the update wouldn't justify the above query but fulfilled my requirent.
Here's the code:
<div class="some" style="width:100px;height:50px;background:green;display:none;"></div>
<button class="some_btn">tada</button>
<script>
$(".some_btn").click(function() {
$(".some").css("display","block");
call();
});
function call() {
if (window.history && window.history.pushState) {
if($('.some').css('display') == 'block') {
window.history.pushState('', null, './');
$(window).on('popstate', function() {
$(".some").css("display","none");
});
} else {
}
}
}
</script>
so in the above code, the call() gets triggered every time that particular block is displayed and made the "back button" null and upon hiding the block, the back button gets enabled.
Hope this helps the one in need.