Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the right way to change the behavior of an <a> tag?

I want to make a link call a Javascript function through the onclick event and not do anything else (follow the link). What is the best way to do that? I usually do this:

<a href="#" onclick="foo()">Click</a>

But I'm not sure that is the best way and in this case it is navigating to page.html# which isn't good for what I'm doing.

like image 495
sheats Avatar asked Oct 08 '08 20:10

sheats


People also ask

How do you modify a tag in HTML?

You can change the HTML tags by typing the new start tags in the Starting Tag(s) field, and the appropriate end tags in the appropriate order, in the Ending Tag(s) entry field. Select the Apply button. Note: Make sure that the starting and ending tags match; otherwise, you may receive unexpected results.

What is tag a in HTML?

The <a> tag defines a hyperlink, which is used to link from one page to another. The most important attribute of the <a> element is the href attribute, which indicates the link's destination. By default, links will appear as follows in all browsers: An unvisited link is underlined and blue.

What is anchor tags?

The <a> tag (anchor tag) in HTML is used to create a hyperlink on the webpage. This hyperlink is used to link the webpage to other web pages or some section of the same web page. It's either used to provide an absolute reference or a relative reference as its “href” value.


1 Answers

Usually, you should always have a fall back link to make sure that clients with JavaScript disabled still has some functionality. This concept is called unobtrusive JavaScript. Example... Let's say you have the following search link:

<a href="search.php" id="searchLink">Search</a>

You can always do the following:

var link = document.getElementById('searchLink');

link.onclick = function() {
    try {
        // Do Stuff Here        
    } finally {
        return false;
    }
};

That way, people with javascript disabled are directed to search.php while your viewers with JavaScript view your enhanced functionality.

Edit: As nickf pointed out in comment #2, a try and catch will prevent the link to follow if there is an error in your handler.

like image 151
Andrew Moore Avatar answered Oct 02 '22 13:10

Andrew Moore