How can I update the gradient color upon refreshing the page while ensuring the cursor remains on the same

I have managed to get the cursor position and gradient working, but I'm struggling to make the gradient color change dynamically while still maintaining the functionality of the cursor position element.

My goal is to have the gradient color change every time the page refreshes, selecting from an array of colors. You can see what I have implemented so far here:

http://jsfiddle.net/trktqqh6/3/

$(".gradient").mousemove(function( event ) {
  var w = $(this).width(),
      pct = 360*(+event.pageX)/w,
      bg = "linear-gradient(" + pct + "deg,#4ac1ff,#795bb0)";
      $(".gradient").css("background-image", bg);
});
html {
  height: 100%;
}
body {
  background-color: #292c2f;
  font-family: monospace;
  overflow: hidden;
}
.gradient {
  height: calc(100% - 70px);
  background-image: -webkit-linear-gradient(270deg, #4ac1ff, #795bb0);
  background-image: -moz-linear-gradient(270deg, #4ac1ff, #795bb0);
  background-image: -o-linear-gradient(270deg, #4ac1ff, #795bb0);
  background-image: -ms-linear-gradient(270deg, #4ac1ff, #795bb0);
  background-image: linear-gradient(180deg, #4ac1ff, #795bb0);
  position: absolute;
  width: 100%;
}
header {
  background: #252525;
  height: 70px;
  line-height: 70px;
}
#currentVal {
  color: #424242;
  font-size: 14px;
  font-weight: 800;
  padding-left: 240px;
}
#currentVal span {
  color: #ccc;
}
#range {
  width: 180px;
  border: 0;
  height: 4px;
  background: #424242;
  outline: none;
  position: absolute;
  left: 30px;
  top: 32px;
}
#range .ui-slider-handle {
  position: absolute;
  margin: 0px 0 0 -7px;
  -webkit-border-radius: 100%;
  border-radius: 100%;
  background: #fff;
  border: 0;
  height: 14px;
  width: 14px;
  outline: none;
  cursor: pointer;
}
#range .ui-slider-handle:hover,
#range .ui-slider-handle:focus {
  -webkit-transform: scale(1.1);
  -moz-transform: scale(1.1);
  -o-transform: scale(1.1);
  -ms-transform: scale(1.1);
  transform: scale(1.1);
}
#range .ui-slider-range {
  background: #4ac1ff;
}
<div class="gradient"></div>

Answer №1

Creating this effect is quite straightforward. All you need to do is have an array of colors, utilize a random number generator, select the colors based on the generated number from the array, apply it to the gradient, and then assign it to the specified element.

$(document).ready(function() {
  var colors = [
    ["green", "purple"],
    ["orange", "pink"],
    ["teal", "gray"],
    ["magenta", "lime"]
  ];
  var num = Math.round(Math.random() * 3);
  bg = "linear-gradient(180deg," + colors[num][0] + "," + colors[num][1] + ")";
  $(".gradient").css("background-image", bg);

  $(".gradient").mousemove(function(event) {
    var w = $(this).width(),
      pct = 360 * (+event.pageX) / w,
      bg = "linear-gradient(" + pct + "deg," + colors[num][0] + "," + colors[num][1] + ")";
    $(".gradient").css("background-image", bg);
  });
});
html {
  height: 100%;
}
body {
  background-color: #292c2f;
  font-family: monospace;
  overflow: hidden;
}
.gradient {
  height: calc(100% - 70px);
  background-image: -webkit-linear-gradient(270deg, #4ac1ff, #795bb0);
  background-image: -moz-linear-gradient(270deg, #4ac1ff, #795bb0);
  background-image: -o-linear-gradient(270deg, #4ac1ff, #795bb0);
  background-image: -ms-linear-gradient(270deg, #4ac1ff, #795bb0);
  background-image: linear-gradient(180deg, #4ac1ff, #795bb0);
  position: absolute;
  width: 100%;
}
header {
  background: #252525;
  height: 70px;
  line-height: 70px;
}
#currentVal {
  color: #424242;
  font-size: 14px;
  font-weight: 800;
  padding-left: 240px;
}
#currentVal span {
  color: #ccc;
}
#range {
  width: 180px;
  border: 0;
  height: 4px;
  background: #424242;
  outline: none;
  position: absolute;
  left: 30px;
  top: 32px;
}
#range .ui-slider-handle {
  position: absolute;
  margin: 0px 0 0 -7px;
  -webkit-border-radius: 100%;
  border-radius: 100%;
  background: #fff;
  border: 0;
  height: 14px;
  width: 14px;
  outline: none;
  cursor: pointer;
}
#range .ui-slider-handle:hover,
#range .ui-slider-handle:focus {
  -webkit-transform: scale(1.1);
  -moz-transform: scale(1.1);
  -o-transform: scale(1.1);
  -ms-transform: scale(1.1);
  transform: scale(1.1);
}
#range .ui-slider-range {
  background: #4ac1ff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="gradient"></div>

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

Leading astray — using htmlentities will not function

