Combining onmousedown and onchange for optimal event handling

There is a div with three slide-bars, each representing an 'rgb' value with a range of 0-255. When the slide-bars are dragged, the background-color of the div should change accordingly. Currently, an 'onchange' event is called to a function with two parameters (this.value and a number) to set the background-color of the div. However, the color is only changing when the 'onmouseup' action occurs, instead of dynamically as the slide-bar is being dragged.

Here is the code:

<html>
            <head>
                <script>
                var r=0;
                var g=0;
                var b=0;
                    function set(){
                        r=g=b=128;
                        document.getElementById('div').style.backgroundColor="rgb("+r+","+g+","+b+")";
                    }
                    function change(val,bar){

                        if (bar==1){
                             r=val;
                        }
                        if (bar==2){
                             g=val;
                        }
                        if (bar==3){
                             b=val;
                        }

                        document.getElementById('div').style.backgroundColor="rgb("+r+","+g+","+b+")";
                    }
                </script>
            </head>

            <body onload="set()">

                <div id="div" style="width:400px;height:100px;">

                </div>
                <table border="">
                <tr><td>red</td><td><input id="r_slide" type="range" style="width:200px" min="0" max="255"  onchange="change(this.value,1)"></td></tr>
                <tr><td>blue</td><td><input id="g_slide" type="range" style="width:200px" min="0" max="255" onchange="change(this.value,2)"></td></tr>
                <tr><td>green</td><td><input id="b_slide" type="range" style="width:200px" min="0" max="255" onchange="change(this.value,3)"></td></tr>
                </table>
            </body>
        </html>

Answer №1

To receive real-time updates, you can utilize the onInput event. It is important to note that onInput may not be compatible with certain versions of IE, so I have included onChange as an alternative to ensure full coverage.

var r=0;
var g=0;
var b=0;

function set() {
    r=g=b=128;
    var div = document.getElementById('div');
    div.style.backgroundColor="rgb("+r+","+g+","+b+")";
}

function change(val, bar){
    if (bar==1){
        r=val;
    }
    if (bar==2){
        g=val;
    }
    if (bar==3){
        b=val;
    }

    var div = document.getElementById('div');
    div.style.backgroundColor="rgb("+r+","+g+","+b+")";
}
<html>
<head>
</head>
<body onload="set()">
    <div id="div" style="width:400px;height:100px;"></div>
    <table border="">
        <tr>
            <td>red</td>
            <td>
                <input id="r_slide" type="range" style="width:200px" min="0" max="255" oninput="change(this.value,1)" onchange="change(this.value,1)">
            </td>
        </tr>
        <tr>
            <td>blue</td>
            <td>
                <input id="g_slide" type="range" style="width:200px" min="0" max="255" oninput="change(this.value,2)" onchange="change(this.value,2)">
            </td>
        </tr>
        <tr>
            <td>green</td>
            <td>
                <input id="b_slide" type="range" style="width:200px" min="0" max="255" oninput="change(this.value,3)" onchange="change(this.value,3)">
            </td>
        </tr>
    </table>
</body>
</html>

Answer №2

To achieve this, one solution would be to utilize the input event handler. Here is a simple way to do it:

<input type="range" oninput="adjustValue(this.value, x)">

Answer №3

Instead of waiting for the change to happen with the onChange event, you can opt for the onInput event. (learn more).

Keep in mind that onInput (along with input:type=range) won't work on IE8 and earlier versions, as well as Opera 9 and below.

<table border="">
     <tr><td>red</td><td><input id="r_slide" type="range" style="width:200px" min="0" max="255"  oninput="change(this.value,1)"></td></tr>
     <tr><td>blue</td><td><input id="g_slide" type="range" style="width:200px" min="0" max="255" oninput="change(this.value,2)"></td></tr>
     <tr><td>green</td><td><input id="b_slide" type="range" style="width:200px" min="0" max="255" oninput="change(this.value,3)"></td></tr>
 </table>

jsFiddle

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

Cutting an image in ReactJS using the HTML5 canvas feature

Seeking a way to crop images in reactjs without relying on any external library. The goal is for users to upload an image and perform cropping using raw JavaScript, then replace the uploaded image. How can this be achieved without the use of libraries? Loo ...

Please provide instructions on how to update a webpage section using ajax/json

Currently, I am in the process of developing a chat website and focusing on managing ONLINE USERS. I have implemented AJAX to handle refreshing data, however, I am facing issues with using Append(); method. Whenever I refresh the section, the same data k ...

