views:

66

answers:

2

Hi,

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'&gt;List Item1</a></li>
    <li><a href='http://www.yahoo.com'&gt;List Item2</a></li>
    </ul> 
+1  A: 
$("#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

CD Sanchez
I find `.each()` is simpler to use when possible: `$("ul#list_o_links").children().each(function() { list.push($(this).text()); });`
Peter Ajtai
+1  A: 

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);
Magnar
incidentally, it doesn't matter whether you include `preventDefault()` as the first, last, or middle line of the function. `return false` must be last, since it stops (returns from) the function.
Peter Ajtai