Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript get href onclick

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.

like image 773
Callum Whyte Avatar asked Jul 23 '13 10:07

Callum Whyte


People also ask

Can we use onclick on link tag?

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.

Can href be a JS function?

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.


1 Answers

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/

like image 179
jenson-button-event Avatar answered Sep 23 '22 08:09

jenson-button-event