Mitch
Mitch

Reputation: 1394

jQuery reset css on active button when another button is clicked

I'm trying to style a group of buttons with jQuery. For the active button I want it to look different, so the user knows its active.

These buttons are being generated with a php foreach loop like this:

foreach($result as $row){
  echo "<a class='linkClass linkStyle' onclick='javascript:swapContent(" . $row['Count'] . "," . $row['ProductID'] . ");'>" . $row['Count'] . "</a>";
}

and i'm trying to style it with this jQuery click function:

$(document).ready(function() { $('.linkClass').eq(0).click(); })

$(".linkStyle").click(function() {       
   $(this).css("background","#258ace");
   $(this).css("border-top-color", "#258ace");
 });

The first bit clicks the first button so that when users come to the page they know what active content is being displayed. My problem is that when another button is pressed the styles are applied to it and they remain on the other button as well. I need a way to reset or remove the class of linkStyles when another button is pressed and only apply it to whatever button is active at the time.

Upvotes: 0

Views: 2449

Answers (3)

Polak
Polak

Reputation: 1493

Try first resetting all styles of all buttons affected and then apply your css. It could be:

$(".linkStyle").click(function() {       
   resetBtnStyles();
   $(this).css("background","#258ace");
   $(this).css("border-top-color", "#258ace");
});

I know it is dirty but it works...

Upvotes: 0

blurfus
blurfus

Reputation: 14031

you can always call:

$("#clicked-button-selector").addClass('active-css-class-name');

on the button clicked and then remove the style of the first button by calling:

$("#first-button-selector").removeClass('active-css-class-name');

Upvotes: 1

Robert McKee
Robert McKee

Reputation: 21477

Javascript:

$(".linkStyle").click(function() {    
   $('.linkStyle.active').removeClass('active');
   $(this).addClass('active');   
 });

CSS:

.linkStyle.active{
background:#258ace;
border-top-color:#258ace;
}

PHP:

$active=" active";
foreach($result as $row){
  echo "<a class='linkClass linkStyle".$active."' onclick='javascript:swapContent(" . $row['Count'] . "," . $row['ProductID'] . ");'>" . $row['Count'] . "</a>";
  $active="";
}

Upvotes: 6

Related Questions