| | |

Simple Progress Bar in Alpine JS!

First, install Alpine js and tailwind css in your project.

Read this: How to install AlpineJS and TailwindCSS on my project?

Create a div with a class of “progress-bar” and set the x-data attribute to an object with a property called “percentage” set to 0.

<div class="progress-bar" x-data="{ percentage: 0 }">
</div>

Inside the div, create a div with a class of “progress” and set the x-bind attribute to “style=’width: percentage + ‘%'” to bind the width of the progress div to the percentage property in the x-data object.

<div class="progress-bar" x-data="{ percentage: 0 }">
  <div class="progress" x-bind:style="'width: ' + percentage + '%'">
  </div>
</div>
Add a button below the progress bar with an x-click attribute to increase the percentage property by 10 when clicked.
<div class="progress-bar" x-data="{ percentage: 0 }">
  <div class="progress" x-bind:style="'width: ' + percentage + '%'">
  </div>
  <button x-click="percentage += 10">Increase Progress</button>
</div>

Style the progress bar and progress div using tailwind css classes. For example, you can use the “bg-blue-500” class for the progress div and the “h-8” class for the height of the progress bar.

<div class="progress-bar h-8" x-data="{ percentage: 0 }">
  <div class="progress bg-blue-500" x-bind:style="'width: ' + percentage + '%'">
  </div>
  <button x-click="percentage += 10">Increase Progress</button>
</div>

You can also add a label to display the current percentage by adding a span element with an x-text attribute set to “percentage + ‘%'”.

<div class="progress-bar h-8" x-data="{ percentage: 0 }">
  <div class="progress bg-blue-500" x-bind:style="'width: ' + percentage + '%'">
  </div>
  <span x-text="percentage + '%'"></span>
  <button x-click="percentage += 10">Increase Progress</button>
</div>

You can also add a maximum percentage limit by adding an x-init attribute to the progress bar div to set the maximum percentage to 100.

<div class="progress-bar h-8" x-data="{ percentage: 0 }" x-init="percentage = Math.min(percentage, 100)">
  <div class="progress bg-blue-500" x-bind:style="'width: ' + percentage + '%'">
  </div>
  <span x-text="percentage + '%'"></span>
  <button x-click="percentage += 10">Increase Progress</button>
</div>

Finally, you can customize the progress bar further by adding more tailwind css classes and using the x-bind attribute to bind

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *