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

Upload file via AJAX immediately after downloading it (no need for storage)

Currently, I am in the process of developing a JavaScript script to safeguard an old game development sandbox website from being discarded by its owners. In order to prevent the loss of all the games on the site, I have managed to create a script that allo ...

Can you tell me what is creating the space between the elements in this form?

For an example, take a look at this link: I am puzzled by the gap between the form-group and the button, as well as between the different form-groups. When using Bootstrap 4 with flexbox activated, all my elements (inputs and buttons) collapse without any ...

What could be causing my jQuery code to not function properly?

I wrote a small piece of code in jQuery, but I am having trouble executing it. Can someone help me figure out what I'm doing wrong? <html> <head> <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.min.js"> & ...

Unleash the potential of a never-ending expansion for grid cells on Canvas

ts: templateStyle = { display: 'grid', 'grid-template-columns': 'calc(25%-10px) calc(25%-10px) calc(25%-10px) calc(25%-10px)', 'grid-template-rows': '150px auto auto', 'grid-gap ...

Avoid clicking on links while the webpage is still loading

I am facing an issue with my website where I need to intercept link-clicking events using jQuery. Everything works fine, but there is a problem if a user clicks on a link before JavaScript finishes loading, causing it to redirect to another page in error. ...

Handle errors originating from unsuccessful connections to a server named "Event" when using RxJS's fromEvent method

Using rxjs fromEvent to establish a connection with a named sse Event, I am looking to handle an Error in case of connection loss namedEvent() { try { const eventSource = new EventSource( 'adress' ); return fromEvent ...

Challenges in creating an alternative path in ExpressJS

I am currently working on a website for my studies. I decided to use nodejs/Express, as the technology is free. The first route /home was successful, but I am having trouble creating more routes. Although I thought I had a good understanding of the system ...

A guide on sorting an array based on elements from a different array

We are currently in the process of developing an application using Vue and Vuex. Our goal is to display a list of titles for venues that a user is following, based on an array of venue IDs. For instance: venues: [ {venue:1, title: Shoreline} {venue:2, ti ...

Learn how to display HTML content in trNgGrid using the $sce.trustAsHtml method

I am currently working with a table that has search options implemented using trNgGrid.js. The data for this table comes from a Sharepoint list where one of the columns contains HTML content that I need to display. To achieve this, I attempted using $sce. ...

Fetch data dynamically upon scrolling using an AJAX request

Instead of making an ajax call to load data, I want to do it on scroll. Here is the code I have: $.ajax({ type: 'GET', url: url, data: { get_param: 'value' }, dataType: ' ...

What could be causing AngularJS to truncate my URL in the search bar?

Currently, I am in the process of setting up a state provider for a CRUD website. One issue I encountered is that when I navigate to www.mysite.com/posts/mypost, the URL gets shortened to www.mysite.com/mypost and does not trigger the controller as intend ...

Execute the function at intervals of 2 seconds until the variable is altered

Is there a way to make sure that the interval function stops running once theImage length exceeds 0? The Code I'm Using var theImages = $('.awesome-slider .slides img'); function checkImages(){ theImages = $('.awesome-slider .sli ...

Google Chrome's development tools are unable to detect the manifest

I have a file named manifest.json, and I included it in my HTML using <link rel="manifest" href="./manifest.json">. Despite everything seeming correct, Chrome developer tools are unable to detect my manifest file! This is the content of my manifest ...

Exploring the process of defining and authenticating an array of objects utilizing cuid as the key and ensuring the object contains designated properties

I have a customized data set that requires validation: { "name": "Some unique name", "blocks": [ {"cj5458hyl0001zss42td3waww": { "quantity": 9, "rate": 356.77, ...

What is the best way to deliver flash messages using Express 4.0?

Currently, my web application requires authentication, and I am encountering an issue with the signup page. If a user tries to sign up with an email that is already in the database, I want to display an error message. Here is the code snippet I am using on ...

Using Conditions in AngularJS: Choosing Between Callbacks and Promises in a Service

I am currently faced with a specific scenario where I am uncertain whether to implement a callback or a promise. As someone who is relatively new to promises and just beginning to grasp their concept, I want to avoid falling into any potential anti pattern ...

The controller function is not triggered if the user does not have administrator privileges

I have a code snippet in which my controller function is not being triggered for users who do not have the role of "Admin". Can someone help me identify where I went wrong? Just to clarify, the controller function works fine for users with the role of "Adm ...

The error message "node Unable to iterate over property 'forEach' because it is undefined" appeared

I am facing an error and unable to find the solution. I believe my code is correct. It is related to a video lesson where I attempt to display popular photos from Instagram using the Instagram API. However, when I try to execute it, I encounter this issue. ...

Does the modularization of code impact the performance of the react-app?

The client provided me with a React app that includes an index.jsx file where 90% of the coding has been completed. To prevent getting stuck in Scroll Limbo, I have started breaking down the code into modules for each specific requirement. These include ...

ES6 module import import does not work with Connect-flash

Seeking assistance with setting up connect-flash for my nodejs express app. My goal is to display a flashed message when users visit specific pages. Utilizing ES6 package module type in this project, my code snippet is as follows. No errors are logged in t ...