I have the following if statement that looks for a hash on document ready (this code NEVER runs again on the page). And if there is no hash then add one using replace, so that it doesn't trigger a hashchange event.
if( window.location.hash == '' ) {
console.log('no hash');
location.replace(location.href.replace(/\/?$/, '#/section-0/page-0')); // change the url without creating a hashchange
} else {
console.log('has hash');
}
However if I visit the page with no hash, what I will see in the console is has hash and the replace will have happened... how is this possible? as that console log is in a different part of the statement. If I comment out the replace then it only falls into the first part of the if statement. How can it jump into the if statement do the replace (but ignoring the first console log) and then jump into the second part?
What you are saying doesn't make sense.
I tried to make a full example from your code:
<html>
<head>
<script type='text/javascript'>
function x()
{
if( window.location.hash == '' )
{
console.log('no hash');
location.replace(location.href.replace(/\/?$/, '#/section-0/page-0')); // change the url without creating a hashchange
alert('changed!');
}
else
{
console.log('has hash');
}
}
</script>
</head>
<body>
<button onclick="javascript:x()">test</button>
</body>
</html>
This code executes as follows when opening default:
Click button
Console no hash
Alert
Click button
Console has hash
If you put the code without function declaration inside the body (so it always executes), like this:
<html>
<body>
<script type='text/javascript'>
if( window.location.hash == '' )
{
console.log('no hash');
location.replace(location.href.replace(/\/?$/, '#/section-0/page-0')); // change the url without creating a hashchange
alert('changed!');
}
else
{
console.log('has hash');
}
</script>
</body>
</html>
It shows:
Console no hash
Alert
Related
I have an alert message that appears on the page for the first time creating a cookie on Dismiss. I created a function on page load to check if the cookie exists, do not display alert and if it does not exist display alert message. I also have another function in place to check if the pageTitle is "Test" display the alert message.
At the moment my alert message is showing even after clicking dismiss and a cookie is generated because of the second function check on pageTitle. If I remove the check on pageTitle I do get the desired result I want but the message appears on all pages when I only want it to appear with the pageTitle = Test
I am attempting to have both checks work properly with one another for example, if cookie exists do not show an alert, if it doesn't exist and the pageTitle = test show alert message
First function
$(window).on("load", function (e) {
$('.preloader').fadeOut('slow');
if (document.cookie.includes("isDismissed=true")) {
document.body.classList.add("alert.container");
} else {
document.body.classList.add("show-alert");
}
});
Second function
if("#pageTitle".indexOf("Test") !== -1) {
document.body.classList.add("show-alert");
}
Put the second code as an else if in the first function.
$(window).on("load", function(e) {
$('.preloader').fadeOut('slow');
if (document.cookie.includes("isDismissed=true")) {
document.body.classList.add("alert.container");
} else if ("#pageTitle".indexOf("Test") !== -1) {
document.body.classList.add("show-alert");
}
});
You have 2 options:
Check if the cookie exists in the second function.
if("#pageTitle".indexOf("Test") !== -1 && !document.cookie.includes("isDismissed=true")) {
document.body.classList.add("show-alert");
}
Check if if the page title includes test on the first function.
$(window).on("load", function (e) {
$('.preloader').fadeOut('slow');
if (document.cookie.includes("isDismissed=true")) {
document.body.classList.add("alert.container");
} else if ("#pageTitle".indexOf("Test") !== -1) {
document.body.classList.add("show-alert");
}
});
If both of these functions are ran on load, this is the only way to do it.
you forgot to remove the class from the class list, it will keep on adding
$(window).on("load", function (e) {
$('.preloader').fadeOut('slow');
if (document.cookie.includes("isDismissed=true")) {
$("body").removeClass("show-alert").addClass("alert.container");
} else {
$("body").removeClass("alert.container").addClass("show-alert");
}
});
so I am using a jQuery Ajax updater which uses jinja2 to determine values when a certain value is too I'm attempting to press an input which loads a url linked to flask. However I only want to go to this url once which is an issue as my updater refreshes every 0.5 seconds causing the link to be loaded multiple times.
Snippet of my updater with javascript to press button:
{% elif item['status'] == "pass" and item['api'] == "Yes" %}
<td style="color: #DAA520;">Good</td>
<input onclick="location.href = '/api';" type="hidden" id="popupbtn">
<script>
setTimeout(function () {document.getElementById("popupbtn").click();}, 500);
</script>
This is called every 0.5 seconds in index.html, I only want to press popupbtn once how can I achieve this? I was thinking I could just wait for the element to be visible in index.html and press it then, but how can I do that?
One possible solution is to use localStorage to maintain a status of the page and prevent the redirect on future clicks. In this example, "onclick" is removed from the input element and an event listener checks a stored variable to determine whether or not the redirect happens.
{% elif item['status'] == "pass" and item['api'] == "Yes" %}
<td style="color: #DAA520;">Good</td>
<input type="hidden" id="popupbtn">
<script>
// determine the status of the page
function getPageStatus() {
var pageStatus = 'initial';
if (!(Storage===undefined)) {
if (!(pageStatus===undefined)) {
pageStatus = localStorage.pageStatus
} else {
localStorage.pageStatus = 'initial';
}
}
return pageStatus;
}
// set the status of the page
function setPageStatus(newStatus) {
if (!(Storage===undefined)) {
localStorage.pageStatus = newStatus;
}
}
setTimeout(function () {
// configure an event listener and remove the "onclick" property from the <input /> element
document.getElementById("popupbtn").addEventlistener('click', function(){
var pageStatus = getPageStatus();
if (pageStatus=='initial') {
// once this has been done once, the click will no longer redirect
setPageStatus('loaded');
location.href = '/api'
} else {
alert('The button has been used.');
}
});
}, 500);
</script>
Be sure to read up on Web Storage
Beware that you have to manually control this so that if you want the button to work on a future visit to the page, you will need to reset the stored value. The above method will kill the button click until the user clears their browser.
Given that you appear to be reloading the page in the onClick event (which I'd highly recommend changing to just loading in a hidden div which would allow you to use a global or other document based mechanism), you'll have to use a query string option.
Something like this:
<input onclick="location.href = '/api?fromclick=yes';" type="hidden" id="popupbtn">
<script>
if (window.location.href.indexOf('fromclick') == -1) {
setTimeout(function () {document.getElementById("popupbtn").click();}, 500);
}
</script>
Basically, if the URL/window.location contains absolutely any variable whatsoever (past domain.com/, of course), I'd like javascript to execute something.
Currently, I have the following jQuery code which only executes when window.location contains the exact wording "#hash", but as stated before I'd like to expand the functionality for all variables.
Edit: Sorry, to clarify, by variable I mean any one of the following examples:
domain.com/#hash
domain.com/#hash2
domain.com/sub/folder
domain.com/textwithoutahash
Also, if someone knows how to do this in basic Javascript and without the need for the jQuery library, that would be an added bonus!
$(function() {
if ( window.location.href.indexOf('#hash') > -1 ) {
myfunctionhere;
}
});
See update at end re your clarification
Put the script at the end of the page, just before the closing </body>, and:
If by "variable" you mean a document fragment identifier ("hash"), then:
<script>
if (location.hash) {
callYourFunction();
}
</script>
If by "variable" you mean a query string, then
<script>
if (location.search) {
callYourFunction();
}
</script>
If by "variable" you mean a resource name, e.g., not http://domain.com but http://domain.com/page, then:
<script>
if (location.pathname && location.pathname !== "/") {
callYourFunction();
}
</script>
More on the location object on MDN.
Re your clarification:
Edit: Sorry, to clarify, by variable I mean any one of the following examples:
Those examples come down to having either hash or pathname or both, so:
<script>
if ((location.pathname && location.pathname !== "/") || location.hash) {
callYourFunction();
}
</script>
...and of course, if you also wanted to handle http://domain.com?foo=bar, then add in search as well:
<script>
if ((location.pathname && location.pathname !== "/") ||
location.search ||
location.hash) {
callYourFunction();
}
</script>
You could check if there is a hash, a pathname or a search.
Or, to simplify, you could simply use this:
if (window.location.href.split('/').filter(Boolean).length > 2) {
callYourFunction();
}
window.location.href is simply the whole URL. If there's something after the domain, it'll be shown.
This function will be triggered for the following cases:
domain.com/some/path
domain.com/#hash
domain.com/?some=variable
You could check if search property of window.location is set to something. Also, you can check the hash property:
if (window.location.search || window.location.hash) {
yourfunctionhere();
}
To invoke it without jQuery, just include it in an 'onload' script:
<script type='text/javascript'>
document.onload = function () {
if (window.location.search || window.location.hash) {
yourfunctionhere();
}
}
</script>
I am having a problem with the hashchange event in Firefox. We are using the JQuery hashchange plugin provided by Ben Alman. The code is as follows.
$(window).hashchange(function (e) {
alert("Hello");
//we want to perform a post in here.
});
var temp = "#123";
if (temp !== "") {
if (window.location.hash == temp) {
$(window).hashchange();
}
else{
window.location.hash = temp;
}
}
else {
window.location.hash = "#Home/Home";
};
Now this works fine in IE9 and Chrome, however in Firefox, I see the alert, but as soon as I click OK, the page refreshes, displays the alert again, and continues infinitely. Is there some sort of weird behaviour that Firefox uses that I am unaware of? Or is there simply some other problem that is hidden deeper?
In some browsers window.location.hash includes the # and in some don't so its better if your ignore it while comparing the hash value in your code.
Try this.
$(window).hashchange(function (e) {
alert("Hello");
//we want to perform a post in here.
});
//Remove hash from here which will be compared with window.location.hash
var temp = "123";
if (temp !== "") {
//Replace # by empty nothing
if (window.location.hash.replace('#', '') == temp) {
$(window).hashchange();
}
else{
window.location.hash = '#' + temp;//Now add the hash here
}
}
else {
window.location.hash = "#Home/Home";
};
We located the problem as occuring in MicrosoftAjax.js and found the following solution:
Firefox 6 Infinite Page Refresh With Page With Hash Tags
I'm not a programmer. I don't want to protect with a strong secure code my page. I just need one option I'm missing in my code and can't figure out how to add it.
<script language="Javascript">
<!--
var password = "lala"
var x = prompt("","")
if (x.toLowerCase() == password) {
location = "http://google.com";
}
else {
alert("Fail")
location = "http://facebook.com"
}
//-->
</script>
As you can see it's so dump but I need it. When I press Cancel button instead of writing true or false text, website still opens. I want to include in this script cancel button function (control it, you know) whitch would redirect to another website if press on it (as it is with true or false functions). I don't want to creat a special button or an input for it.
Update: I would like to include this script in a page which i am redirecting to. Could anyone tell me:
1. How can i modify this script to make it work only once?
2. Is it anything to do with browser's cookies?
p.s. Done :)
If the user presses cancel, prompt will return null. So do like this:
if(x == null) // Cancel
{
alert('Cancel');
}
else if (x.toLowerCase() == password) { // Correct password
location = "http://google.com";
}
else { // Wrong password
alert("Fail")
location = "http://facebook.com"
}
However, I'm not sure if all browsers will return null when the user presses cancel. (I have tested in Opera)
Try
var x = prompt("","");
if( x == null || x == '')
return;
if (x.toLowerCase() == password) {
location = "http://google.com";
}
else {
alert("Fail")
location = "http://facebook.com"
}
To redirect your browser to a URL use following snippet in your Javascript:
top.location.href = "http://google.com";