Haque1
Haque1

Reputation: 593

Finding index of element that was selected

I'm following Semmy Purewal's book Learning Web App Development to learn html/css, javascript, jQuery, etc. In one of his examples, the reader has to make three tabs on a web page and write code to make the tab that is clicked on by the user have a class called "active".

Before I can add that class to the clicked tab, I need to find out its index -- and this is where I'm having a problem.

This is my HTML code:

<!doctype html>
<html>
  <head>
    ...
  </head>

  <body>
    <header>
      ...
    </header>

    <main>
      <div class="container">
        <div class="tabs">
          <a href=""><span class="active">Newest</span></a>
          <a href=""><span>Oldest</span></a>
          <a href=""><span>Add</span></a>
        </div>
        <div class="content">
          <ul>
            ...
          </ul> 
        </div>
      </div>
    </main>

    <footer>
      ...
    </footer>

    <script src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
    <script src="app.js"></script>
  </body>
</html>

This is my jQuery code to get the index of the tab selected by the user (strongly influenced by Purewal):

var makeActiveTab = function(tabNum) {
    //make all the tabs inactive
    $(".tabs span").removeClass("active");

    //make the first tab active
    $(".tabs a:nth-child(" + tabNum + ") span").addClass("active");

    //empty the main content so we can recreate it
    $("main .content").empty();

    //return false so we don't follow the link
    return false;
};

var main = function() {
    "use strict";
    var index;
    $(".tabs a").click("click", function() {
        index = $(this).index();
    });

    console.log(index);
};

$(document).ready(main);

Instead of getting the index of the clicked tab, the console is outputting "undefined". What can I do to fix this problem?

Here's a list of sources I have consulted so far:

Upvotes: 1

Views: 67

Answers (1)

firefoxuser_1
firefoxuser_1

Reputation: 1839

You need to move the console.log() into the click event, like this:

var main = function() {
    "use strict";
    var index;
    $(".tabs a").click("click", function() {
        index = $(this).index();
        console.log(index);
    });


};

Right now, the console.log() runs as soon as the document ready occurs, because it runs whenever main is executed. Because no click event has occurred yet, there is no value to the index variable.

Upvotes: 2

Related Questions