Gerald
Gerald

Reputation: 1083

jQuery toggle not working when back button is hit

I have the following jQuery code:

$(function() {
    var linkSet = $('#link1').add('#link2');
    linkSet.click(function() {
    linkSet.toggle();
        if ($(this).attr('id')=='link1'){
        $('#frame').attr('src', 'www.google.com');
        } else if ($(this).attr('id')=='link2'){
        $('#frame').attr('src', 'www.yahoo.com');
        }
    });
});

On pageload, the link with id link1 is shown while link2 is hidden. When the user click the link1, it will the link1 then show the link2 then vice versa. While toggle takes place, it also changes the source of an iframe which is named frame.

My problem here is when I hit back button, the content of the frame will go back to its previous content BUT the link are not changing. What did I missed here? Thanks in advance!

Note: The links are on a webpage, then inside that webpage is an iframe.

EDIT:

<div id="header">
<ul>
    <li><a id="link1" href=#">Link1</a>
    <li><a id="link2" href=#">Link2</a> 
</ul>
</div>
<div id="iframe">
    <iframe id="frame" src="www.google.com"></iframe>
</div>

Upvotes: 0

Views: 956

Answers (1)

Andres Gallo
Andres Gallo

Reputation: 681

You mean when pressing the browser's back button right.

If so:

The issue is you need to have an event to trigger when the history changes, as that is the only easy way to respond to changes in history (such as when clicking the back button). Since the iframe url is indeed changing, it is therefore also affected by the back button naturally.

To get other non history based logic to work when pressing the back button and such... There are two ways to do this. The new one is by using the history API, while the other more supported, and simpler way is by adding a hash to the url.

WHAT DOES THIS MEAN?

When you click the button you change the url with a hash. Like the url can become

'http://domain.com/blah/#myHash'

Then instead of doing your logic in the click, you do it when the hash changes. So this way as the user clicks back and/or forward the logic always runs fully.

I wrote an entire article about this technique a few months ago at http://andresgallo.com/2012/06/08/ajaxifying-the-web-the-easy-way/

Upvotes: 1

Related Questions