to restore a same id in the page when refreshed - javascript

I am working on javascript as well as jquery. and i am using 2divs in my page. so when my page loads the second div is hidden and when a button from the first div is clicked it navigates to the second page. so when i press refresh button now. the page navigates to the first div as it reacts when the page is opened for the first time. any ideas or suggestions to make the second div display even when the page is refreshed. thanks in advance. here is my fiddled code it works fine in the fiddle as i exactly want. but it fails in my project code. http://jsfiddle.net/pWryf/ . any example to attain this through cookies.?
Here is my code for the div:
$('#sbut1').click(function() {
$('.cont1').show();
$('#log1').hide();
});

Try something like this using localStorage:
$('#sbut1').click(function() {
$('.cont1').show();
$('#log1').hide();
localStorage['shown'] = '.cont1';
});
$(function() {
var sel;
if (sel = localStorage['shown']) {
$('.cont1, #log1').hide().filter(sel).show();
}
});
http://jsfiddle.net/5aJZR/
Use can also use cookies for this purpose.

I can think of atleast 2 frontend approaches to this problem:
using a cookie or a more modern localstorage solution to handle sessions. (already been here, cookie)
using a one page app, where navigations is after the hash # sign. such as in backbone webapps.
You can also use some kind of server side session handling, most web framework have one embedded.

Related

How to implement routing with a single page application build solely using jQuery

Right now when the user inputs a word in the textfield and hits search, the form submits using $.get(). The data(JSON) is fetched from the server and then the UI is updated.
What I want to do is pretty simple:
1) When the form submits, the URL of the browser needs to update (something like search/zyx, zyx is what the user is searching for).
2) when the page is booked into favorites, or clicked as a link from somewhere the page needs to load and then the textfield value have to be 'zyx'. Also the UI needs to show search result of zyx.
This is important to my app because I will be using Google Analytics. So the URL is needed to reflect behaviour. Plus the other issue like back button history. Is this possible using just jQuery or some extremely light libraries build on jQuery. I have searched everywhere and all the solutions I found were using MVC frameworks. Or another solution was to use a templating framework like this one. However my app is way too simple for these solutions.
So, the approach you you need is to listen to hash changes in the url and based on this get the current page and render it in a cointainer. Something like this:
Go to Page 2
<div class="page-container"></div>
<script>
$(window).on('hashchange',function(){
var page = window.location.hash;
$.get('pages/'+page+'.html', function(pageContent){
$('.page-container').html(pageContent);
})
});
</script>
Thank you every one. So I ended up using a combination between #Tulio Faria 's answer and #Gabriele Mantovani.
To get the search keyword from url I used window.location.hash
To update url used history.pushState({id: 'query'}, '', 'some_url_string');
Used $(window).on('hashchange',function(){...}) to load page of the current search keyword if either back or forward buttons of browser were clicked
If I understand you want to change the URL of the user when some actions are done. There is an other topic about it HERE, and they use
window.location.replace(url)
Hope it helps you :)

jquery show/hide when page loads

I am having an issue with jQuery. I have a menu page in my app and when I click on a page I want certain divs to be shown and some to be hidden. When I click on a page the following script
$(document).ready(function() {
$("#sp").hide();
$("#fea").hide();
$("#lib").show();
});
only works if I reload the page.
If the document is already loaded when I click on the menu again and go to a different page the same function doesn't work on that page even though I have the same function between script tags on multiple pages.
So in a nutshell whatever page loads first has the function applied. All other pages have to be refreshed before the function is applied. All of my pages are loaded from the menu page.
Does anyone know how to apply the function every time I load a page from my menu page?
I have also tried:
$(document).on("pageshow", "#pageID", function() {
$("#sp").hide();
$("#fea").hide();
$("#lib").show();
});
and I have the same issue where the function is only applied when I refresh.
Why you didn't use css for this? It will work even if a javascript will be disabled in the browser settings
Ok, I was able to figure out a solution. I am still not sure why the problem was occurring in the first place but I changed my function to this:
$('body').on('pageinit', function() {
$("#sp").show();
$("#fea").hide();
$("#lib").hide();
});
So thank you to everyone who made snide remarks and down-voted instead of providing a solution, your input was invaluable to my project. ;)

Jquery window.location to new page but also open a div originally set to display none

