What steps should be taken to enable bidirectional functionality for this slider control?

My range slider is currently only working in a single direction (to the right) and it's also dragging out of its parent container (#volume). How can I resolve this issue?

I have included a demo fiddle link for reference.

Markup

<div id="volume">
    <div class="progress">
        <div class="volumeslider"></div>
    </div>
</div>

CSS

#volume{
    width:300px;
    background: #ddd;
    cursor:pointer;
}
.progress{
    height:10px;
    background:#999;
    position:relative;
    width:0;
}
.volumeslider {
    background: #808080;
    position: absolute;
    width: 20px;
    height: 20px;
    border-radius: 15px;
    right: -10px;
    top: -5px;
}

JS

$('.volumeslider').bind('mousedown', function(e){
    $('.volumeslider').bind('mousemove', function(e){
        $('.progress').width(e.pageX - $('.progress').offset().left + 'px');
        $(this).css('left', e.pageX - ($(this).width()/2) );
    });
    $('.volumeslider').bind('mouseup',function(){
        $('.volumeslider').unbind('mousemove');
    });
});

JS Fiddle: http://jsfiddle.net/2mYm7/

Answer №1

Your current code does not account for the padding applied to the body element. I have updated the code with some modifications.

$('.volumeslider').bind('mousedown', function (e) {
    console.log('mouse clicked');
    $('.volumeslider').bind('mouseup', function (e) {
        console.log('mouse released');
        $('.volumeslider').unbind('mousemove');
    });
    $('.volumeslider').bind('mousemove', function (e) {
        console.log('mouse moved');
        $('.progress').width(e.pageX - $('.progress').offset().left + 'px');
        $(this).css('left', e.pageX - 25 - $(this).width());
    });
});

Here is the updated jsFiddle link: http://jsfiddle.net/2mYm7/1/

Answer №2

Here is a helpful demonstration on how to ensure your functionality works consistently across all platforms and devices. Currently, the dragging feature will continue indefinitely if you move away from the element.

This example includes boundary validations to ensure that the body of the page is sufficiently large for the dragging action to cease at any location.

http://example.com/jsfiddle

var dragging = null;

function startDrag(){
    console.log('initiated dragging', this);
    var $this = $(this);
    dragging = $this;
    $(document.body).bind('mouseup', stopDrag);
    $(document.body).bind('mousemove', drag);
}

function stopDrag(){
    console.log('concluded dragging', dragging[0]);
    $(document.body).unbind('mouseup', stopDrag);
    $(document.body).unbind('mousemove', drag);
    dragging = null;
}

function drag(e){
    var slider = dragging;
    var progress = slider.parent();
    var container = progress.parent();
    var maxOffset = container.width();
    progress.width(Math.min(e.pageX - progress.offset().left, maxOffset) + 'px');
}

$('.volumeslider').bind('mousedown', startDrag);

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

Tips for transferring PHP results to a database

I am facing an issue with writing data to a database. I need to store the first integer, second integer, and the result in the database. However, despite my attempts at coding, only the first and second integers are being written, not the actual result. A ...

Strange behavior of dropdown submenu

I've encountered an issue where my child's ul li elements are not behaving as expected, despite following advice from other sources. After days of debugging with no success, I am unable to pinpoint the problem. The image showcases the issue perfe ...

Classic ASP offers a feature that allows users to select all checkboxes at once

I'm looking to create a functionality where there is a 'Select all' checkbox along with individual checkboxes for each database record. Is it possible to use JavaScript to ensure that when the 'Select all' checkbox is checked, all ...

Securing your express.js app: The ultimate guide to safeguarding sensitive routes

