Search code examples
javascriptjquerycolors

JavaScript not working the first time but works after refresh


I want the links to change to a random color every time I hover on them. It only works after I refreshed the page. Does anyone know why this happened? I don't have a lot of experience with JavaScript.

$(document).ready(function() {
  $( "a" ).hover(function() {
    $ (this).css("color",getRandomColor());
    }, function() {
      $(this).css("color","");
    }
  );

  function getRandomColor () {
    var letters = '0123456789ABCDEF'.split('');
    var color = '#';
    for (var i = 0; i < 6; i++) {
      color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
  }
})
a {
  color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h2><a href="https://www.google.com/">TEST</a></h2>

I tried to modify the script but failed to make it work.


Solution

  • Are you dynamically loading <a> after the page loads? The code you are using will only bind to the <a> on the page when it runs, which could result in an asynchronous timing issue.

    Also, from the hover docs:

    This API is deprecated. Use .on( "mouseenter", handlerIn ).on( "mouseleave", handlerOut ) instead.

    Using the .on() method allows you to provide a selector for the second argument, which works great for dynamically added content, because you put the handler on the static parent element, rather than each dynamically added element:

    $('body')
      .on('mouseenter', 'a', handlerIn )
      .on('mouseleave', 'a', handlerOut );
    

    Here is an example of randomly added anchors that randomly change color on hover:

    $('body')
      .on('mouseenter', 'a', function() {
        this.style.color = RndHexClr();
      })
      .on('mouseleave', 'a', function() {
        this.style.color = '';
      });
      
      
      
    function RndHexClr () {
      return '#' + '123456'.split('').map(() =>
        '23456789ABCDEF'.split('')[Math.floor(Math.random() * 14)]).join('');
    }
     
     $('body').append('0123456789'.split('').map(() => `<a>${RndHexClr()}</a>`));
    a { display: block; }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>