简体   繁体   中英

Change background color of div based on a value

I am trying to make my basket button have a circular div background turn blue after an item is added to the basket, so far the add to basket function is working perfectly with ajax I just can't somehow toggle background from none to display based on for example if the basket has 1 or more items the background needs to be blue and if the basket has 0 items then background set to none, here is what I have tried so far:

if($objBasket->number_of_items > 0) {
    $background = "block";
} else {
    $background = "none";
}

?>
<p class="in-cart" style="background:<?php echo $background; ?>"><?php echo $objBasket->number_of_items; ?></p>

And the js:

function refreshMiniBasket() {

        $.ajax({

            url: '../modules/basket_mini_nav_refresh.php',
            dataType: 'json',
            success: function(data) {
                $.each(data, function(k, v) {
                    $(".in-cart").text(v);
                });
            },
            error: function(data) {
                alert('Error occurred');
            }

        });

    }

But this only changes the background state when I manually reload the page

Put the code for changing the background inside the success: of the Ajax call.

        success: function(data) {
            $.each(data, function(k, v) {
                $(".in-cart").text(v);
            });

            // Update the JS variable that keeps track
            // of the number of items in the cart.

            // if that variable is > 0, set the background to blue.
            // else, set the background to transparent.
        },

This is more a job for javascript / jquery than php . You can set the initial state of the basket in php, but should make live changes of the basket's state from javascript.

Change your basket's look inside the successCallback of your ajax.

function refreshMiniBasket() {
    $.ajax({
        url: '../modules/basket_mini_nav_refresh.php',
        dataType: 'json',
        success: function (data) {
            //...

            if (parseInt($(".in-cart").text()) > 0)
                $(".in-cart").show();
            else
                $(".in-cart").hide();
        },
        error: function (data) {
            //...
        }
    });
}

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