arrays - Continuously loop colors on div using javascript on mouseenter -


i have div on page , continuously cycle through set of colors using javascript.

i've seen number of articles on stack overflow continuous loops show information using arrays , javascript yet have had trouble trying implement own project.

my html:

<div id="box" style="background:grey;" onmouseenter="change()"></div> 

and closest js solution can find:

var change = function() {     colors = ['#00b0e2', '#e3144e', '#15e39b'];     count = -1;     return function() {         return colors[++count % colors.length];     }     document.getelementbyid('box').style.background = colors; // or should **colors[]**? } 

i understand happening until return function having trouble understanding how inject color html?

any or tips appreciated thanks.

i think close, missing couple of key things.

firstly, when onmouseover="change()" means run change() every time mouseover runs unlike using addeventlistener(change()) run function returned change event handler.

secondly change element, need handle on element , set background.

the code below think trying more simply. hope helps.

// setup our colors , state once  colors = ['#00b0e2', '#e3144e', '#15e39b'];  count = -1;    var change = function(element) {    element.style.background = colors[++count % colors.length];   }
<!-- pass in element when creating change listener -->  <div id="box" style="background:grey;" onmouseenter="change(this)">    give our box contents can see it.  </div>

explanation:

the basic concept behind loop have count tells colors[count] active.

when mouseover happens, 3 things happen in 1 line.

  • ++count: adds 1 count, unlike count++, before value used. meaning first time mouseover occurs, value of count 0

  • count % colors.length: lets wrap around first color once has hit last color. % (modulus) operator gives remainder. a % b return remainder after dividing a / b. if count = 0, count % 3 yields 0, if count = 4, count % 3 yields 1. can read more , other arithmetic operators on mdn

  • element.style.background = colors[...]: sets background css attribute color selected in last step.

so put together, here change function broken out 3 lines.

var change = function(element){     count++; //increment count before using it.     var our_color = count % colors.length; // wrap     element.style.background = colors[our_color]; } 

Comments

Popular posts from this blog

jOOQ update returning clause with Oracle -

java - Warning equals/hashCode on @Data annotation lombok with inheritance -

java - BasicPathUsageException: Cannot join to attribute of basic type -