I'm making a javascript game and once the user finished the game, the user will enter their initials and hit submit. Once they hit submit, it'll redirect them to a new page (end.html). I'm not sure if I've set up my click event incorrectly or I'm using the wrong location.href. But, when I hit the submit button, it brings the user back to the start screen(index.html), instead of the end (highscore) page.
The script tag is located on the bottom of the HTML pages, tags are correctly named. I tried the DOMContentLoaded function and that didn't seem to work. If I need to provide more of my code, please let me know.
here's the js snippet
submitScore.addEventListener("click", function () {
var initials = document.getElementById("initials").value;
// calling highscore page function
endPage(initials, time);
});
function endPage(inits, scores) {
var userData = {
inits: inits,
scores: scores
};
highscores.push(userData);
localStorage.setItem("userData", JSON.stringify(highscores));
location.href = "end.html"
}
I personally have never used location.assign - have you tried location.replace()?
submitScore.addEventListener("click", function () {
var initials = document.getElementById("initials").value;
// calling highscore page function
endPage(initials, time);
});
function endPage(inits, scores) {
var userData = {
inits: inits,
scores: scores
};
highscores.push(userData);
localStorage.setItem("userData", JSON.stringify(highscores));
location.replace(`${location.origin}/end.html`);
// get base url and append 'end.html'
}
EDIT [for others confused]: Actual bug was that the button was being submitted - bravo epascarello for this code:
submitScore.addEventListener("click", function (evt) {
evt.preventDefault(); // prevent default behaviour of event
Related
I have used history.pushState() and now if the user refreshes the page then it is refreshing current URL which is not an original URL.
I tried detecting refresh page with a cookie, hidden filed but it is not working.
window.onload = function() {
document.cookie="PR=0";
var read_cookies = document.cookie;
var s = read_cookies;
s = s.substring(0, s.indexOf(';'));
if( s.includes("1"))
{
window.location.href = "https://www.google.com";
}
else{
document.cookie="PR=1";
}
loadURL();
};
function loadURL()
{
document.cookie="PR=1";
document.getElementById("visited").value="1";
var str="abc/b cd";
str=str.replace(/ /g, "-");
history.pushState({},"",str);
}
when user is refreshing the page I need original URL on that time.
This might be helpful. But you need control over the pushed url.
// this goes to your 'original' url
window.addEventListener('beforeunload', function (event) {
sessionStorage.setItem('lastPage', window.location.href)
}
// page with your pushed url
if (sessionStorage.getItem('lastPage') === 'PAGE_YOU_DONT_WANT_TO_BE_REACHABLE_DIRECTLY') {
window.location = 'PAGE_YOU_WANT'
}
I'm interested what the use case for this is. As far as my knowledge goes you can't suppress the refresh event completely.
I have a component wich manages a view that contains arcticles with games and to preventing overload of memory and spend time using a for with every article if it is open on a new window or reloads the current page (with a checkbox), I made this code, when the user clicks on an article(each one has the class "flashgame"), depending of user's choice it will go to a game and, or reload the current page, or, open in another window and play the game
this is my code :
jQuery(document).on('click', '.flashgame', function () {
console.log(this);
let denom = jQuery(this).find('.urlGame').data('denom');
let val = jQuery(this).find('.urlGame').data('val');
if (denom != "") {
let gamear = denom.toString().split(',');
let orderset: any[] = gamear;
if (orderset.length > 1) {
that.multidenoms = orderset.sort((a, b) => { return a - b; });
that.gameId = val;
console.log("modalflash is showing");
that.modalflash.show();
}
else {
that.goToFlash(val, gamear);
}
}
else {
that.goToFlash(val);
}
});
and this is the article:
but for any reason when I made this change in the project, the page has been accumulate the number of clicks, for instance :
Hard reload and the number of "clicks" starts in zero, i go to another page and then go back, the click has incremented by one, an so on.
So, what should I do?, Is there any workaround to prevent this "clicks" overload?
What I like to do is use .off before .on when rebinding event handlers.
So something like this:
jQuery(document).off('click', '.flashgame').on('click', '.flashgame', function () { ...
-I have an aspx page that has several required field validators.
-After the user clicks on the save button and the page fails the validation you can no longer do anything on the page except fill in the fields.
-Three of the fields are disabled and are filled by clicking on a button that runs a javascript function that opens a popup where the user chooses a person and return the id of the person. The javascript function triggers a server side event that fills the fields.
The problem is that the trigger is never fired because the page is invalid.
Is there any way to reset the validation when the user clicks on the button?
-The javascript function does fire and open the popup but the trigger on the page that is failed will not work.
Things I have already tried:
do a postback in the javascript function - page does not post back
CausesValidation="false" - does not work
Page_BlockSubmit = false - no effect
Page_IsValid = true - no effect
The javascript function is as follows:
function OpenStudentPopup(pDistrictId) {
var modal = PopupContainer.createPopup('modal');
var pc = new PopupContainer(modal, {
src: '/pages/popup/SearchPerson.aspx?id=' + pDistrictId,
showConfirmationWhenClosing: true,
close: function (pData) {
$("#hdnChild").val(pData);
var sse = new ServerSideEvent('tgrChild');
sse.fire();
}
});
}
Finally found the answer.
In my Javascript function I added the following code:
Page_ValidationActive = false;
This allows the trigger to be fired and resets the entire page until a user tries to save again.
//New Javascript function
function OpenStudentPopup(pDistrictId) {
Page_ValidationActive = false; //This resets the validation
var modal = PopupContainer.createPopup('modal');
var pc = new PopupContainer(modal, {
src: '/pages/popup/SearchPerson.aspx?id=' + pDistrictId,
showConfirmationWhenClosing: true,
close: function (pData) {
//if (pData == true) {
$("#hdnChild").val(pData);
var sse = new ServerSideEvent('tgrChild');
sse.fire();
//}
}
});
}
I am having a hard time with setTimeOut function .Let me show the code first.
Here is my code :-
function submitform(loginUrl, username, password) {
try {
loc = new String(window.location);
document.forms.frm_login.action = junctionUrl;
document.forms.frm_login.username.value = username;
document.forms.frm_login.password.value = password;
document.forms.frm_login.submit();
setTimeout(gotoHomePage,4000);
}
catch (e) {
alert(e.message +"submit form");
}
}
function gotoHomePage()
{
alert("test");
var url = "test.aspx";
window.location=url;
}
But here the gotoHomePage function is not at all triggered after the specified
4 seconds.
What i am doing wrong here.Please suggest .
Any help will be appreciated.
Thanks
form submission is redirecting to the result page unloading the current page. So, the timer doesn't tick.
Use ajax or set target of the form to iframe. This way, the current page doesn't unload and so timer ticks executing your timeout function.
<form target="form_output">
<!-- other inputs -->
</form>
<iframe name="form_output"></iframe>
I have made a solution for my website which includes using ajax to present the general information on the website. In doing this, I am changing the URL every time a user loads some specific content with the window.history.pushState method. However, when I press backspace or press back, the content of the old url is not loaded (however the URL is loaded).
I have tried several solutions presented on SO without any luck.
Here is an example of one of the ajax functions:
$(document).ready(function(){
$(document).on("click",".priceDeckLink",function(){
$("#hideGraphStuff").hide();
$("#giantWrapper").show();
$("#loadDeck").fadeIn("fast");
var name = $(this).text();
$.post("pages/getPriceDeckData.php",{data : name},function(data){
var $response=$(data);
var name = $response.filter('#titleDeck').text();
var data = data.split("%%%%%%%");
$("#deckInfo").html(data[0]);
$("#textContainer").html(data[1]);
$("#realTitleDeck").html(name);
$("#loadDeck").hide();
$("#hideGraphStuff").fadeIn("fast");
loadGraph();
window.history.pushState("Price Deck", "Price Deck", "?p=priceDeck&dN="+ name);
});
});
Hope you guys can help :)
pushState alone will not make your page function with back/forward. What you'd need to do is listen to onpopstate and load the contents yourself similar to what would happen on click.
var load = function (name, skipPushState) {
$("#hideGraphStuff").hide();
// pre-load, etc ...
$.post("pages/getPriceDeckData.php",{data : name}, function(data){
// on-load, etc ...
// we don't want to push the state on popstate (e.g. 'Back'), so `skipPushState`
// can be passed to prevent it
if (!skipPushState) {
// build a state for this name
var state = {name: name, page: 'Price Deck'};
window.history.pushState(state, "Price Deck", "?p=priceDeck&dN="+ name);
}
});
}
$(document).on("click", ".priceDeckLink", function() {
var name = $(this).text();
load(name);
});
$(window).on("popstate", function () {
// if the state is the page you expect, pull the name and load it.
if (history.state && "Price Deck" === history.state.page) {
load(history.state.name, true);
}
});
Note that history.state is a somewhat less supported part of the history API. If you wanted to support all pushState browsers you'd have to have another way to pull the current state on popstate, probably by parsing the URL.
It would be trivial and probably a good idea here to cache the results of the priceCheck for the name as well and pull them from the cache on back/forward instead of making more php requests.
This works for me. Very simple.
$(window).bind("popstate", function() {
window.location = location.href
});
Have same issue and the solution not working for neither
const [loadBackBtn, setLoadBackBtn] = useState(false);
useEffect(() => {
if (loadBackBtn) {
setLoadBackBtn(false);
return;
} else {
const stateQuery = router.query;
const { asPath } = router;
window.history.pushState(stateQuery, "", asPath);
},[router.query?.page]