Arete Arete - 7 months ago 41
HTML Question

Change background color of a div on hover from an array of colors

I am new to jQuery and I am experimenting a bit here. Please be patient.

I am trying to give div's a "random" background color on hover. If the div is not hovered I want them to be white.

I realize that random may not be the right word here because I want the script to chose a color from the following array, preferably in the same order:

['#009c61', '#cc0099', '#cc9900', '#cc0033', '#0099cc', '#6600cc', '#66cc00']


I guess some of the problem is because all divs have the same class.

How can this be achieved with jQuery?



jQuery(document).ready(function($) {

var bgColorArray = ['#009c61', '#cc0099', '#cc9900', '#cc0033', '#0099cc', '#6600cc', '#66cc00'],
selectBG = bgColorArray[Math.floor(Math.random() * bgColorArray.length)];

$('.article-container').css('background-color', selectBG)

});

.article-container {
color: #000;
font-family: 'Oswald', sans-serif;
text-align: center;
height: 200px;
width: 200px;
border: solid 3px #000;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="article-container">Div 1</div>
<div class="article-container">Div 2</div>
<div class="article-container">Div 3</div>
<div class="article-container">Div 4</div>





So far I have tried this:

jQuery(document).ready(function($) {

var bgColorArray = ['#009c61', '#cc0099', '#cc9900', '#cc0033', '#0099cc', '#6600cc', '#66cc00'],
selectBG = bgColorArray[Math.floor(Math.random() * bgColorArray.length)];

$('.article-container').css('background-color', selectBG)

});


Problem is this changes the color on page refresh and it changes the bg color of all divs.

Answer

Try to use .hover(mouseInHandler,mouseOutHandler) function at this context,

var colors = ['#009c61', '#cc0099', '#cc9900', '#cc0033', '#0099cc', '#6600cc', '#66cc00'];
$(".article-container").hover(function() {
    $(this).css("background-color", colors[(Math.random() * colors.length) | 0])
}, function() {
    $(this).css("background-color", "")
});

DEMO