Jquery resets when I refresh the page - javascript

I have a site that you can specify which items on the page that should be shown using this jquery:
$('.container h1 a').click(function () {
$('.container').not($(this).parents()).hide();
$(this).css({'text-decoration' : 'none',
'cursor' : 'default'
});
});
But then when I refresh the page the jquery functions that took place are removed

Javascript works on the client side, thanks to the browser. It can modify the current page, but any change will be erased as soon as you reload the page (you get its original content from the server). If you need to restore those changes as "user preferences", use PHP cookies to store information about how each user changes his interface. This way, when you reload the page next time, you can execute the required Javascript functions to restore the user's view.
You could use Ajax to store the user preferences from Javascript, asynchronously.
http://www.w3schools.com/ajax/
Here is W3Schools' Ajax tutorial, you should learn about it. When a user changes his preferences on your page, remember it using a PHP cookie (http://php.net/manual/en/features.cookies.php). When the page is reloaded, check the cookie's content, and execute necessary Javascript functions to restore the user's interface.
Edit : Didn't know about http://www.electrictoolbox.com/jquery-cookies/ which allows you to store a cookie from jQuery without using Ajax and additional PHP scripts. Lars Ebert's solution could be lighter indeed, but the general idea is the same.

The css-properties are only modified temporarily. They are not permanent and are gone when you refresh the page. To remember the hidden elements, you would have to use a cookie. You can use this jQuery-plugin to store a cookie.
In this cookie, you can store the id of the hidden element each time the user clicks to hide one element. On page-load, you simply read the cookie and re-hide the elements the user has hidden!

Related

Changing class using javascript in other pages

I don't know how to change a div's class by using JS on an other page. To specify, it will be like the class on page-A should change depending the JS changes on page-B.
(If you click on a box in page-B, the content on page-A should change.)
You can only amend the DOM of the page which is currently loaded. If you want to change a different page based on an action in a previous one you'd need to persist the state of the user's interactions and then amend the other page when it loads. To do that you can use localStorage, sessionStorage, session, cookies, or AJAX to store information on the server.

How can I make a .toggleClass button click keep its effects on different pages?

I've been developing a site which makes use of a button to toggle it's whole appearance between positive & negative themes for the background/navbar/text color, depending on what the user prefers. I've done the home page with a simple toggleClass method:
$(document).ready(function(){
$('.switchButton').click(function(){
$('.mainBg').toggleClass("bg-inv");
});
});
How can I make it so that when the user loads any other page of the website, it will open with the theme chosen previously (as in, if the page you're in is on negative, all of them will be negative until you change to positive)? I plan to insert a switch on every single page, but having to flick it every time you'd want to use the second theme is very annoying. I'd thought about an IF jquery function, but am not sure how to use it between different pages.
HTTP is stateless. This means that data between connections is not saved, and every request is a fresh one based on the code on the server.
If you want to save data across requests, you will have to save it in a place that is not dependent of the request. This can be either in a in a cookie, a session variable, in a database or you can use localstorage.
You can only access the cookie from JavaScript directly, so that would be your easiest bet.
You could save the value in a cookie and load it in each page so that it persists between pages.
On Home page you can store the value in sessionStorage and on every page you can retrieve the value from sessionStorage variable.
$(document).ready(function(){
$('.switchButton').click(function(){
$('.mainBg').toggleClass("bg-inv");
sessionStorage.class = "bg-inv";
});
});
On every page you can check the variable
$(document).ready(function(){
if(typeof(Storage) !== "undefined") {
$('.mainBg').addClass(sessionStorage.class);
}
});
let's assume you make a variable called class; . Now in the toggleClass function write class=a where a is the variable you pass to toggleClass, bg-inv in this case. Now you can save class in your localStorage by localStorage['class'] =class and retrieve it whenever required using localStorage['class'] or localStorage.getItem('class') Hope this helps!

Calling a Javascript function on focus of a page based on user interaction

I have a requirement where clicking on an icon should open a new window where the user will be able to view and edit certain fields. After the user closes this window and comes back to parent window, the icon color and text should be changed( for eg:- if the user has removed certain data, the icon will change to red color and text is set to null. If the user presses cancel button, nothing changes)
I am planning to implement this using a body onload function which essentially checks with the database using AJAX requests to see if the user has changed the data, then accordingly change the icon and text.
But, I see 2 problems in this approach
1. There will be a AJAX call even if the user has not changed anything.(ie. pressed Cancel button)
2. AJAX is called every time the body is on focus. Eg:- He may be working on some other page (or a different browser altogether) and comes back to this, resulting in an AJAX call.
Can anybody suggest a better approach.
I am using Javacript, JSP, Java
Two ways to implement this
Method 1
You know the methods which changes the database in the opened form. Suppose you have a delete method, write an additional window.opener.location.reload() after the method. The downside is that opener(parent window) gets reloaded every time you change something in the child window. Which is unnecessary.
Method 2 - Using cookies
I am using MDN's A little framework: a complete cookies reader/writer with full unicode support for creating cookies. The plan of action will be this. Create a cookie and set a value for it like this after you change anything in the child window and update it in the database like this docCookies.setItem("isChildFormUpdated", "yes");. You can use the same cookie for every action you do. Now when you navigate back to the parent form, do this.
$(document).ready() {
$(window).focus(function () {
var formCookie = docCookies.getItem("isChildFormUpdated");
if (formCookie !== null && formCookie == "yes") {
//resetting the cookie. you can also remove the cookie
docCookies.setItem("isChildFormUpdated", "no");
//docCookies.removeItem("isChildFormUpdated");
// your ajax call comes here
//or you could simply reload the form so that we get fresh data
//window.location.reload(); // it will be heavier
}
});
});
I hope you get the basic idea.
I think the easiest way to do this would be to set a cookie (learn how here). You can then have the two windows communicate between each other. This wouldn't be AJAX, but it will most likely work.
Another nice way to create a popup-like box is by using a modal box. These can be complicated but they look very nice. You have to make a jQuery plugin in, but you can take the one here and learn how it works. Good luck with your requirement.

