Reputation: 163
I am trying to use JQuery to change the background color of my page, by cycling through an array of colors, every time the button (with ID = "findOut") is clicked - but it does not seem to be working?
HTML (for the button):
<div class = "mainContain">
<button id = "findOut">
<p>Click Me!</p>
</button>
</div>
JS/JQuery:
$("document").ready(function(){
var palette = ["red", "blue", "green", "yellow", "pink", "orange"];
var index = 0;
var size = palette.length;
$("#findOut").click(function(){
document.body.style.background = pallete[index%size];
index++;
});
});
Upvotes: 0
Views: 102
Reputation: 10148
Before OP's edit :
You are actually assigning the same color red
whenever you click on it. You'll have to choose a different color each time you click on it. Choose it from array by something like
palette[index % size]
You are already increment index
take a remander with size of array to repeat when index increases the size of the array
And to make it consistent with jQuery
, use $("body").css('background-color','color')
to change color
After edit :
You've a type in your code pallete
should be pallette
$("document").ready(function(){
var palette = ["red", "blue", "green", "yellow", "pink", "orange"];
var index = 0;
var size = palette.length;
$("#findOut").click(function(){
$("body").css('background-color', palette[index % size]);
index++;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class = "mainContain">
<button id = "findOut">
<p>Click Me!</p>
</button>
</div>
Upvotes: 1
Reputation: 4335
Just use:
$(body).css('background-color', 'red');
Or:
document.body.style.backgroundColor = 'red';
Upvotes: 0
Reputation: 1093
Edit: After you edited the question and inserted the correct code the actual problem you have comes from your misspelling of palette
as pallete
.
$("document").ready(function() {
var palette = ["red", "blue", "green", "yellow", "pink", "orange"];
var index = 0;
var size = palette.length;
$("#findOut").click(function() {
document.body.style.background = palette[index % size];
index++;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="mainContain">
<button id="findOut">
<p>Click Me!</p>
</button>
</div>
Upvotes: 1