Slider Volume with jQuery

Struggling to find a solution for this issue. Seeking some assistance.

My goal is to create a basic volume slider.

So, the orange section represents my volume slider.

This is the jQuery code I am using:

var mouseIsDown = false;

$("#volSlider").on("mousedown", function() { mouseIsDown = true; });
$("#volSlider").on("mouseup", function() { mouseIsDown = false; });
$("#volSlider").on("mouseleave", function() { mouseIsDown = false; });

$("#controlVolume").on("mousemove", function(event) 
{
    if (mouseIsDown == true) 
    {
        var caretPositionFromTop = $("#volCaret").position().top;
        var areaHeight = $("#volSlider").height();
        var volume = (caretPositionFromTop / areaHeight) * 100;
        volume = Math.round(volume);

        $("#volCaret").css("bottom", volume);
        $("#volText").text(volume);

        if (volume <= 100 && volume >= 0)
        {
            // To be continued.
        }
    }
});

Edit: Here is the HTML structure for reference:

<div id="controlVolume">
    <div id="volSlider">
        <div id="volCaret"></div>
    </div>
    <div id="volText"></div>
</div>

When trying to drag the caret upwards, it only goes up to "1" and stops. Is there something I'm overlooking? Any help is appreciated. Thank you.

Answer №1

To accurately track the movement of the mouse, focus on monitoring the Y vertex instead of solely the caret's height (though technically it does change with each mouse movement). Currently, you are observing the volume bar's position which remains constant.

Your code should resemble something like this:

var mousePos = 0;
var mouseDown = false;
var height = 0;

$("#volSlider").mousedown(function(e) { mouseDown = true; mousePos = e.pageY; height = $("#volCaret").height(); });
$("#volSlider").mouseup(function() { mouseDown = false; mousePos = 0 });
$("#volSlider").mouseleave(function() { mouseDown = false; mousePos = 0 });

$("#controlVolume").mousemove(function(e) 
{
    if (mouseDown == true) 
    {
        var areaHeight = $("#volSlider").height();
        var caretHeight = height + (e.pageY - mousePos);
        $("#volCaret").height(caretHeight ); 

        var volume = caretHeight / areaHeight * 100;
        console.log(volume);

    }
});

Consider sharing your code on jsfiddle in case I have overlooked any potential issues causing this script to malfunction.

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

I'm currently utilizing lint in my Angular 2+ project. Is there a way to arrange the constructor parameters in alphabetical order

I am struggling to organize the constructor parameters in TypeScript while using TSLINT with Angular9. I am looking for a rule similar to member-ordering that can help me sort them effectively. constructor( // Sort these private readonly router: R ...

Replace the value of a variable when another variable becomes false in Angular.js

Currently, I am working on a project using Angular and have run into an issue that I need help with: In my project, I have two variables - signed which is a boolean bound to a checkbox, and grade which is an integer bound to a number input field. I am lo ...

Problem with JavaScript and Basic HTML5 Canvas

I'm trying to dive into learning about using a canvas, but I just can't seem to get this basic code to work. Does anyone know what I might be doing wrong? Link to jsfiddle <canvas id="ctx" width="500" height="500" style="border:1px solid #00 ...

Bizarre symbols observed while extracting data from HTML tables produced by Javascript

I am in the process of extracting data from Specifically, my focus is on the "tournament-page-data-results" div within the source code. Upon inspecting the HTML source code, the data does show up, but it appears with a mix of real information and random c ...

Is it possible to retrieve the parent object?

My code snippet is as follows, and I'm struggling to access the data object from within the innerFn function. Is there a way to accomplish this? export default { data: { a: "a", b: "b" }, fn: { innerFn: () => co ...

Creating a horizontal scroll effect using jQuery when the widths of the items are not

I am working on a jQuery gallery that showcases images in a horizontal layout. Below the images, there are "left" and "right" buttons which allow users to scroll through the pictures. There are many tutorials and plugins available for this type of function ...

Incorporating header and footer elements into the design

I am facing an issue while editing a layout. Currently, when clicking on some side of the layout, a header and footer appear in a certain way. However, I would like to change this so that the header and footer appear differently, similar to the example s ...

What is the method to create a resizable table column border rather than resizing the bottom corner border?

At the moment, we are able to resize the table border when we drag the corner. However, my goal is to enable resizing on the right side of the full border. https://i.sstatic.net/yFI24.png Below is the CSS code for resizing: th{ resize: horizontal; ove ...

Issue with Node.js MongoDB collection.find().toArray not returning results

Despite coming across questions similar to mine, I struggled to resolve the issue independently. Within my '../models/user' model, my goal is to retrieve all users and store them in an array, which will then be returned to the controller for fur ...

When using ViewBag in JavaScript, an error may occur with the message "Uncaught SyntaxError: Unexpected token '<'"

When I try to fetch data from an API and assign it to the VIEW BAG, I encounter an error during runtime. List<DevInfo> DevList = await RestApi.Instance.GetAllDevAsync(); var nameT = DevList.Select(a=>a.Name).ToList(); ViewBag.datasourceDevList = n ...

The static files are being received by Django but are not functioning properly

I've been working on a project using django 1.7, and below is my settings.py configuration: STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, "assets"), ) STATIC_ROOT = "absolute/path/to/static" In the 'assets&apo ...

Is the media-heading situated at the base of the picture?

Wondering if it's possible to create a horizontal list of images with the image-heading under each image using Bootstrap 3. I couldn't find any information on this in the documentation. <h5 class="media-heading pull-left">One</h5> &l ...

How can I send identical posts to multiple servers and link specific data to each post?

I am attempting to send a post request to multiple servers using jQuery, potentially facing issues with CORS. I have an array containing the jQuery posts and I register the same callback function for each individual one like this: var requestUrls = getReq ...

Troubleshooting: jQuery $.post not functioning as expected in certain circumstances

I'm currently experimenting with inserting data into a MySQL database using AJAX and jQuery's $.post method. To test this functionality, I have created the following setup: In my index.html file (which already includes jQuery for various other f ...

retrieving an element from a collection of objects

For a project utilizing the openweather api, I encountered fluctuating data based on the time of day it is viewed. My goal is to loop through the first 8 objects to identify a dt_txt value of 12:00:00. Once found, I intend to store this result in a variabl ...

Is there a way to display multiple Bootstrap 5 modals simultaneously without automatically closing the previous ones?

My current project utilizes bootstrap 5.2, which is a departure from the previous version, bootstrap 3. In bootstrap 3, it was possible to open multiple modals on top of each other, creating an overlapping effect. However, in bootstrap 5 and 5.2, the behav ...

Creating custom events in a JavaScript constructor function

Just beginning to learn JavaScript. I have a custom function that I want to assign events to in the constructor. var myFunction = function(){ /* some code */ } myFunction.prototype.add=function(){ /* adding item*/ } Now I am looking to add an event to ...

Problem with maintaining the alternating background color of table rows while using jQuery's animate() function

I have an HTML table that I styled with alternating row background colors. <table class="tb_record"> <tr> <th>Firstname</th> <th>Lastname</th> <th>Age</th> </tr> < ...

Tips for utilizing a printer to print HTML content in PHP

I've stored HTML content in a variable as shown below: $message ="<div> <table align='center'> <tr><td><h1>Tipo de Documentos Report</h1></td></tr> <tr><td>< ...

When clicked, the menu smoothly fades in, but unfortunately, the fade-out effect is not functioning as intended

My website has a "hamburger" icon button that, when clicked, reveals the menu with a fading effect. However, I encountered an issue where trying to apply the fadeOut effect to another icon/button within the menu did not work as intended. The menu remained ...