3

I have a home page that has extensive jQuery...Hiding and showing divs based on clicks of tabs etc. Within the shown div's there are links to other pages which postback and get the new page.

Now i would like a 'back' button on the page to go back to the previous state of the page when the user clicked on it. So if they had the Sell_your_books div shown and 'Sell_your_books tab' selected when they clicked the link, I would like to have a back button going to the home page with the Sell_your_books div shown and 'Sell_your_books tab'selected.

I know that I will have to parse (POST) a variable to the homepage to achieve this with php but I am unsure of the correct way to implement it.

Thanks

tread
  • 10,133
  • 17
  • 95
  • 170

2 Answers2

2

Use hash hyperlinks and the hashchange event. In jQuery:

$(window).on('hashchange',function() {
    var hash = location.hash.substring(1); // strip the leading # symbol
    // now run code based on whatever the value of 'hash' is
});

HTML

<a href="#hash1">function A</a>
<a href="#hash2">function B</a>

Now, whenever the user clicks the browser's "back" button (or an HTML button that triggers history.go(-1)), it will go back to whatever hash was previously selected and trigger the hashchange event again.

MORE DETAILS

Community
  • 1
  • 1
Khawer Zeshan
  • 9,470
  • 6
  • 40
  • 63
  • Thanks, this is the easier quick fix method. The browser defaults to scroll till that div is found...how do i stop that? – tread Jun 19 '13 at 12:23
0

Create a hidden input field and fill this one with the current active tab.

<form>
 ..
 <input type="hidden" name="currentTab" value="" />

</form>

A bit of jQuery to set the right value:

$( YOUR TAB SELECTOR ).on('click', function() { 
 $('input[name=currentTab]').val( $(this).attr('id') ); 
});

In the PHP-Script which handles you data, you can create a back link like this:

<?php

 if( isset($_POST['currentTabe']) && $_POST['currentTab'] != '' ) {
   $backLink = "your_page.php?tab=" . $_POST['currentTab'];
 }

?>

If you now call your site with tabs trough the backlink, you can create a additional document.ready event, which set's the active tab to the PHP $_GET Parm.

<script type="text/javascript">
 <?php
  if( isset($_GET['tab']) && $_GET['tab'] != '' ) {
 ?>
  jQuery(document).ready( function() {

   var tab = $('#'+ <?=htmlspcialchars( $_GET['tab'] )?>);
   if( tab.length <= 0 ) return false; //element not found

   //active tab
   tab.toggle('click'); //click or do something else to activate the current tab

  });
 <?php 
  }
 ?>
</script>

Attention: Beware of XSS (Cross-Site-Scripting), so check your $_POST and $_GET for correct values.

Marco
  • 67
  • 2