Pratyush
Pratyush

Reputation: 130

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.

Upvotes: 2

Views: 780

Answers (2)

user94559
user94559

Reputation: 60153

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>

Upvotes: 2

Pratyush
Pratyush

Reputation: 130

I figured out a way that worked for me, I used a variable with global scope to store value of cookie. defined a method to check if cookie value is not same as that of variable, refresh the page.

But if you don't need to refresh the current page update the value of variable whenever you update cookie.

So basically i am refreshing other tabs but not my current tab. I know this is not the best way to do this, but it will do the job.

If you find something more efficient please post.

Upvotes: 0

Related Questions