I am using
window.history.pushState
and popstate functions for getting the previous page url's while clicking on back button of browser and i want to reload the page every popstate function calls.
My code is..
function refresh_results() {
page_link = $("#form").serialize();
if(page_link!=window.location){
window.history.pushState({path:pageurl},'',pageurl);
}
}
In popstate function
$(document).ready(function($) {
var popped = ('state' in window.history && window.history.state !== null), initialURL = location.href;
if (window.history && window.history.pushState) {
$(window).bind('popstate', function(e) {
var initialPop = !popped && location.href == initialURL;
popped = true;
if (initialPop) return;
pageurl = location;
console.log(pageurl);
window.location = location.href;
//window.location = pageurl;
return e.preventDefault();
});
}
});
But, for every time when i click on back button page is refreshing continuosly in chrome,but in firefox it's fine.
Can u suggest me how my functionlity will workable, and suggest me if i am missing anything
Related
Hello i have this code which works for redirect back
Redirect Users leaving your site - Javascript back button hack
<?php
$javascript = <<<DOC
<script>
var ref = document.referrer;
var siteurl = "YOUR URL HERE";//if you have www, then use www. http://www.yoursite.com
if (ref.indexOf(siteurl)!= -1){
}
else{
(function(window, location) {
history.replaceState(null, document.title, location.pathname+"#!/auth");
history.pushState(null, document.title, location.pathname);
window.addEventListener("popstate", function() {
if(location.hash === "#!/auth") {
history.replaceState(null, document.title, location.pathname);
setTimeout(function(){
location.replace("http://www.blackhatworld.com/");
},0);
}
}, false);
}(window, location));
}
</script>
DOC;
echo $javascript;
?>
I want to add it a counter that will only redirect after 3 clicks on back.
How to do it?
try this javascript code :
<button id="button">Click Back 3 Times </button>
<script>
var counter = 0;
$("#button").click(function () {
counter++;
if (counter == 3) {
window.history.back();
}
});
</script>
This code also works but i need to add the counter
this code which works for redirect back Redirect Users leaving your site - Javascript back button hack:
<script>
// managage back button click (and backspace)
var count = 0; // needed for safari
window.onload = function () {
if (typeof history.pushState === "function") {
history.pushState("back", null, null);
window.onpopstate = function () {
history.pushState('back', null, null);
if(count == 1){window.location = 'http://google.co.il';}
};
}
}
setTimeout(function(){count = 1;},200);
</script>
Looking for a code to make redirect to page after clicking browser back button on the 3rd time... first 2 clicks should remain at the page
I have a long form, that's a sliding page form so that it is broken up into parts for the user.
I do my error checking through jQuery, here is the code:
$("input.next").click(function(e) {
e.preventDefault();
var stage = ((($("#container").position().left) / 950) * -1) + 1;
var thispage = $(this).closest("div.page");
var errors = false;
var isFinal = $(this).hasClass("send");
thispage.find("input.txt").each(function () {
if(($(this).val() == "") && (!$(this).hasClass("optional"))) {
$(this).css("background","#FFE5E5");
errors = true;
} else {
$(this).css("background","#E5FFEA");
}
});
thispage.find(".checkbox").each(function () {
if(!$(this).is(':checked')) errors = true;
});
if(thispage.find("#profileimage").val() == "") errors = true;
thispage.find("textarea.txt").each(function () {
if(($(this).val() == "") && (!$(this).hasClass("optional"))) {
$(this).css("background","#FFE5E5");
errors = true;
} else {
$(this).css("background","#E5FFEA");
}
});
if(!errors) {
// if no errors, slide to next page.
if(!isFinal) {
thispage.find("div.errormessage").fadeOut(50);
$("#container").animate({left: "-=950px"}, 800, function () {
$("ul#stages li").removeClass("active");
$("ul#stages li.stage"+stage).addClass("active");
console.log("Stage: " + stage);
});
}
} else {
thispage.find("div.errormessage").fadeIn(100);
}
console.log("isFinal: " + isFinal);
console.log("Errors: " + errors);
if((isFinal) && (!errors)) {
console.log("submitting form...");
$("#enrolform").submit(); }
});
However when the div.next.send button is pressed, it has a name of sendapplication and in my PHP code I am using:
if(isset($_POST['sendapplication'])) {
..To check whether the entire form was submitted or not. The reason I need to do this is because I also have a 'save' feature of the form, which allows the user to save the data and come back later.
The problem is when the user clicks 'sendapplication' button I don't get that through in the $_POST or $_REQUEST variables. And I think the reason why is because it's the jQuery script that's sending it, and not the button. The button is suppressed because of the e.preventDefault() line.
How can I check that that particular button was pressed? is there someway I can manipulate the .submit() function?
You can add following code into the click() method:
var self= $(this),
form = self.closest(form),
tempElement = $("<input type='hidden'/>");
// clone the important parts of the button used to submit the form.
tempElement
.attr("name", this.name)
.val(self.val())
.appendTo(form);
See jQuery submit() doesn't include submitted button for more details
Anthony Grist's comment is probably a lot better solution to this :)
I am submitting some data to my database then reloading the same page as the user was just on, I was wondering if there is a way to remember the scroll position the user was just on?
I realized that I had missed the important part of submitting, so, I decided to tweak the code to store the cookie on click event instead of the original way of storing it while scrolling.
Here's a jquery way of doing it:
jsfiddle ( Just add /show at the end of the url if you want to view it outside the frames )
Very importantly, you'll need the jquery cookie plugin.
jQuery:
// When document is ready...
$(document).ready(function() {
// If cookie is set, scroll to the position saved in the cookie.
if ( $.cookie("scroll") !== null ) {
$(document).scrollTop( $.cookie("scroll") );
}
// When a button is clicked...
$('#submit').on("click", function() {
// Set a cookie that holds the scroll position.
$.cookie("scroll", $(document).scrollTop() );
});
});
Here's still the code from the original answer:
jsfiddle
jQuery:
// When document is ready...
$(document).ready(function() {
// If cookie is set, scroll to the position saved in the cookie.
if ( $.cookie("scroll") !== null ) {
$(document).scrollTop( $.cookie("scroll") );
}
// When scrolling happens....
$(window).on("scroll", function() {
// Set a cookie that holds the scroll position.
$.cookie("scroll", $(document).scrollTop() );
});
});
#Cody's answer reminded me of something important.
I only made it to check and scroll to the position vertically.
(1) Solution 1:
First, get the scroll position by JavaScript when clicking the submit button.
Second, include this scroll position value in the data submitted to PHP page.
Third, PHP code should write back this value into generated HTML as a JS variable:
<script>
var Scroll_Pos = <?php echo $Scroll_Pos; ?>;
</script>
Fourth, use JS to scroll to position specified by the JS variable 'Scroll_Pos'
(2) Solution 2:
Save the position in cookie, then use JS to scroll to the saved position when page reloaded.
Store the position in an hidden field.
<form id="myform">
<!--Bunch of inputs-->
</form>
than with jQuery store the scrollTop and scrollLeft
$("form#myform").submit(function(){
$(this).append("<input type='hidden' name='scrollTop' value='"+$(document).scrollTop()+"'>");
$(this).append("<input type='hidden' name='scrollLeft' value='"+$(document).scrollLeft()+"'>");
});
Than on next reload do a redirect or print them with PHP
$(document).ready(function(){
<?php
if(isset($_REQUEST["scrollTop"]) && isset($_REQUEST["scrollLeft"]))
echo "window.scrollTo(".$_REQUEST["scrollLeft"].",".$_REQUEST["scrollTop"].")";
?>
});
Well, if you use _targets in your code you can save that.
Or, you can do an ajax request to get the window.height.
document.body.offsetHeight;
Then drop them back, give the variable to javascript and move the page for them.
To Remember Scroll all pages Use this code
$(document).ready(function (e) {
let UrlsObj = localStorage.getItem('rememberScroll');
let ParseUrlsObj = JSON.parse(UrlsObj);
let windowUrl = window.location.href;
if (ParseUrlsObj == null) {
return false;
}
ParseUrlsObj.forEach(function (el) {
if (el.url === windowUrl) {
let getPos = el.scroll;
$(window).scrollTop(getPos);
}
});
});
function RememberScrollPage(scrollPos) {
let UrlsObj = localStorage.getItem('rememberScroll');
let urlsArr = JSON.parse(UrlsObj);
if (urlsArr == null) {
urlsArr = [];
}
if (urlsArr.length == 0) {
urlsArr = [];
}
let urlWindow = window.location.href;
let urlScroll = scrollPos;
let urlObj = {url: urlWindow, scroll: scrollPos};
let matchedUrl = false;
let matchedIndex = 0;
if (urlsArr.length != 0) {
urlsArr.forEach(function (el, index) {
if (el.url === urlWindow) {
matchedUrl = true;
matchedIndex = index;
}
});
if (matchedUrl === true) {
urlsArr[matchedIndex].scroll = urlScroll;
} else {
urlsArr.push(urlObj);
}
} else {
urlsArr.push(urlObj);
}
localStorage.setItem('rememberScroll', JSON.stringify(urlsArr));
}
$(window).scroll(function (event) {
let topScroll = $(window).scrollTop();
console.log('Scrolling', topScroll);
RememberScrollPage(topScroll);
});
I had major problems with cookie javascript libraries, most cookie libraries could not load fast enough before i needed to scroll in the onload event. so I went for the modern html5 browser way of handling this. it stores the last scroll position in the client web browser itself, and then on reload of the page reads the setting from the browser back to the last scroll position.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
if (localStorage.getItem("my_app_name_here-quote-scroll") != null) {
$(window).scrollTop(localStorage.getItem("my_app_name_here-quote-scroll"));
}
$(window).on("scroll", function() {
localStorage.setItem("my_app_name_here-quote-scroll", $(window).scrollTop());
});
});
</script>
I tackle this via using window.pageYOffset . I saved value using event listener or you can directly call window.pageYOffset. In my case I required listener so it is something like this:
window.addEventListener('scroll', function() {
document.getElementById('showScroll').innerHTML = window.pageYOffset + 'px';
})
And I save latest scroll position in localstorage. So when next time user comes I just check if any scroll value available via localstorage if yes then scroll via window.scrollTo(0,myScrollPos)
sessionStorage.setItem("VScroll", $(document).scrollTop());
var scroll_y = sessionStorage.getItem("VScroll");
setTimeout(function() {
$(document).scrollTop(scroll_y);
}, 300);
l am using this code
var exitPop = false;
var nonFire = false;
window.onbeforeunload = function () {
if(!exitPop){
exitPop=true;
return 'Wait! YOU ARE TODAYS WINNER!';
}
};
setInterval(function(){
if(exitPop && !nonFire){
nonFire = true;
window.location.href = 'http://google.com';
}
}, 200);
but its also execute on clicking any html redirect button on page.. i want it execute only if someone close browser and it should support all browsers.
i need to add this at only one link in my site how can id do? i mean i am using this code for redirect
<script type="text/javascript">
window.fbAsyncInit = function() {
FB.Event.subscribe('comment.create',
function (response) {
window.location = "http://domain.com";
});
FB.Event.subscribe('comments.remove',
function (response) {
window.location = "http://domain.com";
});
};
(function() {
var e = document.createElement('script');
e.async = true;
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
//]]>
</script>
so i want exit function do not execute for this.. so how do integrate this
I haven't tested it but you should be able to attach a 'click' event to every link on the page, which should set a global variable such as
linkClicked = true;
You can then check that variable in the unload event
if (!linkClicked) // variable is false so they must not have clicked on a link
{
// Some annoying message here
}
Disclaimer: this is pretty much pseudo code, it's not a copy+paste solution.
window.onbeforeunload does not distinguish between links, back/forward buttons, exit buttons or anything else. If fires when you leave the page, regardless of how you leave the page.
I'm setting the URL after the hashmark with a jquery click event. The URL is getting set properly but when I use the browsers back button it doesn't take me to the previous page.
Before my click event the URL looks like this:
http://example.com/menu.php?home
My click event looks like this:
$('#visits').click(function() {
$('#main').load("visits.php?type=1&view=1", function () {
location.href = "#visits";
});
return false;
});
My URL now looks like this:
http://example.com/menu.php?home#visits
It seems as though menu.php doesn't get called with the browsers back button.
Any idea what I'm missing?
You could code something like this:
var _hash = '';
function myHashChangeCallback(hash) {
// handle hash change
// load some page using ajax, etc
}
function hashCheck() {
var hash = window.location.hash;
if (hash != _hash) {
_hash = hash;
myHashChangeCallback(hash);
}
}
setInterval(hashCheck, 100);
Use the onhashchange event of the window, to check if the hash changes. This is getting called when you hit the back Button of your browser.
$(window).bind('hashchange',function() {
if (location.hash != '#visits') {
//Code to revert the changes on the page
}
}
Older versions of IE don't support hashchange, so you have to cheat by using setInterval to poll a few times a second and check if it's changed.
if($.browser.msie && $.browser.version < 7){
setInterval(function(){
if(window.location.hash != window.lastHash){
hashChangeHandler();
window.lastHash = window.location.hash;
}
}, 100);
}
else{
$(window).bind('hashchange',function() {
if (location.hash != '#visits') {
hashChangeHandler();
}
}
}