Raphael Bergeron Raphael Bergeron - 6 months ago 28
jQuery Question

Randomize border color on hover

I have this script that randomize the color of my border img on hover, but it also removes my basic border when I leave the img..(from the start all my img have a grey border, and I'd like this border to alway stay there and not be removed)

script>
$(function() {
var colors = ["#FC3E6B","#24FF00","#0087F9","#F9F900"];

$('.grid-item-content').hover(
function() {
var rand = Math.floor(Math.random()*colors.length);

$(this).css('border-style', 'solid');
$(this).css('border-width', '10px');
$(this).css('border-color', colors[rand]);
},
function() {
$(this).css('border-style', 'none');
}
);
});
</script>

Answer

Hi you can do this easily by removing the inline style attribute

$(function() {
  var colors = ["#FC3E6B","#24FF00","#0087F9","#F9F900"];

  $('.grid-item-content').hover(
    function() {
      var rand = Math.floor(Math.random()*colors.length);
      $(this).css('border-style', 'solid');
      $(this).css('border-width', '1px');
      $(this).css('border-color', colors[rand]);
    },
    function () {
        $(this).removeAttr('style');
    }
  );
});

Working fiddle: https://jsfiddle.net/jdro6qch/