Currently, I am in the process of developing a Node.js application that utilizes Express.js. In my app.js file, I have set up a route as follows: router.get("/db/:dbName", (req, res) => { var dbName = req.params.dbName ...

Attempting to build a table within a table structure

My goal is to create a nested table structure similar to this image: https://i.sstatic.net/v6lZo.png The number of months, topics, and arguments for each topic can vary as they are retrieved from a database. I have attempted to implement this functionali ...

Tips for maintaining a variable's persistence through Heroku dyno/server restarts and fresh deployments

I need to find a way to persist the values in an array through dyno restarts and code deployments on my Node.js server. The issue I am facing is that every time the server restarts, the 'arrayWithValues' array gets reset to empty. Below is the se ...

The Bootstrap navigation bar is experiencing issues and is not functioning properly, as the classes are not

<nav class="navbar navbar-default"> <div class="container-fluid"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" d ...

Upgrade from "typings" to "@types" using [email protected]

My Angular app is currently using 4.1.3 with <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c094b9b0a5b3a3b2a9b0b480f2eef0eef3">[email protected]</a>. I've heard that for Typescript versions higher than 2.0, ...

Split the flex column into two separate rows

These are the columns I have (Fiddle: https://jsfiddle.net/DTcHh/15420/embedded/result/) https://i.sstatic.net/Uvi0g.png Using flex, I was able to achieve equal height for the columns: @media (min-width: 992px) { .columns-equal { display: -we ...

How can I combine an ordinary image and a CSS2D image in THREE.js CSS2DRenderer and save them together as a single .jpg file?

After implementing the following code... (1) I successfully saved regular rendered THREE.js scenes as .jpg files; (2) Additionally, I managed to utilize CSS2DRenderer to display CSS2D labels on top of the canvas; (3) Now, my goal is to save the image wi ...

Display CSS specifically to the super administrator

I am trying to customize the appearance of certain tables in the WordPress dashboard using CSS so that they are only visible to super admins. <?php is_super_admin( $user_id ); ?> add_action( 'admin_head', 'my_custom_function' ); ...

Issues with the animation feature in AngularJS Material

Despite using angularjs material, the animations are not functioning properly. This is evident when the sidenav does not transition as expected, unlike in the demo. I have already loaded the angular-animate library. <script src="//ajax.googleapis. ...

The gltf model fails to load on Chrome for Android when using Threejs

I encountered an issue while attempting to showcase a basic GLTF 3d model on my website. Surprisingly, it functions smoothly on desktop Mac and Windows, as well as on iOS in Safari and Firefox. However, it fails to load on Android's Chrome browser. St ...

Unable to modify the logo images in React

I'm struggling to figure out how to make my images (favorite.svg and favorite-white.sgv) change every time the button is clicked in React. I've tried various solutions but it's proving to be quite challenging. When the button is clicked, I ...

Can you explain how this particular web service uses JSON to display slide images?

{ "gallery_images": [ {"img":"http://www.jcwholesale.co.uk/slider_img/big/1_1433518577.jpg"}, {"img":"http://www.jcwholesale.co.uk/slider_img/big/1_1433519494.jpg"}, {"img":"http://www.jcwholesale.co.uk/slider_img ...

Triggering the full-screen event for HTML video in Android using the WebKit

Having an issue with the android webkit drawing the video element. I am trying to detect when the video transitions to fullscreen mode upon clicking the fullscreen button located at the bottom right of the video element, but I am unable to do so. There doe ...

Show only a cropped section of a resized image within a div

I have a script that calculates the best region of an image to display within a specific div size. This calculation is done in PHP and generates a JSON output like this: {"scale":1.34,"x1":502,"x2":822,"y1":178,"y2":578} The image in question has dimensi ...

Remove a div using JavaScript

My approach involves dynamically adding div elements using JavaScript in the following manner: <div id="detail[0]"> <input name="detail.Index" type="hidden" value="0" /> <input name="detail[0].details_name" type="text" /> ...

What is the importance of including parentheses when passing a function to a directive?

Hello, I'm currently a beginner in Angular and I am experimenting with directives. Here is the code snippet that I am using: HTML <div ng-app="scopetest" ng-controller="controller"> <div phone action="callhome()"> </div> </div ...

Adjusting the visibility and z-index of HTML5 video controls

Hello, I am facing an issue with a Bootstrap carousel that contains a video. The main problem is that the video controls cannot be clicked due to the carousel indicators overlaying them. I have tried adding margin and padding to the indicators, which worke ...