Search code examples
javascriptjqueryanchorreload

Add anchor in url after page reload and display hidden section in JS


When I click in a link with an anchor, I load the other page after clicking to the link. My problem is I did not succeed to execute the script to display a hidden section after reload.

How can I do to execute the script and display section after reloading a new page with a target? Thank's.

Template

echo '<li><a href="'.get_site_url().'/works#works-list" class="list-link">List</a></li>';

JS script

$('.list-link').click(function() {
    $('#works-list').removeClass("hide");
});

Solution

  • Since the page reloads, the click event will fire on the old page, thus not editing the dom of the newly loaded page. However since you add an anchor to the url, you can just check for that anchor on every page load, the new code would look like this.

    if(location.href.includes("#works-list")) {
        $('#works-list').removeClass("hide");
    }