Link with Anchor

Asked

Viewed 493 times

2

I’m making a website and I have a link that, in addition to sending a message when it is clicked, uses an anchor to put the section of the site in the spotlight.

I’m doing it this way:

<a href="/alerta#destaque">Gerar Alerta</a>

This way, when the user clicks on the link, an alert is generated and the page "descends" to a div with the id "highlight" that shows the content of the generated alert.

The alert is generated from a Jquery function.

My problem is that this link only works once. The first time I click, everything happens right. Only if I click again on the link nothing happens.

I realized that if the anchor link is visible in the URL the link action does not work.

How could I solve this problem?

  • Guy edits your question as your code, it’ll make it easier for someone to answer you. Edit and place the HTML/CSS and JS, talk if using plugins or jquery etc.

1 answer

1

You can restore the page URL (by removing the alerta#destaque) without it being reloaded using the method history.replaceState.

For example: of site.com.br/alerta#destaque passes to site.com.br.

In your jQuery function cited in the question, put at the end the code:

history.replaceState("", null, window.location.pathname);

The window.location.pathname returns only the name of the current page, ignoring parameters, hash etc. Ex.:

site.com.br/alerta#destaque returns /

site.com.br/index.php?alerta#destaque returns index.php

  • The problem continues to happen. The URL actually returns to its original state (appears without the anchor). But the second click still doesn’t work, even removing the anchor from the URL =/ Can you tell me if it is possible to go to an anchor using only Jquery and without having to click on any link? For example: every time I reload the page Jquery sends me to that specific div?

  • yes that can be done, put your code in the question so we can help how it should be. meta html, css, js so we can help better

Browser other questions tagged

You are not signed in. Login or sign up in order to post.