Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

css :target selector does not work when loading a new page #143

Closed
MattApril opened this issue Nov 17, 2020 · 3 comments
Closed

css :target selector does not work when loading a new page #143

MattApril opened this issue Nov 17, 2020 · 3 comments

Comments

@MattApril
Copy link

I am utilizing the css :target selector for highlighting anchor tags that I jump to on a page. It works fine jumping to an element on the same page, but if I navigate to a new page with an anchor tag it does not trigger the :target selector properly.

Example:
Current page: /stuff
This triggers :target selector as expected: /stuff#thing1
This does not trigger the :target selector: /more#thing1

As is, the only workaround I have is to remove Unpoly functionality from links where I'm changing the page and jumping to an anchor. Is there a solution for this, or is it a bug with Unpoly?

PS. Thank you for this framework, it is really great.

@triskweline
Copy link
Contributor

triskweline commented Nov 25, 2020

AFAIK it's a known bug that most browser implementations don't update :target when the history is updated with JavaScript:
whatwg/html#639

This cannot be fixed by Unpoly I'm afraid.

A workaround would be to assign a class .hash-target to elements that would be matched by the URL hash, and style that class in addition to :target:

:target, .hash-target {
  background-color: yellow
}

You could assign that .hash-target class automatically with code like this (untested):

let markedElement = null

window.addEventListener('hashchange', function() {
  if (markedElement) {
    markedElement.classList.remove('hash-target')
  }
  
  if (location.hash && (markedElement = document.querySelector(location.hash))) {
    markedElement.classList.add('hash-target')
  }
});

@triskweline
Copy link
Contributor

I ended up solving this differently for our documentation site unpoly.com, see commit linked above.

@MattApril
Copy link
Author

Thanks for the update, I will take a look.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants