Why does my console.log output the incorrect HTML slider value in JavaScript?

47 Views Asked by At

I am creating a web form and I am using HTML sliders as one of my input methods. I am using to output the current value of the slider on the page as the value of the slider changes. This currently works. However, there are also minimum and maximum values, which are calculated using clamp() to keep it within 0 and 1, and by subtracting or adding 0.05 respectively. When I try to output these values in the console, the outputted value is completely different to the slider value.

Here is the section of my code where the console.log function is:

// Add event listeners to sliders
document.addEventListener('DOMContentLoaded', () => {
  // Iterate over each slider object
  Object.keys(sliders).forEach(key => {
    // Get the current slider object
    const slider = sliders[key];
    // Find the corresponding slider input element in the HTML using its ID
    const sliderElement = document.getElementById(`${key.toLowerCase()}Slider`);
    // Add event listener to detect changes in slider value
    sliderElement.addEventListener('input', () => {
      // Update value of Slider object
      const sliderValue = parseFloat(sliderElement.value);
      slider.setValue(sliderValue);
      // Update display element with current slider value
      const sliderValueElement = document.getElementById(`${key.toLowerCase()}Value`);
      // Fixes the text value to be within 3 decimal places
      sliderValueElement.textContent = sliderValue.toFixed(3); 
    });
  });
    // Add event listener to the submit button
  const submitButton = document.querySelector('button[type="submit"]');
  submitButton.addEventListener('click', (event) => {
    // Prevent the default form submission behavior
    event.preventDefault();    
    // Iterate through each slider object
    Object.keys(sliders).forEach(key => {
      const slider = sliders[key];
      // Log the current value, minimum value, and maximum value of the slider
      console.log(`${slider.name} - Current value: ${slider.getValue()}, Min value: ${slider.getMinValue()}, Max value: ${slider.getMaxValue()}`);
    });
  });  
});

// Define a class for slider controls
class Slider {
  // Constructor method to initialize a slider
  constructor(name, initialValue) {
    // Store the name of the slider
    this.name = name; 
    // Set the initial value of the slider
    this.value = initialValue; 
    // Calculate the minimum and maximum values based on initial value
    // These will be used to provide a range of potential values for the SQL query
    // This will provide us with a greater number of songs for the playlist
    // Ensure minValue is at least 0 (The minimum value for all Spotify variables)
    this.minValue = Math.max(0, this.value - 0.05);
    // Ensure maxValue is at most 1 (The maximum value for all Spotify variables)
    this.maxValue = Math.min(1, this.value + 0.05); 
  }

  // Method to set a new value for the slider
  setValue(newValue) {
    // Restrict the value to a specific range as outlined by minValue and maxValue (Clamping)
    // If it does exceed the range limits it is adjusted to stay within said limits
    this.value = Math.min(Math.max(newValue, this.minValue), this.maxValue);
    // Update minValue based on the new value
    this.minValue = Math.max(0, this.value - 0.05);
    // Update maxValue based on the new value
    this.maxValue = Math.min(1, this.value + 0.05);
  }

  // Method to get the current value of the slider
  getValue() {
    // Return the current value of the slider
    return this.value;
  }

  // Method to get the minimum value of the slider
  getMinValue() {
    // Return the current minimum value of the slider
    return this.minValue;
  }


  // Method to get the maximum value of the slider
  getMaxValue() {
    // Return the current maximum value of the slider
    return this.maxValue;
  }
}

// Create instances of Slider class for each variable
const sliders = {
  Acousticness: new Slider('Acousticness', 0.5),
  //Danceability: new Slider('Danceability', 0.5),
  //Energy: new Slider('Energy', 0.5),
  //Instrumentalness: new Slider('Instrumentalness', 0.5),
  //Valence: new Slider('Valence', 0.5),
  //Speechiness: new Slider('Speechiness', 0.5),
  //Liveness: new Slider('Liveness', 0.5)
};

// Add event listeners to sliders
document.addEventListener('DOMContentLoaded', () => {
  // Iterate over each slider object
  Object.keys(sliders).forEach(key => {
    // Get the current slider object
    const slider = sliders[key];
    // Find the corresponding slider input element in the HTML using its ID
    const sliderElement = document.getElementById(`${key.toLowerCase()}Slider`);
    // Add event listener to detect changes in slider value
    sliderElement.addEventListener('input', () => {
      // Update value of Slider object
      const sliderValue = parseFloat(sliderElement.value);
      slider.setValue(sliderValue);
      // Update display element with current slider value
      const sliderValueElement = document.getElementById(`${key.toLowerCase()}Value`);
      // Fixes the text value to be within 3 decimal places
      sliderValueElement.textContent = sliderValue.toFixed(3); 
    });
  });
    // Add event listener to the submit button
  const submitButton = document.querySelector('button[type="submit"]');
  submitButton.addEventListener('click', (event) => {
    // Prevent the default form submission behavior
    event.preventDefault();    
    // Iterate through each slider object
    Object.keys(sliders).forEach(key => {
      const slider = sliders[key];
      // Log the current value, minimum value, and maximum value of the slider
      console.log(`${slider.name} - Current value: ${slider.getValue()}, Min value: ${slider.getMinValue()}, Max value: ${slider.getMaxValue()}`);
    });
  });  
});
<!-- Label for slider -->
<label for="acousticnessSlider">Acousticness:</label> 
<!-- Range input element type for the slider -->
<input type="range" id="acousticnessSlider" min="0" max="1" step="0.001" value="0.5">
<!-- Span to display current value of the slider -->
<span id="acousticnessValue" class="slider-value">0.5</span>
<br> <!-- Line break -->

<button type='submit'>Submit</button>

If I test it by setting slider value to say, 0.025 the expected console.log should be 'Acousticness - Current value: 0.025, Min value: 0, Max value: 0.075' However, the actual input ends up being something like this: 'Acousticness - Current value: 0.60000000000001, Min value: 0.55, Max value: 0.65000000000001' This is not limited to when I carry out boundary testing. It occurs at any value, and the value that it outputs is seemingly random. Also, sometimes, the output is correct, and at other times it isn't.

Is there something wrong with my console.log logic? Or am I initialising the slider value incorrectly? Or is it a secret third option? Any help would be very much greatly appreciated. Thank you!

0

There are 0 best solutions below