Phil Shotton
Phil Shotton

Reputation: 105

jQuery won't change class attribute

I am trying to create a simple pagination control, here is the code:-

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<title>Untitled Document</title>
<script type="text/javascript">

  $(document).ready(function() {
    $(".pageTab").click(function(e) {
      $("#pagination > a > div").attr("class", "pageTab");
      $(this).attr("class", "pageSelect");
    });
  });

</script>

<style>
  #pagination{width:100%; height:20px; float:left; margin-left:235px;}
  .pageTab{width:14px; height:16px; padding:2px 0px 2px 6px; margin-right:2px; background-color:#fff; border:1px solid #999; color:#0066FF; font-size:11px; cursor:pointer; float:left;}
  .pageTab:hover{width:14px; height:16px; padding:2px 0px 2px 6px; margin-right:2px; background-color:#CCC; border:1px solid #999; color:#0066FF; font-size:11px; cursor:pointer;float:left;}
  .pageSelect{width:14px; height:16px; padding:2px 0px 2px 6px; margin-right:2px; background-color:#CCC; border:1px solid #999; color:#0066FF; font-size:11px; cursor:pointer;float:left;}
</style>
</head>

<body>

    <div id="pagination">

        <a href="#gPage1" class="blue">
        <div id="g1" class="pageSelect">1
        </div>
        </a>

        <a href="#gPage2" class="blue">
        <div id="g2" class="pageTab">2
        </div>
        </a>

        <a href="#gPage3" class="blue">
        <div id="g3" class="pageTab">3
        </div>
        </a>

        <a href="#gPage4" class="blue">
        <div id="g4" class="pageTab">4
        </div>
        </a>

        <a href="#gPage5" class="blue">
        <div id="g5" class="pageTab">5
        </div>
        </a>

        <a href="#gPage6" class="blue">
        <div id="g6" class="pageTab">6
        </div>
        </a>

    </div>  
</body>

If you click on the numbers 2-6, the class is changed and the correct colour scheme applied. But when you click on number 1 the class remains the same.

It seems to have something to do with whichever DIV starts life with the pageSelect class. If you change number 2 to pageSelect in the code and load the page, then numbers 1 and 3-6 are fine, but number 2's class will not change.

Any ideas?

Upvotes: 2

Views: 311

Answers (2)

Eli
Eli

Reputation: 14827

Try changing:

$(this).attr("class", "pageSelect");

to:

$(this).addClass('pageSelect').removeClass('pageTab');

Upvotes: 2

user571545
user571545

Reputation:

Change your click selector to:

 $(".pageTab, .pageSelect").click(function(e) { ... }

Upvotes: 1

Related Questions