user443946
user443946

Reputation: 845

javascript click event question

I have a question below is a list with the anchor links now when the links are clicked I dont want the browser to go to that web page instead I want the browser to stay on the current page and display the list in an alert box to the user. I know this can be done with javascript maybe with the onclick event on the list item and display an alert box but how do I stop the browser to go that webpage.

 <ul id='list_o_links'>
    <li><a href='http://www.google.com'>List Item1</a></li>
    <li><a href='http://www.yahoo.com'>List Item2</a></li>
    </ul> 

Upvotes: 1

Views: 163

Answers (2)

Cristian Sanchez
Cristian Sanchez

Reputation: 32167

$("#list_o_links").children().click(function () {
    var list = [];

    $.map($("#list_o_links").children(), function (elem) {
        list.push($(elem).text()); // take the text of each list item
    });

    alert(list.join(', '));

    return false; // stop the browser from going to the link
});

jsfiddle example

Upvotes: 1

Magnar
Magnar

Reputation: 28830

You stop the browser from going to the link destination by calling event.preventDefault() or returning false in the bound event handler. I think the first is more explicit:

var alert_instead_of_following_link = function (event) {
    event.preventDefault();
    alert(this.href);
};

$("#list_o_links a").bind("click", alert_instead_of_following_link);

Upvotes: 1

Related Questions