Change the class of the dropdown button after clicking the dropdown item and reload the page
P粉877719694
2023-08-17 16:24:17
<p>I'm trying to change the class of a dropdown button item after the user clicks on an item in the dropdown menu and reloads the page. </p>
<p>The following code is valid when the page is refreshed. </p>
<pre class="brush:php;toolbar:false;">$(".dropdown-content").on("click", function() {
$('.dropbtn').toggleClass('active');
});</pre>
<p>Are there any local storage options I can use? I just learned about it. </p>
<p>I'm currently using the following code to call the text that appears in the dropdown button: </p>
<pre class="brush:php;toolbar:false;">$(".dropbtn").text(
localStorage.getItem("selected")
? localStorage.getItem("selected")
: "Helpful Links"
);
$(".dropbtn").on("click", function () {
$(".dropdown-content").toggleClass("open");
});
$(".dropdown-content a").on("click", function () {
$(".dropbtn").text($(this).text());
localStorage.setItem("selected", $(this).text());
$(".dropdown-content").removeClass("open");
});</pre>
<p>Many thanks to @RedApple for the help. It works fine - just wondering if the .dropbtn class could be set to active in a similar way when the .dropdown-content a-item is clicked. </p>
<p> I tried this, but I think I'm not using it correctly because .dropbtn doesn't retain the active class on page refresh: </p>
<pre class="brush:php;toolbar:false;">$(".dropdown-content").on("click", function() {
localStorage.setItem("active", $('.dropbtn').toggleClass('active'));
$('.dropbtn').toggleClass('active');
});</pre>
<p><br /></p>
I think this should work...