Is it possible to change CSS gradients randomly every time the page is refreshed?

Is there a way to randomly cycle CSS gradients each time the page is reloaded?

I have defined the following CSS gradients that I want to use:

/* Purple */
.fp-hero {
    background: linear-gradient(20deg, #6e48aa 0%, #9d50bb 73%, #b176cc 100%);
}

/* Light Blue */
.fp-hero {
    background: linear-gradient(20deg, #1fa2ff 0%, #12d8fa 73%, #a6ffcb 100%);
}

/* Green */
.fp-hero {
    background: linear-gradient(20deg, #56ab2f 0%, #a8e063 73%, #dce356 100%);
}

/* Tangerine */
.fp-hero {
    background: linear-gradient(20deg, #db5041 0%, #ff7566 73%, #fe8a5b 100%);
}

If anyone has any tips or suggestions, please let me know. Thank you.

Answer №1

It seems like you grasp the reason why your current setup is not functioning as expected, but let me elaborate. By consistently using the same selector and properties, each subsequent selection will overwrite the previous one, resulting in always ending up with the color "Tangerine".

To resolve this issue, I recommend modifying the classes to include a secondary class name and then randomly assigning that color class upon page load. This approach enables you to target multiple elements on the page and ensure they are coordinated.

For instance (click "Run Code Snippet" to observe it cycle):

$( document ).ready(function() {
    var colors = [
      "purple",
      "blue",
      "green",
      "orange"
    ];
    var randomIndex = Math.floor(Math.random() * colors.length);
    $(".fp-hero").addClass(colors[randomIndex]);
});
/* Purple */
.fp-hero.purple {
    background: linear-gradient(20deg, #6e48aa 0%, #9d50bb 73%, #b176cc 100%);
}

/* Light Blue */
.fp-hero.blue {
    background: linear-gradient(20deg, #1fa2ff 0%, #12d8fa 73%, #a6ffcb 100%);
}

/* Green */
.fp-hero.green {
    background: linear-gradient(20deg, #56ab2f 0%, #a8e063 73%, #dce356 100%);
}

/* Tangerine */
.fp-hero.orange {
    background: linear-gradient(20deg, #db5041 0%, #ff7566 73%, #fe8a5b 100%);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="fp-hero">
  This is my element
</div>

Answer №2

To begin, it seems that you have 4 CSS classes all named .fp-hero. The last one's background property (/* Tangerine */) takes precedence over the previous ones.

If I understand correctly, my suggestion would be to give them unique names like

.fp-hero-purple, .fp-hero-light-blue
, and so forth. This way, you can manipulate your target elements' CSS classes with JavaScript and switch between them as needed.

If you prefer not to use JavaScript, consider exploring keyframes: https://www.w3schools.com/cssref/css3_pr_animation-keyframes.asp

Update: Apologies for missing the "random" aspect earlier; in this case, keyframes may not work for achieving randomness. It seems you are looking to cycle through different gradients.

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

The concept of see-through backgrounds

I am trying to achieve a more transparent header-menu background, so that the YouTube video underneath it becomes more visible. You can check it out here Unfortunately, the trick mentioned above did not work as expected. .masthead:not(.mixed-header) { ...

Integrate jQuery into your Django project

Having trouble integrating jQuery into my Django app. Not sure what went wrong as the button click is not producing any results. Here's a snippet of my code: base.html {% load static %} <html> <head> <link rel ...

Infinite scrolling with Jquery: Loading dynamic content seamlessly from external websites

Hey there! I recently started using this cool jQuery plugin called jquery-endless-scroll. Here's a snippet of my code: $(function() { $('#list').endlessScroll({ pagesToKeep: 10, fireOnce: false, insertBefore: "#list div:first ...

A guide to using JavaScript to create a button that can dynamically change stylesheets

Just a heads up, I'm not using classes in this particular scenario. Can't seem to find the answer to this exact question. With javascript, how can I code a button to switch stylesheets every time it's clicked? I've experimented with d ...

Getting the ajax response by utilizing a custom attribute within a php loop is definitely a handy trick

Currently working on integrating ajax with php. I have a set of buttons within a loop, and I am trying to display or fetch data (number) in the correct place/div using the "attr" method in jQuery. However, it seems that it is not functioning as expected on ...

Using the data of multiple locations within a for loop to create Leaflet markers for use in a click event

I am currently working on a leaflet map that showcases markers for the top cities in a selected country. The locationList array consists of objects with city information such as latitude, longitude, and cityName. These values are utilized to place markers ...

A guide on retrieving all the table data and displaying it in the user interface using templates in Django

I am working on a Django project where I have created a model named "Files" with fields such as Id (auto-generated) and file_name. My goal is to retrieve all file names from the database and display them as a list on the user interface. To achieve this, I ...

It is impossible for Javascript to access an input element within a gridview

I have developed an asp.net page that allows a site administrator to select a user as the 'systems chair'. The page displays users in a gridview and includes a column of radio buttons to indicate who the current chair is or to change the assigned ...

Incorporating multiple colors into a div with jQuery: A guide

I am looking for a way to create a legend by merging a specified number of colors within a div. I came across this useful Sample code that I have referenced. $.each(Array(50), function() { $("<div>").appendTo(document.body); }); var divs = $(&a ...

Attempting to target modals in CSS using element IDs and class names is ineffective

Trying to implement dark mode in my app involves adding the following to the root element: <div id="dark"> Then, in CSS, styling it like this: #dark { background-color: #1A1A2E; } To customize each DOM element using classes, such as car ...

The presence of lightbox-plus-jquery.min.js leads to sliders experiencing crashes

After implementing a lightbox on the master page, I noticed that it was working fine but unfortunately causing the slider to crash. Removing the following line helped the slider work properly again: <script src="~/***/js/dist/js/lightbox-plus-jquery.mi ...

Using jQuery to serialize elements specifically contained within a div

Is there a way to achieve the effect similar to jQuery.serialize(), but only for the child elements of a specific div? An example result would be: single=Single2&multiple=Multiple&radio=radio1 ...

menu fails to expand when clicked in mobile view

Could someone please help me troubleshoot why the menu icon is not expanding in mobile view? I'm not sure what I did wrong. Here is the link for reference: Snippet of HTML: <nav class="navbar navbar-default navbar-fixed-top" role="navigation"> ...

I'm working in JavaFX and I have several line charts that I need to customize individually using CSS styling

Is there a way in JavaFX to style different charts individually with CSS without having the styles override all of them? I've noticed that when I change the CSS for one chart, it affects the others as well. How can I write CSS code that only applies t ...

Picture in a clear background without any alteration

Is there a way to create a background-color with opacity inside an image without affecting the image itself? The issue lies in the fact that the transparent background-color makes everything underneath it, including text and the image, transparent. Below ...

Modify the color of a table cell date using PHP

I need to change the color of my td's client_birth_date based on the current date. For instance, if today is the client's birthday, I want the font color of this td to turn red. Here is a snippet of my HTML code: <?php foreach ($rows as $row) ...

Troubleshooting: Issues with Mod_rewrite affecting CSS, JS, and Image functionality

Today marks my first time posting a query in this forum. I'm currently facing an issue with mod_rewrite. Below is the structure of my filesystem: site_new/stylesheets/layout.css site_new/javascript/somescript.js site_new/hallendetails.php ...

Words next to picture

Can someone help me with aligning different images of varying widths but the same height inline with text next to each image? I tried to do it, but it doesn't look good on responsive screens. Any suggestions on how to fix this? And if there's a b ...

Load Jquery hover images before the users' interactions

Currently, I am in the process of creating a map of the United States. When hovering over any specific state, my goal is to replace the image with one of a different color. The issue I am encountering lies in the fact that the image gets replaced and a ne ...

Fluctuating CSS appearance during content loading and asynchronous CSS loading

As I work on loading a new page and a CSS file for it using AJAX, I encounter an issue. Once all the CSS files are added to the page, I set the opacity to 1, expecting the page to display with the CSS applied immediately. However, it initially appears wit ...