UPDATE (Instead of deleting this question, I'll keep it as a reminder that errors are sometimes found in unexpected places...) I apologize for leading you down the wrong path with this question. The issue causing the "Actual result" was actually loc ...

Using javascript and d3.js to display a set number of items on each line through printing

I'm currently working on a project that involves printing a specific number of rectangles per line using d3.js var rectangle = svgContainer.selectAll("rect").data(data).enter().append("rect") .attr("x", function(d,i){ return i*5}) ...

Tips for enclosing the "body" element using a background image

Hey there! I'm a newbie web developer with a casual approach to coding. I'm trying to jazz up my menu by adding a background image, but no matter what I do, it keeps showing the default white background. Can anyone lend me a hand? If you're ...

Oops! Issue: The mat-form-field is missing a MatFormFieldControl when referencing the API guide

I included the MatFormFieldModule in my code like so: import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppRoutingModule } from './app-routing.module'; ...

Optimal methods for organizing various perspectives on a one-page website

I am developing an application that incorporates AngularJS and Bootstrap. The current setup involves organizing various views using ng-show, allowing for view changes based on button interactions and the enablement/disabling of ng-show values. Within a si ...

Is There a Quicker Alternative to Eval for Generating Deep Clones?

I am looking to create deep clones of a very large object called veryBigObject. To initialize veryBigObject, it first needs to be initialized using the initVeryBigObject function. Here is how this process looks: initVeryBigObject = function(){ veryBig ...

MongoDB date query with $gte and $le operators mm/dd/yy

Apologies in advance for any language errors. The problem I am dealing with involves a column in the database called "Date" inside the "startOn" Object. This setup creates a structure like "startOn.Date" with data format as yyyy/dd/mm. For example, if we ...

Beginner coding exercises to master JavaScript

With a proficiency in CSS, HTML, and some knowledge of Jquery and PHP, I aspire to become a Front End Web Developer. However, my lack of understanding in Javascript is holding me back. I acquired my current skillset by rapidly learning over 9 months while ...

Error in jQuery submenu positioning issue

I am attempting to design a menu that opens when the parent element is clicked and closes when the mouse leaves the previously opened one. It should operate from left to right. Here is an example: <ul class="menuFirst"> <li><im ...

Swapping out a style sheet within a intricate header

I'm in search of help with creating a stylesheet switcher for my website. My knowledge of html/css/js is self-taught, so I ask for forgiveness for any beginner mistakes. I have customized some code to fit my requirements, but I am unsure how to target ...

Navigating to the bottom of a page once an element is displayed (with react-slidedown)

I'm facing a bit of a challenge here that I haven't been able to resolve yet. So, I have this optin form that is revealed upon clicking on a link. The reveal effect is achieved using react-slidedown. The issue I'm encountering is that when ...

What is the method for obtaining the total row of an ngFor loop within an HTML file?

I am trying to figure out how to retrieve the total number of rows in an ngFor loop and display it above. Any suggestions? <p>Total row: "I need to display the number of rows here"</p> <table class="table" > &l ...

expanding the expressjs res feature

I am currently working on implementing an error and notification feature for my expressjs app. My approach was to add a function by calling: app.use(function (req, res, next) { res.notice = function (msg) { res.send([Notice] ' + msg); } }); ...

Exploring the power of Angular JS promises through ng-repeat

My current project involves fetching latitude and longitude coordinates from a postcode using an API, then utilizing those coordinates to retrieve data on street level crimes near that location on a specific date through the UK police API. However, I have ...

Alignment issue with text in Vuetify Datatables cells

I'm experimenting with Vuetify on my Laravel Vue application, and everything seems to be working fine except for the DataTables styles. The padding of the cells is not vertically center aligned as expected. Here's a screenshot https://i.sstatic.n ...

The received data object appears to be currently undefined

I am currently using MapBox to display multiple coordinates on a map, but I am encountering an issue where the longitude and latitude values in my return object are showing up as undefined. Could there be a missing configuration that is preventing the data ...

What is the best way to incorporate setTimeout in a loop using Coffeescript?

window.onload = -> boxOrig1 = 10 boxOrig2 = 30 canvasW = 400 canvasH = 300 ctx = $("#canvas")[0].getContext('2d'); draw = (origin,dimension) -> ctx.clearRect(0, 0, canvasW, canvasH) ctx.fillStyle = 'rgb(200,0 ...

Integrating a conditional statement into the existing for loop code to conceal the covers

My goal is to hide the covers after they are clicked using an if statement within the for loop code. I believe this is where it should be placed. Trying to prevent this action from happening. https://i.sstatic.net/eLSto.png I made an attempt at achievin ...

I am unable to incorporate the RobotJS module into my ElectronJS project

Currently, I am working on a Windows desktop application using ElectronJS. My main challenge is integrating the RobotJS module into my project. Despite successfully downloading the module with 'npm install robotjs' and incorporating it into my ma ...

Received undefined response from Axios.get() request

While working with the code below, I encountered an issue. The axios get request from await axios.get('/products/api') is functioning properly and I can see the data in the console. However, for await axios.get('/users/api'), 'Unde ...