I am trying to return the href
attribute of a link using JavaScript when the user clicks on it. I want the URL the link is linking to displayed in an alert instead of loading the page.
I have the following code so far:
function doalert(){
alert(document.getElementById("link").getAttribute("href"));
return false;
}
With the following markup:
<a href="http://www.example.com/" id="link" onclick="return doalert()">Link</a>
For some reason, no alert is ever displayed and the page loads instead. Does anyone know why this is?
Using jQuery is not an option in this case.
Using onclick Event: The onclick event attribute works when the user click on the button. When mouse clicked on the button then the button acts like a link and redirect page into the given location. Using button tag inside <a> tag: This method create a button inside anchor tag.
HREF JavaScript is a method to easily call a JavaScript function when a user clicks on a link on a website. If you've ever clicked a link and received a pop-up box, such as an alert dialog, then you've potentially seen this function in action.
Seems to be the order of your code, try this
<script>
function doalert(obj) {
alert(obj.getAttribute("href"));
return false;
}
</script>
<a href="http://www.example.com/" id="link" onclick="doalert(this); return false;">Link</a>
http://jsfiddle.net/YZ8yV/
http://jsfiddle.net/YZ8yV/2/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With