简体   繁体   中英

Progress bar, max and reset on 100%

Im working on a progress bar connected to XP and MAX XP in sql. On every click on a button you get 1 xp and max xp is 10. I would like so that when a user reaches 100% XP it should reset back to 0%. And if you have an idea on how to use that "reset" to increase a value of on this case the level of the user should have his current level + 1 on 100% reset.

Im inserting 1 xp every click by this code:

$sql = "UPDATE progression SET xp=(xp + 1) WHERE username='$username' LIMIT 1";

Im creating the 100% xp bar values by making 1 xp = to 10% of the bar from this code:

$percent = intval($resultprogression[0]['xp']*100/$resultprogression[0]['max xp']);

And im doing the output in html/css by this code:

<div class="experience-bar-container">
        <div id="value" style="width:<?php echo $percent ?>%;"></div>
        <h3>XP: <span><?php echo $percent ?>%</span></h3>
</div>


div#value {
   display: block;
   position: absolute;
   z-index: 2;
   height: 19%;
   background: red;
   left: 0;
 }

You'll have to use js. A solution : add a data-attribute to the progress div to store the progress value :

<div class="experience-bar-container">
  <div id="value" data-value="<?php echo $percent ?>" style="width:<?php echo $percent ?>%;"></div>
  <h3>XP: <span id="xpPercent"><?php echo $percent ?>%</span></h3>
  <button class="xpButton" id="minus">-</button>
  <button class="xpButton" id="plus">+</button>
</div>

Then add listeners on your buttons that use the data-attribute value to update the bar width :

var progress = document.getElementById("value");
var xpPercent = document.getElementById("xpPercent");

document.getElementById("minus").addEventListener("click", function() {
  var newValue = parseInt(progress.getAttribute('data-value')) - 10;
  update(newValue);
});
document.getElementById("plus").addEventListener("click", function() {
  var newValue = parseInt(progress.getAttribute('data-value')) + 10;
  update(newValue);
});

The "update" function check the progression, and call the reset function if needed which calls the dbupdate function

function update(newValue) {
  progress.style.width = newValue + '%';
  progress.setAttribute('data-value', newValue);
  xpPercent.innerText = newValue + '%';
  if (newValue === 100) {
    reset();
  }
}:

function reset() {
  progress.style.width = '0%';
  progress.setAttribute('data-value', 0);
  xpPercent.innerText = '0%';
  dbUpdate();
}

function dbUpdate() {
  // do Ajax stuff to update user's level
}

https://jsfiddle.net/qpg7t603/1/

If you don't plan to support IE10 you should have a look at the progress tag : https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Progress

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM