Guide to utilizing jQuery for random toggling of classes

My objective is to create a mouseover effect on a box that changes its color randomly. Currently, I have managed to achieve this by toggling one class (e.g.

$("#evtTarget").toggleClass(highlighted-2);
). However, I am now attempting to select a random class from a pool of 5 different highlight classes. This means that every time the box is moused over, it will switch to a new random color. Here is my current code:

jQuery

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

function highlight(evt) {
    var number = Math.floor((Math.random() * 5) + 1);
    var colors = "'highlighted'" + "-" + number;
    $("#evtTarget").toggleClass(colors);        
}

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>

I appreciate your patience with me as I am still learning.

Thank you for any assistance provided!

Answer №1

It is recommended to remove all classes and only add the required class in this specific context. Using toggleClass may not work here as it toggles between two classes. Additionally, consider increasing the specificity for div.highlight-1 ... n classes, especially since .box has 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 wish to use different colors than the previous one, you can implement 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

Answer №2

Note:

It is recommended to remove the applied classes and encapsulate this feature within a function so that you can invoke it with your preferred event handler such as mouseenter.

Visit this link for demonstration

If you want to take it further and achieve a TRULY random color, consider using a HEX color picker and directly modifying the style through 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());
});

Demo available here


In case you are working with predefined classes and wish to apply a specific number of random classes, you can utilize a switch case like the following example:

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 the practical demonstration by clicking on this link:

Explore more here

Answer №3

You were so close! Just a few adjustments needed:

  • var colors = "'highlighted'" + "-" + number;
    does not require the inner quotes (apostrophes)
  • .box should be placed before the .highlighted styles to ensure proper overriding
  • I updated the class attribute of the div

Below is the revised code:

<script src="https://ajax.googleapis.com/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>

Alternatively, you could implement something like this.

<script src="https://ajax.googleapis.com/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!

Answer №4

Take a look at this demonstration in action:

function emphasize(event) {
  var position = (Math.floor((Math.random() * 5) +  1));
  var shade = "highlighted" + "-" + position;
  $("#eventTarget").attr('class', 'box'); 
  $("#eventTarget").addClass(shade);        
}

$("#eventTarget").on("mouseover mouseleave", emphasize);

You can view the interactive example on JSFiddle: https://jsfiddle.net/2gt9hmmd/3/

Now, let's address some issues.

  1. CSS is case sensitive, so Red !== red.
  2. The background-color of .box is declared after the highlight styles, and because they have the same priority, the .box style will always take precedence over the highlights.
  3. Avoid using unnecessary arrows within the highlight class string.
  4. You don't need to wrap that initial function within another function.
  5. The toggle class method only switches the color on and off, it does not cycle through different colors.
  6. It's best practice to declare functions before you use them for improved code readability.
  7. Avoid generic variable names like `number`, choose descriptive names that reflect the values they hold.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Strange alignment issues occurring solely on certain PCs

Currently, I am in the process of developing a website for a client who has requested that it be an exact replica of the mockup provided. However, I have encountered some issues with the headers and certain divs that contain background elements. Surprising ...

Implementing AJAX functionality in Codeigniter modulesTo integrate AJAX capabilities within Codeigniter modules

I am currently working on a webpage using the CodeIgniter framework. I am looking to integrate a 'show more' button that will utilize 'ajax.php' to retrieve data from the database and dynamically display it on the site. I prefer for thi ...

Having trouble modifying the fields in the formArray

https://i.sstatic.net/B4uTq.pngWorking with reactive forms, I have a UI feature that displays radioButton options which, when selected, reveals details about the chosen value within the form. Once a button is selected, the form fetches data from the backen ...

Is it possible for me to open an object URL in Internet Explorer?

Using Blob and URL.createObjectURL(), I have obtained an "object URL" (blob:) for some binary PDF data. In Chrome and FireFox, when I add an <A/> link HTML element with the programmatically set href attribute as the object URL, clicking on the link ...

Sometimes, in extremely rare instances, external stylesheets may fail to download or be properly applied

There have been very rare occurrences where major websites like Amazon and Facebook do not load a CSS file or apply the rules correctly, resulting in pages looking incomplete: I was recently asked to provide an internal explanation after receiving a compl ...

Utilizing AJAX Requests in jQuery Widget Elements for an Interactive Dashboard

I recently implemented the jQuery Dashboard plugin on my site to showcase information from a MySql table. Each widget contains buttons corresponding to the results, which when clicked trigger an ajax call to fetch and display a styled form in a jQuery dial ...

Update the state within a different function in Vue.js

Just starting out with Vue.js and I'm trying to figure out how to update the component's state from a function in another file. I have a basic form with only an input file element. Once the user selects a file, the onChange handler will be trigg ...

The EJS templating system

I am currently working on a node.js project and I have an ejs template file that utilizes templates for the header and footer. The structure of template.ejs is as follows: <%- include(header) %> main content <%- include(footer) %> <script ...

Navigating to a new page by clicking a button

I am trying to redirect to a different web page when a button is clicked. Below is the code snippet I am working with: JavaScript code snippet: app.controller('myCtrl', ['$scope', '$location', function($scope, $location) { ...

Error: Attempting to access index '0' of an undefined property in firebase and vuex

When using a vuex action to upload an image to Firebase and save the URL, everything seems fine until trying to retrieve the downloadUrl and adding it to the meetup database reference. The code I have looks like this: actions: { createMeetup ({commit ...

Steps to authorize an API request using a token

I have an API that requires authentication using a token. In Swagger UI, I am able to authenticate this API by providing the token in the authorize section. For example, if I input "Token 6ec8f4023d8148209749a1ed972xxxx" in the authorization box Here is ...

Solving Cross-Origin Resource Sharing problem in an Express JS application

I have encountered a CORS error while using this code, despite having applied the necessary cross-origin headers. I am seeking guidance on how to resolve this issue. var express = require('express'); var bodyParser = require('body-parser&ap ...

Passing variables from ExpressJS to JavaScript can be a seamless process

I am struggling with this issue; I am utilizing NodeJS to retrieve a JSON and I must transfer the variable to my page for use by JavaScript. app.get('/test', function(req, res) { res.render('testPage', { myVar: 'My Dat ...

Retrieve the row id from the table by clicking on a button in a modal box using jQuery

I am encountering a challenge with a small task due to my limited experience in jQuery. I have a table where each row has an icon. When the icon is clicked, a modal box appears with some content. After closing the modal box, I want to retrieve the table ro ...

Tips for creating responsive jQuery autocomplete list items

I've created a website using Bootstrap 4 and integrated JQuery autocomplete. However, the list items in the autocomplete feature are not responding well to different screen sizes. Take a look at my code below: jQuery(document).ready(function ($) { ...

Having trouble with installing a React app using npx create-react-app my-app?

description needed for image Having trouble creating a react application using npx create-react-app my-app... Encountering errors shown in the image. Attempted npm init but it was unsuccessful. Included node.js and vs code in the path. ...

Internal server error is causing issues with the AJAX call

Whenever I make an ajax call, it consistently fails with a 500 Internal server error. Strangely, there seems to be no error in the client side code. This is the JavaScript code being used: $.ajax({ url:"test.php", type:"POST", dataType:"html" ...

What could be causing my jQuery dialogs to lose their draggable functionality?

I've been struggling with making a dialog in jQuery draggable even though I've included 'draggable: true'. Can anyone help me figure out what's causing the issue? Here is the HTML code snippet: <div class="lessonDetails"> ...

Locate the closest text to an element within an HTML document

My HTML content contains specific tags with text and images. If I am able to select an image, is there a way to retrieve the text nearest to that image? <div class="topStory"> <div class="photo"> <a href="somelink"><img src="s ...

Can the CSS property "float: none;" interfere with the Javascript function "ng-click"?

This particular issue is quite strange. Setting "float: none;" appears to be preventing the execution of Javascript (ng-click). new.html.haml (where "float: none;" is located) .container{ng: {controller: 'sample_1_controller'}} %nav.bread.m ...