1

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> 

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

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.
1
$("#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

1 Comment

I find .each() is simpler to use when possible: $("ul#list_o_links").children().each(function() { list.push($(this).text()); });

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.