Change the class of the dropdown button after clicking the dropdown item and reload the page
P粉877719694
P粉877719694 2023-08-17 16:24:17
0
1
538
<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>
P粉877719694
P粉877719694

reply all(1)
P粉063039990

I think this should work...

let isBtnClicked = localStorage.getItem("isBtnClicked")
? localStorage.getItem("isBtnClicked")
: false;
$(".dropbtn").addClass(
isBtnClicked
? "hovered" // 在这里填入您点击按钮的类名
: ""
);
$(".dropbtn").text(
localStorage.getItem("selected")
? localStorage.getItem("selected")
: "Helpful Links"
);
$(".dropbtn").on("click", function () {
$(".dropdown-content").toggleClass("open");
isBtnClicked = !isBtnClicked;
localStorage.setItem("isBtnClicked", isBtnClicked);
});
$(".dropdown-content a").on("click", function () {
$(".dropbtn").text($(this).text());
localStorage.setItem("selected", $(this).text());
$(".dropdown-content").removeClass("open");
});
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template