Transformation in input value does not manifest in other components

When adjusting the sliders, the input fields are supposed to update accordingly. However, I've noticed that the changes in the input fields only take effect if I manually change their values. The automatic reflection doesn't seem to occur when using the sliders.

So, when I change the input value directly, the changes reflect properly. But when I adjust the slider value, which should then update the input field value, this reflection does not happen as expected.

var rSlider = document.querySelector("#r");
var gSlider = document.querySelector("#g");
var bSlider = document.querySelector("#b");

var rInput = document.querySelector('#rInput');
var gInput = document.querySelector('#gInput');
var bInput = document.querySelector('#bInput');

$(document).ready(function() {
  $(rInput).val(0);
  $(gInput).val(0);
  $(bInput).val(0);
})

$(rSlider).on('input', function() {
  $(rInput).val($(this).val());
})

$(gSlider).on('input', function() {
  $(gInput).val($(this).val());
})

$(bSlider).on('input', function() {
  $(bInput).val($(this).val());
})

$(rInput, gInput, bInput).change(function() {
  rValue = String($(rInput).val());
  gValue = String($(gInput).val());
  bValue = String($(bInput).val());
  var tempString = `rgb(${rValue},${gValue},${bValue})`
  console.log(tempString)
})

Interestingly, the console.log statement is only triggered in the first scenario and not in the second case. Any assistance with this issue would be greatly appreciated. Thank you in advance.

Answer №1

Take a look at the code snippet below.

$(function() {
  function changeColor(arr) {
    $("#resultColor").css("background-color", "rgb(" + arr.join(",") + ")");
  }

  function getValues() {
    return [
      $("#r").val(),
      $("#g").val(),
      $("#b").val()
    ];
  }

  $("input[type='range']").on('input change', function() {
    var i = $(this).attr("id");
    $("#" + i + "Input").val($(this).val());
    changeColor(getValues());
  });

  $("input[type='text']").change(function() {
    var i = $(this).attr("id").substring(0, 1);
    $("#" + i).val($(this).val());
    changeColor(getValues());
  });

  changeColor(getValues());
});
input[type='text'] {
  width: 2em;
}

label {
width: 60px;
display: inline-block;
}

#resultColor {
  width: 100px;
  height: 100px;
  border: 1px solid #000;
  top: 10px;
  left: 300px;
  position: absolute;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="content">
  <div>
    <label>Red</label> <input type="range" min="0" max="255" value="0" id="r" /> <input type="text" id="rInput" value="0" />
  </div>
  <div>
    <label>Green</label> <input type="range" min="0" max="255" value="0" id="g" /> <input type="text" id="gInput" value="0" />
  </div>
  <div>
    <label>Blue</label> <input type="range" min="0" max="255" value="0" id="b" /> <input type="text" id="bInput" value="0" />
  </div>
  <div id="resultColor"></div>
</div>

For future reference, it is recommended to provide a Minimal, Reproducible Example.

To improve the code, consider creating helper functions for getting and setting values. Additionally, try consolidating repetitive code into a single function.

You may find inspiration from jQuery UI's colorpicker example here: https://jqueryui.com/slider/#colorpicker

Working with HTML Range Input can be challenging, but the jQuery UI version offers better styling options.

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

Refine results by searching through the text contained in the elements of every div

I recently came across a helpful fiddle that allows text to be hidden based on what is entered into a search box. However, I am struggling to apply this method to a div that contains multiple elements. Is there a way to modify the jQuery in the provided fi ...

Disable reloading when submitting and reset input fields after submission

I am working on developing a website where users can post things and comments without the need to refresh the page. I have encountered some issues while implementing this feature and need some assistance with it. My goal is to allow users to submit comment ...

Verifying that the class name prefix aligns with the folder name using Stylelint

