最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to use jQuery to randomly toggle between classes - Stack Overflow

programmeradmin2浏览0评论

My goal is to mouse over a box and have it change color randomly. It's successful so far when I only have to choose one class to toggle ( i.e. $("#evtTarget").toggleClass(highlighted-2);). However, I'm trying to choose a random class from 5 different highlight classes. That way, every time I mouse over the box I want it to pick a random different color to change to. Here's my code so far:

jQuery

$(function() {
    $("#evtTarget").on("mouseover mouseleave", highlight);                
});

function highlight(evt) {
    $("#evtTarget").toggleClass(colors);        

    var number=(Math.floor((Math.random() * 5) +  1));
    var colors = "'highlighted'" + "-" + number;
}

CSS

.highlighted-1 {
    background-color:Blue;
}
.highlighted-2 {
    background-color:Purple;
}
.highlighted-3 {
    background-color:Green;
}
.highlighted-4 {
    background-color:Pink;
}
.highlighted-5 {
    background-color:Red;
}
.box{
    border: solid 1px black;
    height: 300px;
    width: 300px;
    background-color: gray;
}

HTML

<div id="evtTarget" class="box"><p>Random Highlight</p></div>

Please forgive the ignorance, I'm new here.

Thanks for any and all help!

My goal is to mouse over a box and have it change color randomly. It's successful so far when I only have to choose one class to toggle ( i.e. $("#evtTarget").toggleClass(highlighted-2);). However, I'm trying to choose a random class from 5 different highlight classes. That way, every time I mouse over the box I want it to pick a random different color to change to. Here's my code so far:

jQuery

$(function() {
    $("#evtTarget").on("mouseover mouseleave", highlight);                
});

function highlight(evt) {
    $("#evtTarget").toggleClass(colors);        

    var number=(Math.floor((Math.random() * 5) +  1));
    var colors = "'highlighted'" + "-" + number;
}

CSS

.highlighted-1 {
    background-color:Blue;
}
.highlighted-2 {
    background-color:Purple;
}
.highlighted-3 {
    background-color:Green;
}
.highlighted-4 {
    background-color:Pink;
}
.highlighted-5 {
    background-color:Red;
}
.box{
    border: solid 1px black;
    height: 300px;
    width: 300px;
    background-color: gray;
}

HTML

<div id="evtTarget" class="box"><p>Random Highlight</p></div>

Please forgive the ignorance, I'm new here.

Thanks for any and all help!

Share Improve this question edited Feb 26, 2016 at 19:28 Hunter Turner 6,92411 gold badges42 silver badges57 bronze badges asked Feb 26, 2016 at 18:51 EFHEFH 4411 gold badge6 silver badges15 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 4

Try to remove all the classes and add required class at this context, since toggleClass cannot be implemented here as it will toggle between 2 classes. Also increase the specificity for div.highlight-1 ... n classes. Because .box is having a property background-color.

$(function(){
  $("#evtTarget").on("mouseover mouseleave", highlight);                
});

function highlight() {
  var number= Math.floor(Math.random() * 5) + 1;
  var colors = "highlighted-" + number;
  $(this).removeClass().addClass('box ' + colors);        
}

DEMO

If you want to set different colors paring with previous color then just do a simple recursion.

$(function() {
  $("#evtTarget").on("mouseover mouseleave", highlight);
});

function highlight(e, $this) {
  $this = $this || $(this);
  var colors = "highlighted-" + getNumber();
  if ($this.hasClass(colors)) {
    highlight(null, $this);
    return;
  }
  $this.removeClass().addClass('box ' + colors);
}

function getNumber() {
  return Math.floor(Math.random() * 5) + 1;
}

DEMO

Edit:

As noted in the ments, you will want to remove the classes applied and wrap this entire feature inside of a function so you can call it on whatever event handler you prefer (mouseenter).

https://jsfiddle/rbyoj47j/2/

You could expand it further even if you want a TRULY random color by simply applying a HEX color picker and not using classes, but altering the style itself via javascript:

var $foo = $('#foo');
function getRandomColor() {
  var length = 6;
  var chars = '0123456789ABCDEF';
  var hex = '#';
  while(length--) hex += chars[(Math.random() * 16) | 0];
  return hex;
}
$foo.mouseenter(function(){
    $(this).css('background-color', getRandomColor());
});

https://jsfiddle/rbyoj47j/3/


If you're using predefined classes, and a specified amount of random classes you'd want to apply, you could use a switch case like this:

var rand = Math.floor((Math.random() * 5) + 1);
var element = $('#foo');
switch(rand){
  case 1:
    element.addClass('blue');
    break;
  case 2:
    element.addClass('pink');
    break;
  case 3:
    element.addClass('red');
    break;
  case 4:
    element.addClass('green');
    break;
  case 5:
    element.addClass('yellow');
    break;
}

View Here:

https://jsfiddle/rbyoj47j/

You were very close. I only made a couple of tweaks:

  • var colors = "'highlighted'" + "-" + number; didn't need the inner quotes (apostrophes)
  • .box needs to e before the .highlighted styles since it needs to be overridden by them
  • I set the class attribute of the div

Here's the updated code:

<script src="https://ajax.googleapis./ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<script type="text/javascript">

  $(function() {
    $("#evtTarget").on("mouseover mouseleave", highlight);
  });

  function highlight(evt) {
    var number=(Math.floor((Math.random() * 5) +  1));
    var colors = "highlighted" + "-" + number;
    $(this).attr('class', 'box ' + colors);
  }

</script>

<style type='text/css'>

  .box {
    border: solid 1px black;
    height: 300px;
    width: 300px;
    background-color: gray;

  }
  .highlighted-1 {
    background-color:Blue;
  }
  .highlighted-2 {
    background-color:Purple;
  }
  .highlighted-3 {
    background-color:Green;
  }
  .highlighted-4 {
    background-color:Pink;
  }
  .highlighted-5 {
    background-color:Red;
  }
  
</style>

<div id="evtTarget" class="box"><p>Random Highlight</p></div>

Another approach would be something like this.

<script src="https://ajax.googleapis./ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<script type="text/javascript">

  $(function() {
    $("#evtTarget").on("mouseover mouseleave", highlight);
  });

  var colors = ['blue', 'purple', 'green', 'pink', 'red'];

  function highlight(evt) {
    var number= Math.floor(Math.random() * 5);
    $(this).attr('style', 'background-color:' + colors[number]);
  }

</script>

<style type='text/css'>
  .box{
    border: solid 1px black;
    height: 300px;
    width: 300px;
    background-color: gray;
  }
</style>

<div id="evtTarget" class="box"><p>Random Highlight</p></div>

Cheers!

Here's the working example:

function highlight(evt) {
  var index = (Math.floor((Math.random() * 5) +  1));
  var color = "highlighted" + "-" + index;
  $("#evtTarget").attr('class', 'box'); // this resets the class back to box
  $("#evtTarget").addClass(color);        
}

$("#evtTarget").on("mouseover mouseleave", highlight);

And fiddle https://jsfiddle/2gt9hmmd/3/

Now, for the errors.

  1. CSS is case sensitive, so Red !== red.
  2. .box background-color is declared after the highlights, and having the same priority, the .box style always overrides the highlights.
  3. You don't need those extra arrows inside the highlight class string.
  4. You don't need to wrap that first function in another one.
  5. Toggle class just adds and removes the same color, it's on/off.
  6. It's better to declare functions above using them, it improves readability
  7. Try not to use words like number for variable names, it's much better when all variables make sense and describe what they store. It's not an error, just will make your life easier.
发布评论

评论列表(0)

  1. 暂无评论