user2103008
user2103008

Reputation: 524

jQuery tabs multiple refresh with # url

I'm learning how to use jquery and had a noob question. From jquery-ui(http://jqueryui.com/tabs/#ajax):

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>jQuery UI Tabs - Content via Ajax</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<script>
$(function() {
  $( "#tabs" ).tabs({
    beforeLoad: function( event, ui ) {
      ui.jqXHR.error(function() {
        ui.panel.html(
          "Couldn't load this tab. We'll try to fix this as soon as possible. " +
          "If this wouldn't be a demo." );
      });
    }
  });
});
</script>
</head>
<body>

<div id="tabs">
<ul>
  <li><a href="#tabs-1">Preloaded1</a></li>
  <li><a href="#tabs-2">Preloaded2</a></li>
</ul>
<div id="tabs-1">
  <p>Proin elit arcu, rutrum commodo, vehicula tempus, commodo a, risus. Curabitur nec arcu. Donec sollicitudin mi sit amet mauris. Nam elementum quam ullamcorper ante. Etiam aliquet massa et lorem. Mauris dapibus lacus auctor risus. Aenean tempor ullamcorper leo. Vivamus sed magna quis ligula eleifend adipiscing. Duis orci. Aliquam sodales tortor vitae ipsum. Aliquam nulla. Duis aliquam molestie erat. Ut et mauris vel pede varius sollicitudin. Sed ut dolor nec orci tincidunt interdum. Phasellus ipsum. Nunc tristique tempus lectus.</p>
</div>
<div id='tabs-2'>
Look, it's working!
</div>
</div>
</body>
</html>

When I try to use this html file with #tabs-1 appended to the URL, it works fine. However, after changing the URL to #tabs-2, nothing happens. I have to refresh it again to make the second tab appear. Is there a way to make this happen by refreshing only once ?

Upvotes: 0

Views: 197

Answers (1)

MaveRick
MaveRick

Reputation: 1191

$(function() {
  $( "#tabs" ).tabs({
    beforeLoad: function( event, ui ) {
      ui.jqXHR.error(function() {
        ui.panel.html(
          "Couldn't load this tab. We'll try to fix this as soon as possible. " +
          "If this wouldn't be a demo." );
      });
    }
  });
    $(window).on('hashchange', function() {
      $("div#tabs a[href="+window.location.hash+"]").click();  
    });
});

Upvotes: 1

Related Questions