Question

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);
    }
});
});
Was it helpful?

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})
  });
});

OTHER TIPS

Here's a full simple example:

HTML:

<p class="alphabet">abcdefghijklmnopqrstuvwxyz</p>

JavaScript:

// Your container
var $wrap = $('p.alphabet');

// Wrap all letters in <span>
$wrap.html(function(){
  return $(this).text().replace(/./g, '<span class="letter">$&</span>');
});

// Attach the event
$wrap.find('.letter').click(function(){
  var isHidden = $(this).css('opacity') == .5;
  $(this).fadeTo(300, isHidden ? 1 : .5);
});

Demo: http://jsbin.com/eyajel/1/edit

The opacity can just be done with css transitions and regular old styles.

The CSS

.letter {
    transition: opacity 1s;
    color: red;
    cursor: pointer;
}
.letter.active {
    opacity: 0.2;
}

The Javascript

$('body').on('click', '.letter', function(e){
    $(this).toggleClass('active');
});

Here is a JSFiddle as an example. It also includes a way to take a string of letters and turn them into markup that works with this: http://jsfiddle.net/PFjnB/1/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top