javascripttogglefadingfadeto

Toggling between two different Opacities


I have all 26 letters in the alphabet and I want to make it so that when you click on it will fade to a lower opacity but if you click on it again it will come back to 1.0 opacity. I have not a single clue on how I would go about specifically choosing the letter that was clicked on and I also cant seem to figure out how I would toggle it to a specific opacity.

$(document).ready(function() {
$(".alphabetLetter").click(function(event) {
    var x = event.target||event.srcElement;
    if(event.target.style.opacity == 1.0){
        $(x).fadeTo('slow',0.5);
    } else if(event.target.style.opacity == 0.5){
        $(x).fadeTo('slow',1.0);
    }
});
});

Solution

  • You can select for the currently clicked element by using $(this) inside the click event handler.

    $(document).ready(function() {
      $(".alphabetLetter").click(function(event) {
          if ($(this).css('opacity') == '1')
            $(this).animate({'opacity':0})
          else
            $(this).animate({'opacity':1})
      });
    });