Search code examples
javascripthtmlhref

href="#" and back button on browser situation


Hi guys I've got a problem with "back" action in browser. When I click on the link it takes me to my "page"(calls the javascript function that shows some specific div) but when I click on the back button it just removes # from the url and does nothing.

This is the code with that function:

html += '<p><a href="#" title="' + places[i]['formatted_address'] + '" onclick="select_business(' + i + ');return true;">' +  places[i]['name'] + '</a><br/>' +  places[i]['formatted_address'] + '<br/>' +  places[i]['phone_number'] + '</p>';

So the URL is now : ... listings.html?store=29# and when I press back button it just removes the "#" from the URL and stays on the same page (shows the same div)

Any ideas how to fix that? Thanks


Solution

  • Instead of using href="#" use href='javascript:void(0)' This will prevent your URL from changing and effecting the back button

    html += '<p><a href="javascript:void(0)" title="' + places[i]['formatted_address'] + '" onclick="select_business(' + i + ');return true;">' +  places[i]['name'] + '</a><br/>' +  places[i]['formatted_address'] + '<br/>' +  places[i]['phone_number'] + '</p>';
    

    Using the # changes the URL which is stored in browser history and therefore most browsers will count it as a page change. javascript:void(0) does not have this effect and provides a convenient way to set up non-functioning a tags in your HTML

    As user skobaljic pointed out in the comments below, you could also keep the # and return false from your function:

    html += '<p><a href="#" title="' + places[i]['formatted_address'] + '" onclick="select_business(' + i + ');return false;">' +  places[i]['name'] + '</a><br/>' +  places[i]['formatted_address'] + '<br/>' +  places[i]['phone_number'] + '</p>';
    

    Note, usually if you are using an anchor tag with no href value you can easily substitute a span or some other inline element and not worry about this kind if issue. You can mimic the behavior of an a tag using css without having to worry about the links default behavior.