简体   繁体   中英

Show popup when <a href >link clicks

I just want to make a URL with a button when It clicks it must show a dialog with my message. Is there any way to achieve in HTML?. Already searched google, as a beginner I don't understand much. So a simple tutorial might help me.

the link should be like www.google.com/webpage/#popup

dialog must be shown in the center of the screen.

onClick with a function:

<script type="text/javascript">
function AlertIt() {
  alert("ATTENTION! THIS IS AN ALERT");
}
</script>

<a href="javascript:AlertIt();">click me</a>

Complex single one-liner:

<a href="http://example.com/"
 onclick="return alert('Please click on OK to continue.');">click me</a>

You can make use of a hashchange -event!
Make a check-hash function and call it initially, so that loading the URL with the hash has the same behavior as changing the hash when already on-page.

You could create an array holding the IDs of the elements that should "listen" for such a hashchange , and give them a specific class (eg .hash-selected ) when their ID equals the hash.

 const hashes = ["#popup"]; // List of IDs that are "listening" let lastHash = ""; function checkHash() { if (hashes.includes(lastHash)) // Remove class from last selected element document.querySelector(lastHash).classList.remove("hash-selected"); if (hashes.includes(location.hash)) // Add class to current selected element document.querySelector(location.hash).classList.add("hash-selected"); // Save current hash as 'lastHash' for first if-statement when calling 'checkHash()' again lastHash = location.hash; } checkHash(); // Initial function-call for same behavior on "page-open" window.addEventListener("hashchange", () => checkHash());
 body {margin: 0} #popup { position: absolute; border-bottom: 1px solid black; width: 100%; transform: translateY(-100%); background: lightgreen; } #popup.hash-selected {transform: translateY(0)}
 <div id="popup"> <p>Some sample text</p> <a href="#">Close</a> </div> <a href="#popup">Open popup</a>

We could even easily fill the hashes -array with IDs of elements that have a specific class, like .hash-listen :

const hashes = [];
for (let el of document.querySelectorAll(".hash-listen"))
  hashes.push("#" + el.id);

// ...

Sidenote
To remove hashchanges from the browser-history, you should take a look at this answer that demonstrates the history.replaceState() -function .

 <a href="https://stackoverflow.com/" onclick="myAlert()">Click Here</a> <script> function myAlert() { alert('hello there!'); } </script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM