<script> function applyBeforeunload() { $(window).on('beforeunload', function() { $('body').hide(); $(window).scrollTop(0); }); } applyBeforeunload(); $(document).on('click', '[samepage]', function() { $(window).off('beforeunload'); setTimeout(applyBeforeunload, 1000); }); </script>