Alfred
Alfred

Reputation: 11

jump to named anchor with javascript

I have a php (codeigniter) program that displays all the finished projects of and engineering company. I can click the detail page and from there I can click a link to go back to the overview page. To avoid starting at the top of the list again I would like to jump to the project I cam from. It seems easy but it gives me problems. I found this solution on the Internet that works with Chrome but not with Firefox and IE:

<script type="text/javascript" language="javascript">
    function moveWindow (){window.location.hash="a13";}
</script>
<body onload="moveWindow()">
.
.
.
<a name="a13"></a>

The content of the anchor gets dynamically generated by PHP. As I said it works in Chrome only. IE says something like undefined function moveWindow when I go in debug mode.

Upvotes: 1

Views: 1400

Answers (1)

Capsule
Capsule

Reputation: 6159

You can attach a function to the details click that change the URL to currentURL#yourID and then change it to the final URL. This way, currentURL#yourID will be stored in the history of the browser and going back will get you to the right anchor.

Something like (assuming you use jQuery and your IDs are on the <a>):

$(document).ready( function() {
    $('#yourlist a').click( function(e) {
       e.preventDefault();
       window.location = '#'+$(this).attr('id');
       window.location = this.href; // intentionally not using jQuery ;-)
    });
});

The HTML would look like:

<ul id="yourlist">
    <li><a href="details_page_for_item_1.html" id="a1">Item 1</a></li>
    <li><a href="details_page_for_item_2.html" id="a2">Item 2</a></li>
    <li><a href="details_page_for_item_3.html" id="a3">Item 3</a></li>
</ul>

Not tested...

Upvotes: 4

Related Questions