dancemc15 dancemc15 - 2 months ago 7
jQuery Question

How do I change the background of a paragraph to a random color on click with jQuery?

I want to change the background color whenever you click on one of the 3 paragraphs. I used a random color generator function and used jQuery to change the background color of the paragraph on click. However, I am not sure what I am doing wrong now.

Here's my jsfiddle: https://jsfiddle.net/vo7rs09g/

p {
width:400px;
height:300px;
background-color:blue;
}

<script>

var randomColor = Math.floor(Math.random()*16777215).toString(16);

$('p').click(function() {
$(this).css('background-color',randomColor());
});
};




<p></p>
<p></p>
<p></p>


Thanks in advance!

Answer

Try this :

$(document).ready(function() {
    
    $('p').click(function() {
        
        $(this).css('background-color',"#"+randomColor());
    })
    
    function randomColor() {
        
        return Math.floor(Math.random()*16777215).toString(16);
        
    }
})
 p {
  width:400px;
  height:300px;
  background-color:blue;
}
<p></p>
<p></p>
<p></p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>