0

I have used following code to let user change the body background-image by clicking a button:

<script>
    $(document).ready(function() {
         $(".button1").click(function() {
            $("body").css("background-image", "url('')");
         });
    });
</script>

It really works, but when I click the a article to enter the article page, the body background-image changes back to previous image. So how to make a permanent change by clicking a button.Thanks a lot.

Shiladitya
  • 12,003
  • 15
  • 25
  • 38
  • Possible duplicate of [Persist variables between page loads](https://stackoverflow.com/questions/29986657/persist-variables-between-page-loads) – Sebastian Simon Nov 03 '17 at 04:47
  • 1
    You should explore storing these adjustments in cookies or using javascript session storage - none of these solutions are eternal though, although persistent (especially in the case of session storage) at some point these settings can still be cleared. – UncaughtTypeError Nov 03 '17 at 05:13

1 Answers1

0

What you need to do is, you need to store a flag variable in session/cookie to check, if user has clicked on button to change to background image or not.

When you reload the page or redirect to other page, you need to get that session/cookie value and based on its value you need to set the background image of <body>.

Here is the code by which you can get what you want to do:

jQuery Code:

jQuery(document).ready(function() {
    call_Ajax_get_set_session('get');
    jQuery(".button1").click(function() {
        call_Ajax_get_set_session('set');
    });
});

function call_Ajax_get_set_session(value){      
    data = {
        action : 'setBgImage',
        method : value
    };
    // first parameter will be the ajax url.
    jQuery.post('<?php echo admin_url( 'admin-ajax.php' );?>', data, function(response) {
        response = jQuery.parseJSON(response);
        if(response.success == '1'){
            jQuery("body").css("background-image", "url('')");
        }
    });
}

PHPCode in Function.php file of your active theme:

add_action( 'wp_ajax_nopriv_setBgImage', 'setBgImage' );
add_action( 'wp_ajax_setBgImage', 'setBgImage' );

function setBgImage() {
    $method = $_POST['method'];
    if(session_id() == '') // check session has already start or not
    {
        session_start();
    }   

    if($method == 'set'){
        $_SESSION['setBgImage'] = '1';
        echo json_encode(array('success' => 1));
        exit;
    }
    else if($method == 'get'){
        if(isset($_SESSION['setBgImage']) && $_SESSION['setBgImage'] == '1'){
            echo json_encode(array('success' => 1));
            exit;
        }
        else{
            echo json_encode(array('success' => 0));
            exit;
        }
    }
    echo json_encode(array('success' => 0));
    exit;
} 

Please let us know if you need more help in this.

Thanks!

AddWeb Solution Pvt Ltd
  • 21,025
  • 5
  • 26
  • 57