pawel
pawel

Reputation: 31

.toggle class. is it possible that

I uploaded here my problem: my problem example

My question: Is it possible that 'content B def' is visible first after page is loaded (or after refreshing) without modifying order of

<a> href="..." C </a>
<a> href="..." B </a>
<a> href="..." A </a>

I want C B A order. Not B C A or B A C My javascripting knowledge is basic but it's increasing fast..

Sorry for my english,

Thanks a lot for suggestions! I'm struggling with this problem for a few days now.

HTML code:

    <html>
   <head>
      <meta content="charset=utf-8" />
      <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
      <script defer src="js/swap.js"></script> 
   </head>
   <body>
      <div>
         <div id="view-c" class="swap-cont">
            <h1>content C xyz</h1>
         </div>
         <div id="view-a" class="swap-cont">
            <h1>content A abc</h1>
         </div>
         <div id="view-b" class="swap-cont">
            <h1>content B def</h1>
         </div>
         <div class="toggle">
            <a href="#view-c">C</a>
            <a href="#view-b">B</a>
            <a href="#view-a">A</a>
         </div>
      </div>
   </body>
</html>

swap.js:

    $(function() {
    var toggles = $('.toggle a'),
        codes = $('.swap-cont');

    toggles.on("click", function(event) {
        event.preventDefault();
        var $this = $(this);

        if (!$this.hasClass("active")) {
            toggles.removeClass("active");
            $this.addClass("active");
            codes.hide().filter(this.hash).show();
        }
    });
    toggles.first().click();
});​

Upvotes: 3

Views: 93

Answers (1)

Michal Klouda
Michal Klouda

Reputation: 14521

All you need is to change the last line of your script from:

toggles.first().click();

to:

toggles.eq(1).click();

This line initializes your view by triggering click on default anchor.

You were clicking the first anchor, which is C. B is actually second, therefore you need to use the .eq() method, which selects the n-th element from the set and is documented here.

Alternative (cleaner) approach would be adding a defaultAnchor class to default anchor and modify the script to:

 $('.defaultAnchor').click();

Upvotes: 2

Related Questions