Reputation: 1229
I have three columns within my webpage. On each column there are a group of three squares, the square represent a unique colour. So when the user clicks on red in column 1 the text within column 1 goes red, if blue it will go blue. If the user clicks on green within column 2 the text within column 2 will go green.
I am new to jQuery so I am not sure if I have done this right and would like to know if this is the best way of doing it.
What I want to know is there anyway of changing this so there is only one style called picker for all in each column. Also can I change the jQuery so it's not 3 seperate functions, is there a more cleaner way of doing this?
Thanks.
Upvotes: 1
Views: 168
Reputation: 36531
yes there is.. change all you class(picker1,picker2) to picker
and remove the id (test,test1..)
try this
$('.picker').each(function(){
var myColor = $(this).data('color');
$(this).css({background: myColor })
});
$('.picker').click(function(){
var myColor = $(this).data('color');
$(this).parent().css({color: myColor});
});
NOTE: you don't need click
event inside each
loop
Upvotes: 0
Reputation: 123739
You may try this way:
$(function () {
$('.picker').css('background-color', function () { //Setup the background color for each picker square.
return $(this).data('color'); //get its color from data attribute
}).click(function () { //Chain it through for the click event
$(this).closest('.content').css({ //get the parent content element where color needs to be applied
color: $(this).data('color') //set the color as that of the clicked picker.
});
});
});
In the markup provide a class called say content
to identify its own parent content.
<div class='col2 content' id="test1"> <!-- You don't need id if you are using this for selcting.
Remove all the picker1, 2
css rules and have just the picker
.
Using closest
will ensure that even if you plan to add a wrapper to your picker still your actuall content div will be selected.
Upvotes: 0
Reputation: 4234
Yes! CSS selectors are all reusable! you shouldn't created multiple class' with the exact same attributes and values!
all the css classes you need .col, .wrapper, .picker
and then working with jQuery instead of using a div id when you want to use the code in mulitple places, work out where the element is relative to the element that fired the event or $(this)
check out the fiddle http://jsfiddle.net/WJ5DZ/1/
Upvotes: 2