I'm currently using window.location.href.indexOf in my current project. I've noticed that it doesn't seem to work properly. For example this code that I made.
$(document).ready(function () {
//Show Sign Up drawer if user clicks on referral link
//It will show the Sign Up drawer once the word "referral" is found in the URL
if (window.location.href.indexOf("?referral") > -1) {
console.log('Sign Up Drawer');
$(".header-form-container.signup").addClass("show"),
}
});
This code what it does is to add a class in an element if the word referral is found in the URL. The add class being inserted will then slide a sign up drawer. Here is what happened during testing.
In my first test, I tried inserting the word referral in the url. After typing in the word and pressing the Enter key, the javascript I'm trying to run did not trigger
But after refreshing the browser or inserting the word again it now works. It currently shows the sign up section.
How can I ensure that the code window.location.href.indexOf will work in the first try or without refreshing the browser again. The website is built on a angular framework
If you only change the URL after the # sign, the page won't reload, since you're only changing the anchor part of the URL.
Your code wrapped in $(document).ready(function () { ... will only run once, when the page loads.
What you want to do is to add a listener for the route change event and run your code in that handler, something like this:
$rootScope.$on("$routeChangeSuccess", function() {
if (window.location.href.indexOf("?referral") > -1) {
console.log('Sign Up Drawer');
$(".header-form-container.signup").addClass("show"),
}
});
It does not work because your script (e.g: main.js) is executed only one time when the page load.
You might want to use window.historyto manipulate the browser history. You can update the query string with pushState()
History API
Hope it helps.
Related
I'm working on a web application which is a traditional aspx (asp.net) web forms app but has had some angular 6 apps incorporated into it.
I've been tasked with fixing a bug that causes the browser to refresh when clicking on an anchor element with a href="#".
I'm not sure what's causing the whole page to reload.
Strangely when I open dev tools in Chrome, choose the network tab and select disable cache the page only refreshes the first time I click a link and any other subsequent clicks work fine. This might be to do with the fact that after the first time I click it the browser url now contains the # at the end of it.
I know this seems a bit random but I wondered whether anyone had any theories on what may cause the reload in the first place.
It's hard to tell what could be causing this without seeing any code. The most common solution I've used when I get this behavior is a prevent default. You can do something like
<a href="#" (click)="$event.preventDefault()">
Or if you already have a click event then pass in $event as a parameter to your function then preventDefault in the function you are calling. This would look like:
Html
<a href="#" (click)="someFunc($event)">
and in your ts:
someFunc(event) {
event.preventDefault();
// rest of your code here
}
This answer is related to the question and it's the first one that comes up in Google so I hope this is useful.
I have some external web components that use regular anchor tags with hrefs that point to routes in my angular app. Clicking the href causes a full page reload. This is because I'm not using routerLink - but, in my case, I can't.
So, my work around is:
#HostListener('window:click', ['$event'])
onClick(e: any) {
const path = e.composedPath() as Array<any>;
const firstAnchor = path.find(p => p.tagName.toLowerCase() === 'a');
if (firstAnchor && !firstAnchor.hasAttribute('routerlink')) {
const href = firstAnchor.getAttribute('href');
this.router.navigateByUrl(href);
e.preventDefault();
}
}
Depending on your application, you might need to make some other checks e.g. is the target _blank, is it an external url etc.
change your a tag code as below
A Tag
this will invoke yourClickEvent(); without page reload
check the stackblitz here stackblitz
If you don't want to reload the page use $event.preventDefault()
<a href="#" (click)="$event.preventDefault()">
Try using debug tools to select the element, then click Event Listeners and then the Click event to see what is listening. Perhaps you can track it down that way.
You could also simply paste this into the console to trigger a break, and then click any of the offending elements:
['unload', 'beforeunload'].forEach(function (evName) {
window.addEventListener(evName, function () {
debugger; // Chance to check everything right before the redirect occurs
});
});
source: Break when window.location changes?
As you are using angular routes, try to use this notation:
<a [routerLink]="['./']" fragment="Test">
As explain by this comment: https://stackoverflow.com/a/38159597/4916355
use href="javascript:void(0);"
The reason you’d want to do this with the href of a link is that normally, a javascript: URL will redirect the browser to a plain text version of the result of evaluating that JavaScript. But if the result is undefined, then the browser stays on the same page. void(0) is just a short and simple script that evaluates to undefined.
Use [routerLink] instead of using href = "", and use click event to call your calling method in the typescript file.
ex:
// downloading the file based on file name
<a [routerLink]="'file://' + 'path'" (click)="downloadFile(templateDocument.fileName)">{{downloadDocuments.fileName}}</a>
Since you have mentioned the web app is asp.net webforms, can you please let us know
Whether the link is asp.net hyperlink control. If so,
AutoEventWireUp could cause the link to be automatically submitted:
Please have a look at this link
If you do have asp.net server controls on the page, then you could disable by setting
#Page AutoEventWireup="false"
For the entire project, this can be disabled by setting in web.config:
We want to have a back button in our site
but history.back in javascript does not help us.
We need this function only run on the site and if the user comes from other site, clicking the return button on the previous site should not return.
In fact, we want a return button to run on our site only.
my code is
<i class="fas fa-arrow-left"></i><span class="btn-text">Back</span>
This only works for your own made back button and won't work with the browser back button
There is two ways to achieve that: a simple but not always reliable method and a complex one but always good.
1- The simple method
You use document.referrer and ensure the domain is yours before calling history.back().
2- The complex method
You could register a JavaScript function on page load to get the first URL the internaut land which you could store using history.pushState. Before calling the back function, you could ensure this is not that page. Though, this idea is not complete as the user could probably have landed on this page twice. i.e. Home->Product->Home. I'll let you search for further code that would let you counter this problem.
This code checks the history of back button of the browser on its click event:
$('#backbtn').click(function () {
if (document.referrer.includes(window.location.hostname)) {
window.history.back();
} else {
window.location.href = "/your/path";
}
});
I'm working on a group project for a class, and we have a webpage that is split into different tabs, so it is only one webpage, but appears to be different pages using Jquery so the page doesn't have to reload when switching between tabs. The problem I am having is that one of the tabs has a form to get information from the user, then after the user clicks the submit button, the info is sent to the database using php, causing the page to reload. Then depending on if the information was successfully sent to the database, there will be either "success" or "invalid" appended to the end of the URL. If the user submits this form, we want them to automatically come back to this tab on the reload, and I have tried doing this by using a script like this:
<script>
document.getElementById("baseTab").click();
window.onload = function() {
var theurl = document.location.href;
if (theurl.includes("success") || theurl.includes("invalid") {
document.getElementById("infoTab").click();
}
};
</script>
The baseTab is the tab we want to load whenever someone first loads the webpage, unless they have just submitted the form on the infoTab page. This code structure works on a simple test webpage I run on my computer, but when I try to push it to our project repository, it will only do the "baseTab".click, and not click the "infoTab" button even if theurl includes "success" or "invalid". I tried doing it without the window.onload(), but that doesn't work either. Also, if I do
if (theurl.includes("success") || theurl.includes("invalid") {
document.getElementById("infoTab").click();
}
else {
document.getElementById("baseTab").click();
}
then neither of the buttons get clicked. If their is an easier way to do this or you see where I am going wrong, any help would be appreciated. Thanks!
hi here is the problem: my url is like this
http://somesite.com?theSearch=someword&a=b&c=d
on this page search results are displayed and on this page i have put the functionality of ajax search i.e. the results are updated without the page reload but the problem is if the user clicks on any link on the page and then presses the back button he results on the page page with the search results of "someword" not the new word typed (i mean the word for which the ajax results were updated) the client complains it and i need to fix it anyone have a solution?
i am using jQuery
You can't change the location.href without a new load. What you can do is set the hash.
Every time you make a search change the hash
function doSearch(searchword) {
location.hash = searchword;
//your search code
}
Now the hash will refer to the latest search. And then add this code to "override" the get parameter ?theSearch=.
$(document).ready(function() {
if(location.hash.length>0) {
doSearch(location.hash);
}
});
Its not a nice solution since you will load 2 search results, but it will work.
You can try Sammy. It utilizes the URL hash (#) so you can create single page applications that still respond to the back button in your browser, just like facebook. And it runs on jQuery.
Is there a way to make the user's back button on their browser, call a javascript function instead of going back a page?
You can't override the behaviour that if a user follows a link to your page, clicking Back will take them off it again.
But you can make JavaScript actions on your page add entries into the history as though they were clicks to new pages, and control what happens with Back and Forward in the context of those clicks.
There are JavaScript libraries to help with this, with Really Simple History being a popular example.
yes, you can. Use this js:
(function(window, location) {
history.replaceState(null, document.title, location.pathname+"#!/stealingyourhistory");
history.pushState(null, document.title, location.pathname);
window.addEventListener("popstate", function() {
if(location.hash === "#!/stealingyourhistory") {
history.replaceState(null, document.title, location.pathname);
setTimeout(function(){
location.replace("http://www.programadoresweb.net/");
},0);
}
}, false);
}(window, location));
That will redirect your back button to the location.replace you specify
I think this will do the trick.
you can write your custom code to execute on browser back button click inside onpopstate function.
This works in HTML5.
window.onpopstate = function() {
alert("clicked back button");
}; history.pushState({}, '');
I assume you wish to create a one-page application that doesn't reload the website as the user navigates, and hence you want to negate the back button's native functionality and replace it with your own. This can also be useful in mobile web-apps where using the back button inside apps is common to close an in-app window for example. To achieve this without a library, you need to:
1st. Throughout your application modify the window's location.hash instead of the location.href (which is what tags will do by default). For example, your buttons could fire on click events that modify the location.hash like this:
button.addEventListener('click', function (event) {
// Prevent default behavior on <a> tags
event.preventDefault()
// Update how the application looks like
someFunction()
// Update the page's address without causing a reload
window.location.hash = '#page2'
})
Do this with every button or tag you have that would otherwise redirect to a different page and cause a reload.
2nd. Load this code so that you can run a function every time the page history changes (both back and forward). Instead of the switch that I used in this example, you can use an if and check for other states, even states and variables not related to location.hash. You can also replace any conditional altogether and just run a function every time the history changes.
window.onpopstate = function() {
switch(location.hash) {
case '#home':
backFromHome()
break
case '#login':
backFromLogin()
break
default:
defaultBackAnimation()
}
}
This will work until the user reaches the first page they opened from your website, then it will go back to new tab, or whatever website they were in before. This can't be prevented and the teams that develop browsers are patching hacks that allow this, if a user wants to exit your website by going back, they expect the browser to do that.
If you are creating a one-page web application, where your html body has different sections and you want to nevigate through back button to the previous section you were. This answer will help you.
Where your website sections are differentiated by #. Such as:
your-web-address.com/#section-name
Just follow a few steps:
Add a class and a id in every section in you html body. Here it is ".section"
<section class="section" id="section-name">...</section>
Add two CSS class in your linked css (e.g., style.css) file to your html (e.g., index.html) file such:
.section .hide {
display: none;
}
.section .active{
dislplay: block;
}
Add this JavaScript function in you linked .js (e.g., main.js) file to your html file.
window.onpopstate = function () {
if (location.hash !== "") {
const hash = location.hash;
// Deactivating existing active 'section'
document.querySelector(".section.active").classList.add("hide");
document.querySelector(".section.active").classList.remove("active");
// Activating new 'section'
document.querySelector(hash).classList.add("active");
document.querySelector(hash).classList.remove("hide");
}
}