Currently, I am utilizing the "selector-class-pattern" rule from stylelint. My chosen pattern enforces the ECSS naming convention. The specific rule configuration is outlined below: "selector-class-pattern": ["^[a-z]([a-z0-9]){1,3}-[A-Z][a-zA-Z0-9]+(_[A-Z ...

methods for transferring javascript variables to modal

<div> <h5> <a href="<?php echo base_url(); ?>/vendor/home/projects" >Return to Projects</a> </h5> <div> <div class="container"> <div class="row"> ...

What is the frequency of page rendering in Angular 2 before displaying it?

I've been working with Angular 2 on a project lately. In my template, I have a simple div that triggers a function in my .ts file to display basic text like so: <div>{{ test() }}</div> test(): void { console.log("Test text") ...

Using cfajaxproxy in conjunction with URL rewriting capabilities

I have successfully integrated the cfajaxproxy tag, but encountered an issue with the cfc's location in the root directory of my site. When accessing a page within the root directory through a rewritten URL (e.g. mysite.com/one/two/ -> mysite.com/ ...

"Initially, the input state does not establish a binding for onChange event upon

A state named account_type has been declared, and an onChange event has been created to change the state's value when the div is clicked. <div className="price-plan" value="star" onClick={() => this.setPlan("star") ...

Maximize Efficiency with Bootstrap 4: Aligning Content in Flexbox Elements

I'm currently working with Bootstrap 4 and Flexbox to ensure that the columns inside a row are properly aligned. One of my requirements is to have all columns be of the same height, so I utilize the "align-items-stretch" class () to achieve this unifo ...

How can I align inner boxes to the same level?

I would like the inner two divs to be positioned as: _________ _________ | | | | | | | | | | | | |_________| | | | | |_________| Usually, when they are both empty o ...

Performing a PHP loop to concatenate the latest database entries

Imagine having a MySQL structure structured like this... +--------------+--------------------+-------------------+ | tdate | tuser | tvalue | +--------------+--------------------+-------------------+ | 11:16:48 | John ...

What is the best way to display additional content in a Django application?

My Django application has a template for viewing group lists. However, I have noticed that as the number of groups increases, the page scrolls down and I am unable to see all the names of the groups. What I want is to display only 4 group names initially ...

Add Content to Textbox by Clicking

In my current setup, I have a variety of buttons that, when clicked, should add the text from the button to a text box. Each time a button is clicked, I want the text to be appended to whatever is already in the input field. Current Approach $('#js- ...

Filtering data in Asp.net MVC 3 and converting it to JSON format

For my asp.net mvc 3 project, I'm considering the best approach for handling data: should I pass all the data via JSON and filter it with JavaScript, or should I filter the data first and then convert it to JSON? If filtering the data before passing ...

What is the best way to transform the request query id = ' [12eetftt76237,jhgasduyas7657] ' into an array of elements or strings like [12eetftt76237,jhgasduyas7657]?

Hey there, I am working on a project using hapijs and typescript. I have a requirement to send an array of IDs as parameters through the request URL. Here is an example of the URL: localhost:3444/?id='[askjajk78686,ajshd67868]' I attempted to u ...

Using regular expressions to extract data from a Solr query parameter FQ specifying a local tag

Currently, I am utilizing Ajax Solr for a development project. I am experimenting with the additive method in facet selection and successfully appending FQ values to breadcrumbs. The issue at hand is that I only want the value to be displayed in the bread ...

Masking elements using CSS3 filters

Is it feasible to apply CSS3 filters as a mask? For example, I would like to blur only 30% of a div from the top. How can this be accomplished? I have created a small jsfiddle to demonstrate what I am attempting to achieve: http://jsfiddle.net/uxCXa/2/ ...

Tips for ensuring that the footer remains at the bottom of the content and stays fixed at the bottom of the viewport

In my Django project, I am using Bootstrap 4.5 and I need the footer to be in one of two positions: 1- At the bottom of the content if the content is larger than the view height 2- At the bottom of the viewport if the content is smaller than the view hei ...

Implementing Jquery Ajax Autocomplete Feature in JSP

I am currently exploring a tutorial on jQuery autocomplete using remote data. In my JSP page, I have the following code snippet: (getData.jsp) Department t = new Department (); String query = request.getParameter("q"); List<String> ...

Changing Text to Number in JavaScript

Looking to convert the string value of 41,123 into an integer using JavaScript. I attempted parseInt(41,123, 10) and parseFloat methods but haven't received the desired result. The issue seems to be with ParseInt and parseFloat when encountering com ...

Error: pos variable is not defined

I encountered a TypeError: pos is undefined while running the code below. $(document).ready(function() { var s = $("#col-scroll"); var pos = s.position(); $(window).scroll(function() { var windowpos = $(window).scrol ...