Home > Software engineering >  JavaScript for Changing width of DiV element using range slider
JavaScript for Changing width of DiV element using range slider

Time:12-28

I'm trying to do a html5 canvas drawing app and i can't figure out how to change de line width for the shapes using a range slider. PLease help me with the javascript or tell me where i'm wrong This is my html code:

<div id="toolbar2">

    <input oninput="strokeColor = this.value" type="color" >
    <input oninput="lineWidth = this.value" type="range" min="1" max="50" >
    
</div> 

The oninput strokeColor worked.

This is what i tried in JS:

function change_width(element) {
    lineWidth = element.innerHTML
  }

CodePudding user response:

In the inline version which works you use the value of the element.

In the other version you have used innerHTML.

Try using element.value instead.

CodePudding user response:

Rather than the naive inline event handlers used you could quite easily use a single external event listener to process each input that you use to control the properties of the canvas. If you were to assign each DOM element a dataset attribute that relates to the property to be modified/monitored you could assign these to the global window object at page load and update these window properties when the value of the input element changes.

The below code simply prints the name and value to the console but you would likely use a callback to redraw the canvas to reflect the variable changes?!

document.querySelectorAll('input[data-attr]').forEach(input=>{
  window[ input.dataset.attr ]=0;
  
  input.addEventListener('change',function(e){
    window[ this.dataset.attr ]=this.value;
    console.info('attr:%s value:%s',this.dataset.attr,window[ this.dataset.attr ])
  })
  
  
});
<div id="toolbar2">

    <input data-attr="fillColor" type="color"  />
    <input data-attr="strokeColor" type="color"  />
    <input data-attr="lineWidth" type="range" min="1" max="50"  />
    <input data-attr="opacity" type="range" min="1" max="50"  />
    
</div> 

  • Related