I have a form when on submit it will run two on-click events the first to redirect the window location to the new page and then the second to open the hidden div as below.
The issue is that it will load the new div in the source code and change it's status to display block but when it refreshes for the window location the function showDiv() is then hidden again. I'm sure there is a way to merge them both into one but I'm struggling.
function SetUpRedirect(destination)
{
setTimeout("window.location=\'/?page=4\'",1000);
return true;
}
function showDiv() {
document.getElementById('thanks').style.display = "block";
}
If I understand you right, the problem here is that you refresh the page. Once you refresh the browser loads a new DOM and forgets all about the old one and all the modifications you made to it. Changes you do to the DOM with JavaScript are not persistent over page loads.
So, how can you get around this? I can think of three options:
Alt 1. Use some kind of server side scripting, i.e. PHP, and pass the state of the div in the URL:
window.location = "/?page=4&display=block";
Then in the PHP (or whatever language you use), you need to read the value of display and handle it appropriately.
Alt 2. Set a cookie with JavaScript to signal that the div should be displayed, and when the page loads check if the cookie is present and adjust the display property of the div appropriately. You can read more about cookies in JavaScript here.
Alt 3. Design your page in such a way that a page load is not needed (for instance submitting the form with AJAX). This could require a major redesign, though.
This might help you with your problem. Since window.location will just reload the page and reset all the styles to the original form: How can I make a redirect page using jquery

How to parse URL for page navigation when clicking the back button on single page site using ajax?

I am working on this website http://techxpertschico.com which uses ajax and .htaccess to update a single index.php page, the problem is that I can't get the back button to work. For example if you click two separate top header links and then click back it will not change the content you are looking at even though the url will be updated. This is because my logic to direct the user to the proper web page happens using php but when a user clicks the back button they receive a cached copy of the page therefore no server request. In fact, you'll notice if you click refresh on my site after clicking the back button it will load the correct content because it will send out the server request. My first thought to fix this was to force a refresh when a user clicks the back button, but I couldn't get this to solve the problem. I tried using header files, I tried using javascript, and I failed, so I'm asking for help once more. I just need to be able to parse the URL and direct them to the appropriate page but normally I do this using php and since the back button uses caching I am not sure if I need a javascript solution or if I need to try harder to figure out the forced refresh approach.... What would you do, or what do other sites that use a single index.php file do?
P.S. I'll post any code if you need to see it. Looking at my question from yesterday might help. How to refresh page on back button click?
Your problem is not related to the cache mechanism.
I've just checked your website using firebug and I have noticed that after loading the home page (without ajax), you use ajax to load requested page asynchronously and change URL in the address, the URL altering is done by your code which is ignored by firefox.
The URLs altered with code are not kept in the browser's history, this is why the Back button doesn't work in your case
EDITED, added own working Code example
If you are still working on this:
I do suggest you take a look into this article
change-browser-url-without-page-reload
I think it explains a good method which is not too complicated to make use of the HTML5 history possibilities.
Here's the code I finally implemented on my site, and the only issues I have is with my expandable menu states when going back in history..
HTML just uses a DIV with #content-main on your index.html, for all the external html-file contents will be loading into it.
The links(anchor) which should direct to that DIV get a class assigned: ajaxLink
In your referenced html-files, just write the content, no head or body.
You may include scripts, though, if it makes sense to not put them on your index page.
$(function () {
//AJAX: load html-pages dynamically into this site's div (#content-main), and add browser history and URL support
/*unnecessary? I don't use the next 3 lines of code
//To override the default action for the link(anchor tag), use the following jQuery code snippet.
$("a.ajaxLink").on('click', function (e) {
//code for the link action
return false;
});
*/
//Now to get the ajax content and display it and change the browser URL to the specific location without refresh use the following code.
$("a.ajaxLink").on('click', function (e) {
e.preventDefault();
/*
- if uncomment the ABOVE line, html5 nonsupported browers won't change the url but will display the ajax content;
- if commented, html5 nonsupported browers will reload the page to the specified link.
*/
//get the link location that was clicked
pageurl = $(this).attr('href');
//to get the ajax content and display in div #content-main
$('#content-main').load(pageurl);
//to change the browser URL to the given link location
if(pageurl!=window.location){
window.history.pushState({path:pageurl},'',pageurl);
}
//stop refreshing to the page given in
return false;
});
//the below code is to override back button to get the ajax content without page reload
//added some details from http://rosspenman.com/pushstate-jquery/ - otherwise going back in history to initial page resulted in issues
$(window).on('popstate', function(e) {
if (e.originalEvent.state !== null) {
$('#content-main').load(location.pathname);
}
else {
$('body').load(location.pathname);
}
});
});

Remember click before changing pages

Is there a way to remember the click that transitions to a new page using jquery. I have a page where a tree drop down structure transitions to a new page. If the user comes back to previous page, i'd like to have the tree expanded as it was before. The page from which it happens uses a .live('click') function. I don't have any code that I did so can't paste anything here. Just looking out for suggestions or hints! :)
Use cookies. When the tree is expanded, store it:
document.cookie = "tree=open";
When the user visits the page, check for it:
if (document.cookie.search(/tree-open/) != -1) {
...
}
My code is over-simplified to help you look in the right direction. You may want to borrow a JS cookie library.
If your application is in HTML5 then you can use HTML5 Web Storage and save the clicked link in it and on load check if some link was clicked then open that else open the first link, you can check it in jquery easily.
thanks
abhishek

Categories

Resources