In the previous article, we saw how we can change the width/height of an image with input value in Vue.js. In this tutorial, we’ll look at how we can change with size (width attribute) of an image with the HTML range slider in Vue.js. Here’s the code we’d need to implement the functionality:
<template>
<div>
<h3>Vue 3 change image size with input slider example</h3>
<div class="np-slide-container">
{{ sliderValue }}%
<input
type="range"
min="1"
max="100"
v-model="sliderValue"
class="np-slider"
/>
</div>
<div class="np-img-container">
<img
src="https://picsum.photos/id/46/600/400"
:style="{
width: `${sliderValue}%`,
borderRadius: '10px',
}"
/>
</div>
</div>
</template>
<script>
export default {
name: "App",
data() {
return {
sliderValue: 35,
};
},
};
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
.np-slide-container {
width: 300px;
margin: 0 auto;
}
.np-img-container {
max-width: 600px;
margin: 0 auto;
}
.np-slider {
-webkit-appearance: none;
width: 100%;
height: 20px;
background: #131313;
border-radius: 20px;
outline: none;
opacity: 0.7;
-webkit-transition: 0.2s;
transition: opacity 0.2s;
margin: 10px 0;
}
.np-slider:hover {
opacity: 1;
}
.np-slider::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 35px;
height: 20px;
background: #acacac;
border-radius: 20px;
cursor: pointer;
}
.np-slider::-moz-range-thumb {
width: 35px;
height: 20px;
background: #acacac;
border-radius: 20px;
cursor: pointer;
}
</style>
Code language: HTML, XML (xml)
In the above file, we initialized a reactive state named sliderValue with a default value of 35. Next up, we created an input range slider on line 6 and v-model it with the reactive state sliderValue. It’ll take a minimum value of 1 and a maximum value of 100.
Then on line 19, we’ve used an img element and bound it’s width value with the sliderValue in percentage. It means that the default width of the image will be 35%. Of course, we can also use values in pixels (px). We’d need to change with min and max range set on the input slider accordingly in that case.
Starting line 39, we’ve styled our range slider with custom CSS.
Here’s what the above component would look like in action:
You can find a working version of the above code from my repos below: