-2

I have a function that adds a CSS class to all "a" selectors when I click on the button, unfortunately when I refresh the page or go to another tab its result is lost and I have to click on the button again. How can I fix this?

JS code:

function underlineLinks() {
    const links = document.querySelectorAll("a");
    links.forEach(a => a.classList.toggle("underline-links"));
}

CSS:

.underline-links {
    text-decoration: underline!important; }
nsog8sm43x
  • 329
  • 5
  • 14
  • 2
    Does this answer your question? [How to store persistent data client side](https://stackoverflow.com/questions/714420/how-to-store-persistent-data-client-side) – zero298 May 28 '20 at 20:09
  • when you refresh or navigate to another page, everything is reset. your script will be run fresh without any state from previous runs next time you go to the page. you can save data using local storage https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage and then you have to fetch that data when your script starts. – Chris Rollins May 28 '20 at 20:10
  • why do you specifically need to change css only when the button is clicked ? Why not add the css ```underline-links``` to your "a" selector by default itself ? – Rahul Pillai May 28 '20 at 20:10
  • @RahulPillai - because it is part of the element improving accessibility of the website, and is an optional feature to be enabled by the user. – nsog8sm43x May 28 '20 at 20:18
  • So you need to store that it was applied and check it on page load and add it. Also why apply it to each link, just add a class to the body – epascarello May 28 '20 at 20:19
  • @zero298 no, this is not my topic. – nsog8sm43x May 28 '20 at 20:19
  • @nsog8sm43x - that _sort-of_ is your topic, though you may not realize it. To keep the underlines for a person you _**must**_ store the fact that the user wants them (they clicked the button) _someplace_. That someplace you store it could be as [localStorage](https://developer.mozilla.org/docs/Web/API/Window/localStorage) in the browser, or could be stored on the server as a user-preference – Stephen P May 28 '20 at 21:36

1 Answers1

0

Actually jquery function in this case is applied only on click. From it's name --> "on click" means that it will function only when the button is clicked, and will lose the changes when refreshed.

In order to keep the css style changed when button is clicked you can use the following :

  1. JS Local Storage . If you need to store the data for the specific browser only.
  2. PHP & AJAX (Post/Get) with a condition (e.g: sql condition), if you want to keep the change permanently unless another condition occurs.

edit: In 2. ,you can use php&jquery alone without the use of ajax get/post methods

Tarek AS
  • 187
  • 13