Sam
Sam

Reputation: 1229

Change colour of text on click using jQuery

I am new to jQuery and I have no idea about where to begin with this. On my webpage I have text and I want to put at the top four squares where the user can click on a square and this will change the colour of the text.

I am hoping to make the squares using CSS with the squares being red, yellow, green and black.

From this I need to create a colour picker using jQuery where the user will click a square and this will change the text into the appropriate colour.

Upvotes: 2

Views: 2412

Answers (1)

Roko C. Buljan
Roko C. Buljan

Reputation: 206028

http://jsbin.com/emical/1/edit

  <div class="picker" data-color="red"></div>
  <div class="picker" data-color="green"></div>
  <div class="picker" data-color="blue"></div>
  <div class="picker" data-color="black"></div>

  <div id="test">TEST DIV THAT WILL CHANGE COLOR</div>

...where eg: instead of "red" you can also use HEX: "#f00" or "#ff0000" or "rgb()", "rgba()"... etc etc :)

CSS:

.picker{

  cursor:pointer;
  margin:3px;
  width:30px;
  height:30px;
  float:left;

}

jQuery:

$('.picker').each(function(){
  $(this).css({background: $(this).data('color')}); // set BG color for every element
}).click(function(){
  $('#test').css({color: $(this).data('color')});  // change Target's text color on click
});

http://api.jquery.com/each/
http://api.jquery.com/css/
http://api.jquery.com/click/

or like this:

$('.picker').each(function(){

  var myColor = $(this).data('color');

  $(this).css({background: myColor }).click(function(){
    $('#test').css({color: myColor});
  });

});

Upvotes: 2

Related Questions