Is there a way to automatically change the hash url with jQuery? - javascript

I'm looking for a way to change the hash url automatically. (no page reload)
The reason I want it is this:
I'm using a pop login / registration form that only initially opens the login portion. You can only get to the registration portion after clicking the login. So, when the user clicks the http://website.com/#modal-login from a certain link, I'd want it to redirect to http://website.com/#register.
Currently it is directly going to the #register. Is there a way to change the hash url after user clicks on login?

No need to use jQuery
document.getElementById("modal-login").onClick = function () {
window.location.hash = "register";
}
For example, try pasting this into your browser's JavaScrtipt console, then click on your question text.
document.getElementById("question").onclick = function() {
window.location.hash = "footer";
}
If you really want to use jQuery for some reason
$('#modal-login').click(function(event) {
event.preventDefault();
window.location.hash = "register";
});
Edit:
Your question isn't about hash locations in general, but how this modal plugin that you're using works. The following was determined by reading the source to the plugin, found here:
http://demo.pressapps.co/plugins/wp-content/plugins/pressapps-modal-login/js/modal-login.js?ver=1.0.0
http://demo.pressapps.co/plugins/wp-content/plugins/pressapps-modal-login/js/modal.js?ver=1.0.0
Here's what you need to execute to get your desired behavior
$('.your-register-button-class').click(function(e) {
/* We expect plugin's click handler to fire in addition to this one. */
$(".modal-login-nav[href='#register']").click();
});
I'm assuming that the element with .your-register-button-class also has attribute data-toggle="ml-modal".

Related

How to detect redirection to the same address when using hash navigation?

This question is sort of what i'm thinking, but has no answers.
I have successfully implemented hash navigation in my application using the following code:
$(window).on('hashchange', function () {
loadContent(location.hash.slice(1));
}).trigger('hashchange');
I use this event to download partial HTML content from the server via Ajax, and it gets called when the browser detects a change on the hash in the address bar. The addresses looks like this:
https://www.mywebsite.com/#/account/login
The problem is, when the link is the same it does not fire the hashchange event (for obvious reasons). I need to call the function loadContent to refresh the page.
For example, before I implemented hash navigation, if the user wanted to discard all the changes he made to the page, he simply clicks the same link in the system menu, or click the address bar and hit enter. Then, the browser will redirect to the same page and drop all the changes.
But now, I can't detect that. What can I do to detect those commands and call my loadContent(location.hash.slice(1)); function?
After some research, I come to conclusion that there's no way to do that. I found this question that is very close to mine, but also no useful answer, other than handling the "onclick" event on every link on the site. Not a very beautiful solution - and does not solve the functionality of hitting enter on the address bar.
I ended up with a different approach. Definitely does not solve the way I wanted, however I think that it's more elegant from code perspective and practical from user perspective. I created a keyboard shortcut to refresh the page:
function doc_keyUp(e) {
if (e.altKey && e.keyCode === 82) { // ALT + R
if (confirm("Discard changes and refresh the page?")) {
loadContent(location.hash.slice(1));
}
return false;
}
}
document.addEventListener('keyup', doc_keyUp, false);
It may a simple approach, but what if you store your current hash in a property and afterwards register a click event and check if the hash is still the same?
Here is an (untested) example. But you should get the idea.
var storedHash = document.location.hash;
// You may add a data attribute to corresponding links to not
// catch all 'a'-tags (i.e. document.querySelectorAll('a[data-nav=true]'))
var links = document.querySelectorAll('a');
for (var i in links) {
if (!links.hasOwnProperty(i)) {
continue;
}
links[i].addEventListener('click', function() {
if (document.location.hash === storedHash) {
// Here comes your logic
}
});
}

Javascript - Get URL being navigated to

