Reset Variable Flag to original state

740 views Asked by At

When a user empties the cart it removes all items and the page reloads. The page will reload in order to reset the buttons that are activated (all buttons with .button class will reset to there original state) There should be a way to reset the buttons without needing to reload the page. Instead of the function preforming location.reload is there a function that can reset all flags to "99cents.png"

<script>
$(".button").on('click', function(){
    var flag = $(this).data('flag');

    simpleCart.add({
        name     : $(this).attr("data-product-id"),
        price    : .99,
        quantity : (flag ? -1 : 1)
    });

    $(this).attr("src", flag ? "99cents.png" : "m99cents.png");

    $(this).data('flag', !flag);
});
function reloadFunction() {
location.reload();
}
</script>
2

There are 2 answers

0
Neil Cross On

Store the original state in a data also. When reloadFunction is called, you can retrieve the state from this property and replace the source attribute.

In the html:

<img class="button" src="originalsrc.png" />

In the javascript:

$(function(){
  $(".button").each(function(i,el)
                    {
                      var el = $(this);
                      el.data('flag-original', el.attr('src'));
                    });
});

function reloadFunction() {
  $(".button").each(function()
                    {
                      var el = $(this);
                      el.text(el.data('flag-original'));
                    });
}
0
Jeff On

After some research on jquery I discovered there was a method I could use called .removeData(); with this I was able to achieve the desired task by adding a class called ".empty" to the empty cart button. Here is what I came up with that works:

$(".empty").on('click', function(){

    $(".button").attr("src", "99cents.png");

    $(".button").removeData();
});

.removeData() was able to clear out everything without needing to refresh the page!

Thank you!