I want to show a confirmation box in javascript when an user clicks on
<link to="###">XYZ <link>
I have already tried <Link onclick="return confirm('Are you sure?')" to="###" >XYZ</Link>
But it does not give the desired result.
I want to show a confirmation box in javascript when an user clicks on
<link to="###">XYZ <link>
I have already tried <Link onclick="return confirm('Are you sure?')" to="###" >XYZ</Link>
But it does not give the desired result.
(Answer edited now that the question tags have been changed)
<link>
isn't a valid tag for what you're trying to do; it's designed for pages to call in and embed external resources. It is not allowed to have child contents, and will not respond to user events when placed in the document body (I believe, though am not certain, that it is required to be in the document <head>
.)
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link
Any valid HTML entity will work as you've shown:
<a onclick="return confirm('Are you sure?')" href="###" >XYZ</a>
<div onclick="return confirm('Are you sure?')" >ABC</div>
...but I suspect you intended to use the <a>
tag. (As ScottMarcus correctly points out in comments, anchor tags aren't correct as hooks for arbitrary javascript, but since what you're controlling here is the navigation itself, it is an appropriate tag.)
You've added the "reactjs" tag to the question, so it becomes clear that what you're trying to use is actually the React component "Link" rather than the (completely different) HTML tag.
I'm far from expert in React, but it appears that you need to wrap the event handler in {} brackets rather than quotes (which cause React to interpret the contents as a string) -- and should probably move the confirm
code into a function contained within your React component.
The link
element cannot be used in the way you are wanting. It's only allowed in the head
section of a document and used to link out to external resources that the page requires.
Also, you shouldn't be using any kind of link to open a confirmation dialog in the first place as it is semantically incorrect and will cause issues for people that rely on assistive technologies (like screen readers) to view pages. Additionally, you'll need to cancel out the native behavior of clicking a link by with return false
or event.preventDefault()
, which essentially means you are asking the browser for a link but to please disable the link, which is counter intuitive. A link (<a>
) is for navigation and shouldn't be used just as a "hook" to trigger some JavaScript.
Just about any element in the body
supports a click
event and for something like this, a button
or just a div
can easily do the job.
document.querySelector("div").addEventListener("click", function(){
console.log(prompt("What is your favorite color?"));
});
<div>Click Me</div>