how to change content using id from hash url? - javascript

I'm using
var integer = window.location.hash.match(/\d+/) | 0;
alert(integer);
to get id from the hash url but when i use back button after changing the url after ajax call.
It doesn't reflect any change, basically page remains in same state and only the url changes.
so, what i want to know is that how to change the content when i use back button.
Or simply show the integer in alert box when i use back button that's it.
e.g.
http://test.php/#1
show 1 when i get to that page using back button
http://test.php#2
show 2 when i get to that page using back button
http://test.php
show 0 when i get to that page using back button

You need to catch the window.onhashchange event, or use HTML5's history.pushState() methods.
Or just use the jQuery history plugin.

You need to handle the hashchange event of window. Something like:
window.onhashchange = function() {
// Update the page
};
Or you can use addEventListener and attachEvent. Be warned, though, it doesn't work in IE7 or earlier! For earlier IE compatibility, you need a hack like this one.

Related

Add to browser History without changing current URL

I have a 3 step signup process where each step is shown on the page using javascript without a page refresh. What I am trying to do now is add a back reference to what step the user was on so if they click the browser back button they will not lose all of their progress.
So for example, as the user navigates from Step 2 to Step 3 the URL stays at www.example.com. The user then clicks the browser back button. The URL should now be www.example.com?step-2.
I'm thinking that I will somehow need to use the History API to accomplish this but if I use window.history.pushState(null, null, 'www.example.com?step-2'), the current URL would be changed as well.
How would I accomplish adding to the history without changing the current URL?
If your objective is to not change the URL, but to still allow back and forth history state changes, your best bet would be to utilize the window's hashchange event listener. This would of course utilize hash references within the URL, but the base URL won't change:
function locationHashChanged() {
if (location.hash === '#step-2') {
// Do something here
}
}
window.onhashchange = locationHashChanged;
For further info on this, refer to official documentation:
https://developer.mozilla.org/en-US/docs/Web/API/Window/hashchange_event

CKEditor restore element / undo all changes

Is there a way to restore the original content / undo all changes of an element that had become an Inline-CKEditor?
There does not seem to exist a build-in function for that, see for example this ticket.
Some propose workarounds like a button with onclick javascript event, which reloads a page. Or saving the initial data inside of the editor and use javascript to replace the content with that on an event again. (Here is a thread concerning your request with the mentioned tricks.)
My solution:
After instantiating CKEditor I save the initial content with CKEDITOR.editor1.getData() to a custom variable CKEDITOR.editor1.firstSnapshot. Later when I want to restore it I write it back with CKEDITOR.editor1.setData(CKEDITOR.editor1.firstSnapshot);
At first I wanted to use getSnapshot() but however it always returned true, so that didn't work for me.
I want to share a different approach to problem. I'm using inline CKEditor, and have on blur event (when user unfocus ckeditor) which prompt option for saving content or rollback changes.
For case of rollback - i just put checkDirty() - function which check if instance has changes - in while loop, so undo executes in each true until ckeditor will be restored to initial state.
Code will look like this:
CKEDITOR.instances["editor"].on('blur', function (evt) {
if (confirm("Do you wish to roll back changes ?")) {
while (CKEDITOR.instances["editor"].checkDirty()) {
CKEDITOR.instances["editor"].execCommand('undo');
}
} else {
// do nothing!
}
})

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

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".

How to handle history.pushState with content change

While Mozilla has an easy to understand documentation on history.pushState and history.replaceState it doesn't show me how to deal with the content when the back button is pressed and content is changed dynamically.
Suppose foo.html has a form and executes an AJAX call to replace its content on submit, then pushState looks like below:
history.pushState({content:$('#content').html()}, '', 'bar.html');
When the user clicks on the back button the URL changes back to foo.html but the page doesn't display the form. How can I display the form? I had a look at popState but couldn't get it to work properly.
so this is what I have done to solve it:
When foo.html loads, I execute history.replaceState({container:$(#container').html()},'', window.location);
Then after ajax call to replace content, I execute this: history.pushState({container:$(#container').html()},'', 'bar.html');
On page load, I bind the popstate to check if event has state object which contains the container like this:
$(window).bind("popstate", function(event) {
if (event.state != null){
if ('container' in event.state){
$(#container').html(event.state.container);
}
}
});
You need to store all of the state you need to re-render the old content, then use that state to re-create the previous page on popstate.
Model-binding techniques such as Knockout.js (or full MVC frameworks) can make this much easier.

Force page reload with html anchors (#) - HTML & JS

Say I'm on a page called /example#myanchor1 where myanchor is an anchor in the page.
I'd like to link to /example#myanchor2, but force the page to reload while doing so.
The reason is that I run js to detect the anchor from the url at the page load.
The problem (normally expected behavior) here though, is that the browser just sends me to that specific anchor on the page without reloading the page.
How would I go about doing so? JS is OK.
I would suggest monitoring the anchor in the URL to avoid a reload, that's pretty much the point of using anchors for control-flow. But still here goes. I'd say the easiest way to force a reload using a simple anchor-link would be to use
where in place of $random insert a random number (assuming "dummy" is not interpreted server side). I'm sure there's a way to reload the page after setting the anchor, but it's probably more difficult then simply reacting to the anchor being set and do the stuff you need at that point.
Then again, if you reload the page this way, you can just put myanchor2 as a query parameter instead, and render your stuff server side.
Edit
Note that the link above will reload in all circumstances, if you only need to reload if you're not already on the page, you need to have the dummy variable be more predictable, like so
I would still recommend just monitoring the hash though.
Simple like that
#hardcore
an example
Another way to do that is to set the url, and use window.location.reload() to force the reload.
<a href="/example#myanchor2"
onclick="setTimeout(location.reload.bind(location), 1)">
</a>
Basically, the setTimeout delays the reload. As there is no return false in the onclick, the href is performed. The url is then changed by the href and only after that is the page reloaded.
No need for jQuery, and it is trivial.
My favorite solution, inspired by another answer is:
myanchor2
href link will not be followed so you can use your own preference, for example: "" or "#".
Even though I like the accepted answer I find this more elegant as it doesn't introduce a foreign parameter. And both #Qwerty's and #Stilltorik's answers were causing the hash to disappear after reload for me.
What's the point of using client-side JS if you're going to keep reloading the page all the time anyways? It might be a better idea to monitor the hash for changes even when the page is not reloading.
This page has a hash monitor library and a jQuery plugin to go with it.
If you really want to reload the page, why not use a query string (?foo) instead of a hash?
Another option that hasn't been mentioned yet is to bind event listeners (using jQuery for example) to the links that you care about (might be all of them, might not be) and get the listener to call whatever function you use.
Edit after comment
For example, you might have this code in your HTML:
example1
example2
example3
Then, you could add the following code to bind and respond to the links:
<script type="text/javascript">
$('a.myHash').click(function(e) {
e.preventDefault(); // Prevent the browser from handling the link normally, this stops the page from jumping around. Remove this line if you do want it to jump to the anchor as normal.
var linkHref = $(this).attr('href'); // Grab the URL from the link
if (linkHref.indexOf("#") != -1) { // Check that there's a # character
var hash = linkHref.substr(linkHref.indexOf("#") + 1); // Assign the hash to a variable (it will contain "myanchor1" etc
myFunctionThatDoesStuffWithTheHash(hash); // Call whatever javascript you use when the page loads and pass the hash to it
alert(hash); // Just for fun.
}
});
</script>
Note that I'm using the jQuery class selector to select the links I want to 'monitor', but you can use whatever selector you want.
Depending on how your existing code works, you may need to either modify how/what you pass to it (perhaps you will need to build a full URL including the new hash and pass that across - eg. http://www.example.com/example#myanchor1), or modify the existing code to accept what you pass to it from you new code.
Here's something like what I did (where "anc" isn't used for anything else):
And onload:
window.onload = function() {
var hash = document.location.hash.substring(1);
if (hash.length == 0) {
var anc = getURLParameter("anc");
if (anc != null) {
hash = document.location.hash = anc;
}
}
}
The getURLParameter function is from here
If you need to reload the page using the same anchor and expect the browser to return to that anchor, it won't. It will return to the user's previous scroll position.
Setting a random anchor, overwriting it and then reloading seems to fix it. Not entirely sure why.
var hash = window.location.hash;
window.location.hash = Math.random();
window.location.hash = hash;
window.location.reload();
Try this its help for me
<a onclick="location.href='link.html'">click me</a>
In your anchor tag instead of
click me
As suggested in another answer, monitoring the hash is also an option. I ended up solving it like this so it required minimal code changes. If I had asked the original question, I believe I would have loved to see this option fully explained.
The added benefit is that it allows for additional code for either of the situations (hash changed or page loaded). It also allows you to call the hash change code manually with a custom hash. I used jQuery because it makes the hash change detection a piece of cake.
Here goes!
Move all the code that fires when a hash is detected into a separate independent function:
function openHash(hash) {
// hashy code goes here
return false; // optional: prevents triggering href for onclick calls
}
Then detect your hash for both scenarios like so:
// page load
$(function () {
if(typeof location.hash != typeof undefined) {
// here you can add additional code to trigger only on page load
openHash(location.hash);
}
});
// hash change
$(window).on('hashchange', function() {
// here you can add additional code to trigger only on hash change
openHash(location.hash);
});
And you can also call the code manually now like
Magic
Hope this helps anyone!
Try this by adding simple question mark:
Going to Anchor2 with Refresh

Categories