Reputation: 3
I want to change the website logo color and the hover color of the buttons every time a user refreshes the pages. The colors have to be coordinated. Website Link The logo is actually an image with a transparent region, where I can put any background color I want.
Someone had a similar problem here: JQuery Random Background color and color, on 2 div's
This is the javascript that I made based on that thread:
$(document).ready(function(){
var colors = ["#fda65f","#66CCFF","#71e271","#D37AFF"];
var rand = Math.floor(Math.random()*colors.length);
$('#logo').css("background-color", colors[rand]);
$('.cbp-ig-grid').css("background-color", colors[rand]);
});
.cbp-ig-grid changes the background color properly, but I want the color to appear only on hover. The .cbp-ig-grid class has this hover property:
.cbp-ig-grid li > a:hover { background-color:#71e271;}
The problem is that if I change the javascript code '.cbp-ig-grid' with '.cbp-ig-grid li > a:hover' it stops working. I have no experience with Javascript, so I'm definitely doing something wrong.
Upvotes: 0
Views: 1195
Reputation: 6442
i would be more inclined to print out a <style>
sheet using javascript than add hover()
events using jquery
<script>
var colors = ["#fda65f","#66CCFF","#71e271","#D37AFF"];
var rand = Math.floor(Math.random()*colors.length);
var head = document.head,
style = document.createElement('style');
var css = '#logo { background-color: ' + colors[rand] + '; } ';
css += '.cbp-ig-grid li > a:hover { background-color: ' + colors[rand] + '; } ';
style.type = 'text/css';
if (style.styleSheet){
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
head.appendChild(style);
</script>
Upvotes: 1
Reputation: 3194
What you're doing is this:
replace $('.cbp-ig-grid').css("background-color", colors[rand]);
with $('.cbp-ig-grid li > a:hover').css("background-color", colors[rand]);
is that correct?
anyways, you can't control the hover state with a jQuery selector: $('.cbp-ig-grid')
you can achieve this by setting a event handler with a function like this:
$(document).ready(function(){
var colors = ["#fda65f","#66CCFF","#71e271","#D37AFF"];
var rand = Math.floor(Math.random()*colors.length);
$('#logo').css("background-color", colors[rand]);
$(".cbp-ig-grid li").on("mouseover", function () {
$(this).css("background-color", colors[rand]);
});
}
Upvotes: 0
Reputation: 1642
Use this
$('.cbp-ig-grid li > a').hover(function(){
$(this).css("background-color", colors[rand]);
});
Upvotes: 0
Reputation: 1468
Try using hover()
method :
$('.cbp-ig-grid').hover(function() {
$(this).css("background-color", colors[rand]);
});
Upvotes: 1