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
434

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.

The following code is valid when the page is refreshed.

$(".dropdown-content").on("click", function() { $('.dropbtn').toggleClass('active'); });

Are there any local storage options I can use? I just learned about it.

I'm currently using the following code to call the text that appears in the dropdown button:

$(".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"); });

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.

I tried this, but I think I'm not using it correctly because .dropbtn doesn't retain the active class on page refresh:

$(".dropdown-content").on("click", function() { localStorage.setItem("active", $('.dropbtn').toggleClass('active')); $('.dropbtn').toggleClass('active'); });


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
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!