The callback function in AngularJS filters

I'm currently using an AngularJS filter to sort through a list of items. Here is the Jade markup I am using: li(ng-repeat="parcel in parcels | filter : filterActiveAreaParcels") After the filter function runs and the elements are displayed in the DO ...

Is there a way to prevent Prettier on VS Code from automatically unfolding my code blocks when saving?

I have Prettier set up in my VS Code editor with the formatOnSave feature enabled. However, I am facing an issue where every time I save my (js) or (jsx) file, Prettier automatically expands all my functions. Is there a way to stop this from happening? I ...

Center an image of varying height within a container of fixed height

I have this HTML structure, and while I am open to making changes, I would prefer to keep it simple: <div class="c"> <img ...> </div> The image within the div will vary in size and I want it to be vertically centered. Currently, I ...

Is there a way to establish a connection with a secondary Firestore database in Node.js, allowing for the use of multiple Firestore databases

I have set up multiple firestore databases within my project. Using the command line, I created these databases and can view them in the Firestore Databases preview by following the instructions outlined here: https://cloud.google.com/blog/products/databas ...

Concealing the submit button until a file has been selected

How can I make the submit button invisible until a file is selected? <form action="upload.php" method="POST" enctype="multipart/form-data"> <input type="file" name="imageURL[]" id="imageURL" /> <input type="submit" value="submi ...

Modify the CSS class of a customized component using a different component

Here is a small example illustrating my issue: https://github.com/lovefamilychildrenhappiness/AngularCustomComponentValidation The problem arises with a custom component that contains an input field. The formControl linked to this input field utilizes Val ...

``Maybe there is a way to fix the issue of jQuery not functioning properly

I am currently working on integrating jquery with Reactjs to add a class on click event. The functionality works fine when the page is refreshed, but it stops working if I navigate to the page after clicking on any menu item without refreshing. How can I ...

Unable to find the specified element within Gmail

Recently, I've been working on a project with Nightwatch.js where it checks the dev environment and sends a test email to a Gmail account. Following that, it logs into Gmail, locates and clicks on the correct email. My main challenge now is trying to ...

Local email.js functionality successful, but fails upon deployment alongside React

I have implemented Email.js to create a contact form for a Next.js website. It functions perfectly when tested locally, but encounters issues once deployed. Upon clicking the submit button, the form fails to reset as intended within the sendEmail function. ...

Making a div equal in height to an image

What I currently have is like this... https://i.stack.imgur.com/7FeSi.png However, this is what I am aiming for. https://i.stack.imgur.com/fn9m0.png The image dimensions are set up as follows... #content img{ padding: 3%; width: 60%; height: 50%; floa ...

AJAX - Implementing a delay in displaying AJAX results

My search function uses AJAX to retrieve data from the web-server, and I am trying to implement a fade-in animation for each search result. I want the results to load and fade in one by one with a slight delay between them. Currently, it seems like all th ...

Issue with iframe's size not displaying correctly

<body> <script> document.write("<iframe id='theframe' src='http://www.website.com?testvr=" + testvr + " height='900' width='500'></iframe>"); </script> </body> The iframe is added, but ...

Attempting to delete a request using FormData resulted in a 500 error response

Currently, I am working on deleting an attachment by sending a request with form data containing a URL through an API path along with an ID. deleteAttachment(id, url) { const formData = new FormData(); formData.append('url', url); ...

Modifying properties of an array of objects in React Native using JavaScript

I have a scenario where I am using Flatlist to render a couple of boxes. If the "shapes" element's "visible" key is false, the box will be blank. This visibility property is defined in state and I'm not sure if this is the correct approach. Now, ...

Find keys in an array based on a specified value

I need to retrieve an array of keys from an object that match a specified value ...

Limiting the number of characters in PHP/MySQL

Here is a glimpse into the scenario I am currently facing: The content, including the heading, text, and image, is all dynamically generated based on user input. Users have the option to include an image and choose the text for both the heading and main c ...

Align child elements in the middle horizontally within a col-lg-4 class using Bootstrap

I am currently working with Bootstrap 4.3.1 and utilizing flex for my page layout. <div class='row d-flex align-items-center'> <div class='col-lg-12'> <div class="form-group row"> ...

Distinguish between a function and a constructor during execution

As I work with TypeScript, I am creating a function that accepts an error factory as an argument. This factory can be either a class name or a function. The function looks something like this: // Alias from class-transformer package type ClassConstructor& ...