appendChild() checkboxes: remember selections with browser back button

Thank you in advance to anyone who attempts to help me with this.
I have a form that I am adding checkboxes to via appendChild() - as selections for the user to chose from - based on a bunch of criteria.
When the user checks any of these boxes and then clicks the 'continue' button to post the selection to another page - and then clicks the back button - the checkboxes that were checked by the user - have now been forgotten by the browser (no longer checked).
If I use php to write the checkboxes or simply have static checkboxes - when the user checks any of these boxes and then clicks the 'continue' button to post the selection to another page - and then clicks the back button - the selected checkboxes are remembered (still checked)
My question is:
Why does the browser forget the selections the user made when I create the checkboxes with appendChild()
yet the same browser will remember the selections the user made when using static checkboxes
What is it about appendChild() that is not allowing the same browser to remember the checked selection?
[div id="mydiv"] here is where the checkboxes are going[div]
[script type="text/javascript"]
var newInput = document.createElement("INPUT");
newInput.id = "mycheckboxid";
newInput.name = "mycheckboxname";
newInput.type = "checkbox";
document.getElementById('mydiv').appendChild(newInput);
[/script]
The browser may "forget" dynamic changes to the DOM because different browsers use different strategies for caching web pages. When you hit the back button, the idea is that the browser can display its cached copy rather than re-request the page from the original web server.
It can accomplish this in (at least) two ways:
The browser caches the DOM itself of a page upon leaving it. Upon revisit (forward or back) dynamic changes will persist.
The browser caches only the original HTML of the page at load time (prior to any dynamic changes). This has the effect of losing those dynamic changes--further modification to the DOM with appendChild() or innerHTML is not recorded.
Note that some browsers additionally keep modified form data, and others do not. If your goal is 99+% compatibility across all browsers, then you have some work to do.
To work around this you need to persist the state somehow. You have a few options:
Save data about the modifications to the page to localstorage. Use a key that is generated randomly on first page load and then kept in the page, so that the state changes will only apply to that instance of the page. On page load, if this key already exists, read the change data out and re-apply the changes. Older browsers do not support local storage.
Do the prior thing with cookies. I don't recommend this, as it has the drawback of proliferating cookies. Cookies are sent and received in every request (including ajax ones), so you would be bloating the data being transmitted on every request. Old browsers would work fine with this.
Abandon your dynamic change model and make the changes occur through a post to the server. Then the page will contain the modified html when pulled from the browser's cache. You probably don't want this, but I thought I'd point it out for completeness' sake.
Save data about the modifications to the page via ajax behind the scenes to the server. This is not the same as actually round-tripping each change like the previous item. You still make changes dynamically, but you post an "advisement" file to the server. Then, on each page load, request any adjustment data from the server. This is similar to the first suggestion, but you are using the remote server as your storage. This makes extra net traffic occur on each page load, but the traffic can be minimal as it would be just about this page. It also makes extra net traffic occur that would not normally be sent (the advisement data). A clever system architecture, however, could use this information to persist a user's unsubmitted form data across computers and over time in a way that could be very handy (lets say your user does 199 out of a 200-question survey and then his power goes out--with this scheme he has a chance of painlessly continuing later exactly where he left off!).
Make your Continue button open a new browser window, preserving the original page intact.
Make your Continue button post the data without leaving the page, preserving it intact. You could do a simple lightbox-style overlay.
If the lightbox-style overlay will not work but you really have to display a new page and don't want it to be in a new window, then redesign your site to work similarly to gmail: where pages change only through javascript, and only through using #hash tags at the end of URLs to control behavior. This can be difficult but there are libraries out there that can accomplish it. (For some browsers one has to resort to polling to see if the hashtag has changed.) The basic idea is that when you click a link that points to the same page but has a tag on it such as About the browser will initiate a page load event, and will push a new context into the history forward/back stack, but will not actually load a new page. You then parse the updated URL for the hash code (which maps to some kind of command) and carry it out. Through careful choice of the proper hash codes for each link, you can hide and display the appropriate page dynamically through Javascript and it will appear as if the person is navigating around a real web site. The reason you do all this is that, because the page never loads, you not only can maintain state in Javascript, you can maintain your DOM state as well--you simply hide the page that was modified by the user, and when the back event occurs that means to visit that page again, you display it, and it is exactly how the user left it. Advantage: If your site requires Javascript to operate, then you are not taking a risk by using even more Javascript to accomplish it. Disadvantage: Completely changing the architecture of your site is a LOT of work and can be difficult to get working on older browsers. To get started with this see Unique URLs. You might try out the jQuery hashchange plugin. If your web site has wide distribution you will want to be sure to address search engine optimization and web usability issues. You may want to see this SO page on detecting back button hash changes.
Use the same strategy as in the prior point but instead of doing it with hashtags, use the new HTML5 history.pushState() and history.replaceState() methods--see Mozilla browser history.
If your goal is not 99% compatibility across 99% of the browsers in use, then please let us know what you are aiming at, as there may be a shortcut possible.
Update: added an option #8
Scripting pages doesn't stop at state management. It includes state management.
This means scripted state changes such as scripted page transitions(pages that internally navigate), content panes, popover menus , style changes and of course, form input and selections are all the responsibility of the scripter.
So, in answer to why .. it is because you did not manage the page state you scripted.
If you want your page to work as you seem to expect you can manage the page state changes you script yourself, use a js lib that manages page, or perhaps in your case form, state, or use the http(s) client/server state management and load up the session state, or in your case just the form state, at the server.

Using Javascript, how can I change the CSS display property on a different HTML page

So, I want to change the display style of one of my divs, here's the code in my javascript:
document.getElementById("header1").style.display='none';
Now the problem... header1 is a div id on a different page, but I want to affect that from selecting an option on the current page. How do I go about doing that so that the header1 will be hidden when I go onto the next page?
Thank you in advance!
You cannot change the properties of an element that has not been loaded into the browser yet. You would have to use a cookie or the querystring to tell you to hide the element when the page is loaded.
Edit
You can redirect to a new page using the following javascript. Note: everything following the ? is part of the querystring.
// Redirect without querystring
window.location = "http://www.mySite.com/default.html"
// Redirect with querystring
window.location = "http://www.mySite.com/default.html?hide=true"
// Redirect with multiple values in querystring
window.location = "http://www.mySite.com/default.html?hide=true&test=1"
Check out get-query-string-values-in-javascript to see how to retrieve querystring values through javascript.
You could pass the value to the next page in a hidden form field or possibly via the url then when that page loads use that value to set the desired value on the page.
how about carrying the value/selection to the other page using local/session storage, or even indexDB, if you have a lot of information to carry or you are carrying across multiple pages. saves having unneeded POSTS and removes the need for any server side code

Categories