tags:

views:

116

answers:

1

Based on this answer - http://stackoverflow.com/questions/3778647/how-to-change-classes-on-click can somebody explain me what exactly the code below is doing?

$("a").click(function() {
  var $this = $(this); // this is just for performance
  if(!$this.hasClass('yy'))
    $('.yy').toggleClass("yy").toggleClass("xx");
  $this.toggleClass("yy").toggleClass("xx");
});

I mean the last two lines.

+10  A: 

First, it finds all of the a elements (links).

It sets their on-click actions to a function which:

  1. checks to see if that link currently has the yy CSS class.

  2. If it doesn't, then it turns off the yy class on everything which has it and toggles the xx on those that used to have the yy class.

  3. After that, it toggles the yy and xx classes on the link that was clicked.

Amber
One further way to clarify the code is to write `$('.yy').removeClass("yy").toggleClass("xx");` instead of `$('.yy').toggleClass("yy").toggleClass("xx");`.
Peter Ajtai