Concealing a label for a certain range of values

Does anyone have a clever solution for dynamically hiding a label associated with an input range element when the value is below a certain threshold? And then reappearing it once the value surpasses a specific minimum?

Any thoughts on this matter?

Thank you

$('input[type="range"]').on('mouseup', function() {
  this.blur();
}).on('mousedown input', function() {
  $('#1').text(this.value + "%");
  $('#2').text(100 - this.value + "%");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="container">
  <input type="range" min="0" max="100" step="1" value="50" />

  <div class="container2">
    <label id="1">50%</label>
  </div>

  <div class="container3">
    <label id="2">50%</label>
  </div>
</div>

Answer №1

To validate a condition, you can use an if statement and then utilize hide() or show() to display or hide the desired element.

For instance, in the scenario below, the label with id="2" is displayed when the value is 50 or higher, and hidden when the value is lower.

$('input[type="range"]').on('mouseup', function() {
  this.blur();
}).on('mousedown input', function() {
  var label1value = this.value;
  var label2value = 100 - this.value;

  $('#1').text(this.value + "%");
  $('#2').text(100 - this.value + "%");
  
  // check if value is greater than or equal to 50
  if (this.value >= 50) {
    // display element if the condition is met
    $('#2').show();
  } else {
    // hide element if the condition is not met
    $('#2').hide();
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="container">
  <input type="range" min="0" max="100" step="1" value="50" />

  <div class="container2">
    <label id="1">50%</label>
  </div>

  <div class="container3">
    <label id="2">50%</label>
  </div>
</div>

Answer №2

It seems like you're looking for a way to hide the range label when the value is below 50. Below is a code sample along with a demo to help you achieve that.

Using Plain JavaScript

// When the document is loaded
document.addEventListener("DOMContentLoaded", function() {
  var rangeLimit = 50;

  function rangeValueListener(event) {
    var rangeElement = event.target || event.srcElement;
    setRangeLabelValue(rangeElement);
  }

  function setRangeLabelValue(rangeElement) {
    var rangeLabelElement = document.querySelector(
      'label[for="' + rangeElement.id + '"]'
    );
    
    var rangeValue = rangeElement.value;
    rangeLabelElement.innerText = rangeValue + "%";

    if (rangeValue < rangeLimit) {
      rangeLabelElement.style.display = "none";
    } else {
      rangeLabelElement.style.display = "initial";
    }
  }

  var rangeElement = document.querySelector("#myRange");
  rangeElement.addEventListener("input", rangeValueListener);
  rangeElement.addEventListener("change", rangeValueListener);
  setRangeLabelValue(rangeElement);
});

Code snippet using jQuery (adapted from the above)

$(document).ready(function() {
  var rangeLimit = 50;
  var rangeDefaultValue = 65;

  function rangeValueListener(event) {
    setRangeLabelValue(event.target);
  }

  function setRangeLabelValue(rangeElement) {
    var rangeElementId = rangeElement.id || rangeElement.attr("id");
    var rangeLabelElement = $('label[for="' + rangeElementId + '"]');
    var rangeValue = rangeElement.value || rangeDefaultValue;
    rangeLabelElement.text(rangeValue + "%");
    if (rangeValue < rangeLimit) {
      rangeLabelElement.hide();
    } else {
      rangeLabelElement.show();
    }
  }

  var rangeElement = $("#myRange");
  rangeElement.on("input change", rangeValueListener);
  setRangeLabelValue(rangeElement);
});
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <title>Document</title>
  </head>
  <body>
    <input id="myRange" type="range" min="0" max="100" step="1" value="65" />
    <label for="myRange"></label>
  </body>
</html>

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

Node 18 is having trouble locating NPM and is unable to locate the module './es6/validate-engines.js'

Previously, I attempted to install Node.js without any issues. However, this time around, I am encountering difficulties accessing the npm package. While I can successfully retrieve the version of Node.js after installation, attempting to check npm -v or w ...

How to include <li> in a preexisting <ul> using JSON data in jQuery

Here is the code snippet I am currently working with: <div id="tags"> <ul> </ul> </div> I want to add some items to the list using JSON data $.getJSON("data.json", function (data) { var html = ''; ...

How to make a JQuery list item unselectable when appending it

I encountered a strange issue while using jQuery to append items to a list. <ul id="idNicheItems" class="clScrollItems ui-widget-content ui-corner-all"> <li id="NicheItem_1"> Item 1</li> <li id="NicheItem_2"> Item 2</li& ...

tips on utilizing the JSON information transmitted from the backend

$.ajax({ url: '{{ URL('reports/groupsUsersGet') }}', dataType: "json", data: { group_id : $('#group').val(), }, success: function(data) { <li>"i need to insert variable here"</li> }, error: function (data) ...

How can I retrieve a data field with a colon in its key using Cytoscape.js?

After diligently going through the official documentation and following the steps in the tutorial, I have successfully managed to access a node's data field and use it for labeling, as long as the key is a simple string. However, my data will contain ...

Click on a row in ReactTable to toggle the background color or expand the row

Is there a way to toggle the row background color in ReactTable when it is expanded? I have tried using onExpandedChange but haven't had any success. Any suggestions on how to achieve this would be greatly appreciated. Thank you! https://i.sstatic.ne ...

How can you temporarily delay the original ajax request until a certain condition is satisfied before proceeding?

I'm looking to set up a recaptcha process that intercepts all ajax requests before they are executed - here's how I envision the process unfolding: A user performs an action that triggers an ajax request. If the user has already completed the r ...

Difficulty with AngularJs Translation Partials

I have encountered an issue with binding translation. Some objects are converting to their translated value successfully, while others, as mentioned below, are not working. This problem only occurs the first time I build the project. Upon refreshing, every ...

res.render() Displaying Data in Frontend using Local Variables

I have a question regarding defining local variables in Express. When I use res.render(view, {variable: variable}), how can these variables be accessed on the frontend? Where are they stored? I attempted to access a variable with console.log(variable), but ...

Can you pinpoint the weak wiring in this AngularJS function?

I am currently studying AngularJS and I suspect there may be a glitch in my page. On the page, there is a TEXTAREA where I have typed 'aaa'. The TEXTAREA is linked to an ng-model named input. The following AngularJS code aims to monitor external ...

Performing a JavaScript AJAX request to send a complex object containing an array of other complex objects within it

My issue arises from encountering an empty array of objects at the backend. To illustrate, I have established two classes at the backend... public class ScoreModel { public string Subject { get; set; } public float Score { get; set; } ...

Performing calculations within handsontable

Trying to figure out how to concatenate values from a handsontable grid, I stumbled upon some code on jsfiddle that caught my eye. Here is the link: http://jsfiddle.net/9onuhpn7/4/ The task at hand involves 3 columns A,B,C and an attempt to concatenate ...

The functionality of the click event attached with the addEventListener is

I have a unique project where I am developing a user interface for a paper-rock-scissor game. To create the UI, I included four buttons: "Start game," "rock," "paper," and "scissor." Initially, I wrote separate code for each button, which worked perfectly ...

Using JavaScript to pass a newly created variable as an argument in a default

Currently, I am developing a node application that heavily utilizes promises. To enhance the readability of my code, I have been removing anonymous functions and storing them in a JavaScript object called "myCallbacks". Here's an example: let myCallb ...

Troubleshooting: Jquery show effects not functioning as expected

Currently, I am facing an issue where I am attempting to display a fixed div using the show function of jQuery. Although the show function itself is working properly, when I try to include an effect from jQuery UI, it does not seem to work as expected. Bot ...

Is it possible for amCharts to show the data properly?

Starting out with amCharts and javascript can be a bit overwhelming. Here is the structure of my html file: <!DOCTYPE html> <html> <head> <link rel="shortcut icon" href=""> <title>chart created with amCharts | amChar ...

Execute a Python script using an Ajax jQuery call

Recently, I encountered an issue when attempting to execute a python file via jQuery. To address this problem, I conducted research online and came across a specific code snippet designed to call and run a python script. Below is the AJAX code utilized fo ...

One or multiple web browsers set in the Browserslist of the project

I have recently started working with the Ionic framework and encountered some warnings while setting up my application. Can anyone help me with a solution? [ng] When starting the Ionic application, I received the following warnings: [ng] One or more browse ...

Any tips on how to retrieve the data from an AJAX request using vanilla JavaScript?

After successfully implementing my first AJAX call last week, I am now faced with a new challenge. This time, I need to not only change something onSuccess but also access the returned data. <script type="text/javascript"> function showMessage(j ...

What steps can I take to perform unit testing on a custom element?

While working on a project where I have a class that extends HTMLElement, I came across some interesting information in this discussion: https://github.com/Microsoft/TypeScript/issues/574#issuecomment-231683089 I discovered that I was unable to create an ...