Reputation: 130
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
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
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