Is there any way to use JavaScript's OnUnload() function to find out which URL the user is navigating away to?
For example, if my code is in page1.html, and the user clicks a link to http://example.com, is there any way for JavaScript code present in page1.html, to retrieve the URL "http://example.com" and display/store it before the page unloads?
I am able to do this if I invoke a function through my link by using its OnClick, but I cannot find a way to do this otherwise. (I can post my code for that if needed, but it does meet my business requirement)
EDIT : This looks to be impossible, since my business requirement demands that I do not make any change to the content of the page, excepting the adding in of a javascript file where this code is present.
Ignore onBeforeUnload/onUnload, you don't need that. You can do it with a simple click handler like this:
$('a').on('click', function(e)
{
e.preventDefault();
var destinationLink = $(this).attr('href');
$.post('/your/analytics/url', {link:destinationLink}, function()
{
// Success
window.location.href = destinationLink;
});
});
This will stop any link from working until it's been submitted to your analytics so it's not ideal - you need to make sure what ever is receiving the data does so as quickly as possible.
You could replace the current url of the clicked link.
That will allow you to call your server to do the check of the clicked url, and then redirect it.
The code bellow change the url of the clicked link only for a couple of microseconds
$("a").on("click",function(e){
// Save the current link
var h = this.href;
//Change the link of the current a
this.href = "http://www.example1.com/redirect.php?url="+encodeURI(h);
// replace the href with the original value on the next stack
setTimeout((function(my_link){
return function(){
my_link.href = h;
};
})(this),0);
});
my link

perform href before onClick

I've the following link:
I
And this use the following javascript:
function showGallery(){
if(window.location.hash) {
$('#gallery').fadeIn('fast');
var hash = window.location.hash.substring(1);
alert(hash);
} else {
}
}
So it only show the gallery when in the URL is a hashtag. But when i click on the link, nothing happens. When i click it twice, the gallery fade in.
So the link first make the javascript, and i doesn't work 'cause there is no hashtag in the URL and after that, it perform the href and insert the Hashtag in the URL.
How can i do that?
My Target:
When i click on a link, it open a gallery. To know which gallery i must open, i insert in the URL a Hashtag. Here i want to display the HDR album. And i also want, if my site get opend with a hashtag, it should display the gallery.!
Is there also a another, easier or cleaner way to make it?
Hope you understand what i want.
For modern browsers, you can bind your Javascript code to the onhashchange event. Links will be without Javascript:
I
And the Javascript is run whenever the hash has changed:
function locationHashChanged() {
if (location.hash === "#HDR") {
$('#gallery').fadeIn('fast');
}
}
window.onhashchange = locationHashChanged;
Have you tried a setTimeout call to delay the onclick event?
Like this:
I
You can simplify this quite considerably, it is not good practice to use the href for other things than pure navigation.
<a onClick="showGallery('HDR')">I</a>
And then:
function showGallery(name){
if(name) {
$('#gallery').fadeIn('fast');
alert(name);
} else {
}
}
If you want to run showGallery() without following the link, the correct code is this:
I
By keeping the href the user still sees the destination in the status bar and navigation still works for clients without Javascript (i.e. Google). By returning false in the event handler, you prevent the browser from following the link.
In showGallery(), you can then show the gallery and add '#HDR' to the location.hash.
You don't need to verify the window's hash, because on first click you don't have any hash in the address bar. The functionality will only apply on the second click.
What you can do is this:
gallery 1
function showGallery(galid){
var linkhash = $('#' + galid).attr('href').substring(1);
alert(linkhash);
$('#gallery' + linkhash).fadeIn('fast');
}

Executing JQuery after page load only after clicking a specific link

I have a link in my app that when clicked, leads to another page. I want to execute some JQuery on this new page after it loads, but only if that specific link is clicked to get to the page.
I have this JQuery:
$('#new_to_topics').click(function(){
$(document).ready(function() {
$('#topic_guidelines').slideDown('normal');
$('#topic_guidelines').addClass('on');
});
});
where #new_to_topics is the id of the link that leads to the new page and
$('#topic_guidelines').slideDown('normal');
$('#topic_guidelines').addClass('on');
is the JQuery code I want to execute on that new page. However, this does not work. How should I do this?
You could pass a location hash to the new page, and then conditionally run some javascript based on that hash.
If my link was to mynewpage.html#fromXlink (this would show in the address bar)
My javascript on mynewpage.html could be:
$(document).ready(function() {
if (location.hash == '#fromXlink') {
$('#topic_guidelines').slideDown('normal');
$('#topic_guidelines').addClass('on');
}
});
You could add a variable to the query string i.e. somepage.aspx?fromthislink=true
and then pick that up in jquery.
This shows how
If it cam from that link then fire off your jquery.
You can use window.name to pass data to the target page (although I would prefer passing data in the hash, if possible).

Javascript : Change the function of the browser's back button

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");
}
}

Categories