There is a list

<ul> <li class="sort">1</li> <li class="sort">2</li> <li class="sort">3</li> </ul> <a href="1.php">link</a> 

By clicking on a particular li, the class red is added. If the user follows the link and returns, the red class is not remembered. How to make the red class remain in li even when switching to another link?

  • one
    Write the position to the cookies and, when outputting, take into account or send the information about the marked item to the server by the Ajax - binliz
  • not strong in cookies, how will it all look, tell me pozhalsta - G_test_00
  • learn.javascript.ru/cookie here everything is just described for js, and for php you can take advantage of the $ _COOKIE superglobal array - binliz

1 answer 1

If you need to implement sorting, or rather, if you need to “remember” the value for one or a small number of blocks, you can use cookie / Then the code on js will be:

 NodeList.prototype.forEach = Array.prototype.forEach; function setCookie(name, value, options) { // функция установки cookie options = options || {}; var expires = options.expires; if (typeof expires == "number" && expires) { var d = new Date(); d.setTime(d.getTime() + expires * 1000); expires = options.expires = d; } if (expires && expires.toUTCString) { options.expires = expires.toUTCString(); } value = encodeURIComponent(value); var updatedCookie = name + "=" + value; for (var propName in options) { updatedCookie += "; " + propName; var propValue = options[propName]; if (propValue !== true) { updatedCookie += "=" + propValue; } } document.cookie = updatedCookie; } /*Обработка нажатия на блок*/ var divs = table.querySelectorAll(".sort"); divs.forEach(function(el, iNum){ el.addEventListener("click", function(e){ addActiveClassToCookie(el.innerText, iNum); }); }); function addActiveClassToCookie(data, num){ // сохранение значений в cookie setCookie("sortActiveValue", data, { expires : 60*60*24*365, // ставим куку на год domain : window.location.host // ставим доступной для текущего домена }); setCookie("sortActiveNum", num, { expires : 60*60*24*365 }); } 

In php, you can get these values ​​and display the appropriate class:

 $sortActiveValue = $_COOKIE["sortActiveValue"]; $sortActiveNum = $_COOKIE["sortActiveNum"]; 

But do not forget to check that the data in the cookie is safe.

The most important thing

If you need to write data for a large number of classes (you had to do this a couple of times), then you need to store the data in the browser due to the fact that the cookies are transmitted in each request to the server and can significantly “burden” it.