Changing color of a div by clicking the first time and showing an alert by clicking the second time

Asked

Viewed 64 times

0

I’m having trouble creating a code that is simple, I need to click on a div she changes color and when clicking a second time she opens a alert stating the name of the color.

Can be in jQuery or js

$(document).click(function() {
  $(".cor").css("background", "blue");

});

$(".cor").click(function() {
  alert("HTML: " + $("#test").html());

});
  • Can you explain the logic of colors better? where the color comes from? each div will have a different color?

  • I don’t know how to do it in Javascript, but my tip would be to create the color patterns in CSS, when you want to change the color, change the CSS class defined in DIV; already to present a alert, declare a variable that serves as a counter and click, increment this variable and check for its value, whether or not to display Alert... Here you do not indicate the language you are using, it would help in case you post an example!!!!

1 answer

0

Here is an example, if there are any questions put in the comment.

$(function(){
  $('div').click(function(){
    console.log($(this).css('background-color'))
    if($(this).css('background-color') == 'rgb(204, 204, 204)'){
      $(this).css('background-color','rgb(255, 0, 0)');
    }else{
      alert('Cor da div : ' + $(this).css('background-color'));
    }
  });
});
div{
  width: 300px;
  height: 300px;
  background: rgb(204,204,204);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.