0

I'm trying to trigger a function by clicking on a link, but this is not working.

This works on a <button> or a <p> tag or anything else but not on a link.

<a href="#" onclick="search()">click me</a>
<button onclick="search()">clickity</button>

JavaScript function:

function search()
{
    alert("hello");
    return false;
}
1
  • 1
    Where in the page is that JS? Is it nested inside any other JS? Commented Jun 17, 2013 at 15:34

1 Answer 1

2

It's because a links have a property named .search, which isn't a function.

When you assign an inline handler, the properties of the element become accessible as variables, and so the .search property/variable is shadowing the global search() function.

Just change the name, and it'll work.

<a href="#" onclick="mysearch()">click me</a>

function mysearch() {
    alert("hello");
    return false;
}

Or you could just access the global function directly from the window object.

<a href="#" onclick="window.search()">click me</a>

It works on the button because buttons don't have that property.

Sign up to request clarification or add additional context in comments.

2 Comments

Docs: developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement. That properties of elements are added to the scope of inline event handlers is one of the most confusing things IMO.
@FelixKling: Yep, it's all the confusion of the with statement, and without any visible syntax to let you know it's happening.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.