Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update div element value based on cookie in multiple tabs

I'm inserting and removing div's based on value of cookie. the value of cookie is updated by checking and un-checking the check box. this works fine for a single tab. but how to update div's in other tab also if multiple tabs are opened for same page. The cookie value is updated as it remains same for browser, but how to add or remove div's with respect to cookie value.

like image 815
Pratyush Avatar asked Jun 14 '16 05:06

Pratyush


1 Answers

If you're okay with using local storage instead of a cookie, you can use the storage event, which fires when a change is made to local storage.

See http://synccheckbox.site44.com/ for a running example. Code pasted below:

<!doctype html>
<html>
<head>
    <style>html { font-family:Arial }</style>
</head>
<body>
    This checkbox should synchronize between open tabs:
    <input type="checkbox" id="checkbox" />

    <script>
        function updateCheckbox() {
            document.getElementById('checkbox').checked =
                (localStorage.checked === 'true');
        }
        updateCheckbox();

        document.getElementById('checkbox').addEventListener('change', function () {
            localStorage.checked = this.checked;
        });

        window.addEventListener('storage', function () {
            updateCheckbox();
        });
    </script>
</body>
</html>
like image 120
user94559 Avatar answered Nov 09 '22 05:11

user94559