0

I made a function in javascript that changes the height of a triangle. I also made a range slider. I am trying to get the slider to change the height of the triangle however I am struggling to get this to work.

HTML

    <!DOCTYPE html>
<html lang="en">

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.1.9/p5.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.1.9/addons/p5.sound.min.js"></script>
  <link rel="stylesheet" type="text/css" href="style.css">
  <meta charset="utf-8" />

</head>

<body>
  <script src="sketch.js"></script>
  <input type="range" name="rangeInput" min="20" max="40" value="20" id="height">
</body>

</html>

JavaScript

//default ramp parameters
let rampHeight = 150;
let rampLength = 150;

function setup() {
  createCanvas(800, 500);
}

function draw() {
  background(220);
  fill(150);
  triangle(700, rampHeight, 700, 400, rampLength, 400);
}

function changeHeight(height) {
  rampHeight = 500 - height * 10;

  if (height >= 20 && height <= 40) {
    return rampHeight;
  } else if (height > 40) {
    return rampHeight = 100;
  } else if (height < 20) {
    return rampHeight = 300;
  }
}

changeHeight(document.getElementById('height').value)

I am using the p5.js online web editor to code this by the way.

jonasg
  • 13
  • 2

2 Answers2

0

You would need to listen to the change or input event of the slider, and then change the height accordingly.

so add

document.querySelector('#height').addEventListener('input',(e)=>{
  changeHeight(e.target.value)
})
Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
0

you need to add eventlistener to slider element and listen for change event so that you can invoke changeHeight function.

var slider = document.getElementById('height')
slider.addEventListener('change', function(){ changeHeight(this.value)});

here is a working fiddle

sandeep joshi
  • 1,991
  • 1
  • 8
  • 13