Hi the code I am trying to simplify is:
$(document).ready(function(){
$('.selection0').click(function() {
$('.selection0').css('background-color', 'white');
$(this).css('background-color', 'yellow');
});
$('.selection1').click(function() {
$('.selection1').css('background-color', 'white');
$(this).css('background-color', 'yellow');
});
$('.selection2').click(function() {
$('.selection2').css('background-color', 'white');
$(this).css('background-color', 'yellow');
});
$('.selection3').click(function() {
$('.selection3').css('background-color', 'white');
$(this).css('background-color', 'yellow');
});
$('.selection4').click(function() {
$('.selection4').css('background-color', 'white');
$(this).css('background-color', 'yellow');
});
});
I feel like I must be missing something, and that there is a way to make this much cleaner. Thanks!
Edit: I just wanted to clarify the functionality of this code. Basically, each 'selection' class corresponds to span tags around sentences in a paragraph. The code allows the user to highlight exactly one sentence in each paragraph by clicking on it. If it clicks on a different sentence, that sentence will be highlighted while the rest of the sentences in that specific paragraph is deselected.
It would be easier to have a single class and have the following code :
$('.selection').click(function() {
$(this).css('background-color', 'white').css('background-color', 'yellow');
});
Seems like odd code, though... I'm guessing your just wanting it to flash when you click it?
EDIT to Add : Remember, you can have more than one class on an object... ie <div class="selection selection1> etc...
EDIT 2 :
From your update and posted HTML, make all of your spans have the same class and use this :
$('.selection').click(function() {
$(this).css('background-color', 'yellow').siblings().css('background-color', 'white');
});
http://jsfiddle.net/shaneblake/9pF6U/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With