Reputation: 5
I have a chat box in the bottom right of my website, that opens and closes no problem. It is hidden by default, and then when you click on "chat" it stays open! My problem is that I would want the chatbox to stay open when a user changes pages until they decide to minimize it again. At the moment, if you change pages the chatbox minimizes itself. Can someone help?
jQuery(document).ready(function() {
jQuery('#hideshow').on('click', function(event) {
jQuery('#initiallyHidden').toggle('show');
});
});
#chatbox {
position: fixed;
bottom: 0;
right: 0;
float: right;
}
#initiallyHidden {
bottom: 100;
right: 0;
float: right;
width: 300px;
height: 200px;
border-style: solid;
background-color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="chatbox"><input type="button" id="hideshow" value="Quick Chat" class="tbox" />
<br>
<div id="initiallyHidden" style="display: none;">Content</div>
Above is the scripts all used for this.
Thanks
Upvotes: 0
Views: 1671
Reputation: 1159
It seems to me, that Cookie or Local storage is needed to be used to persist the user preferences for the current session. So when page is rendered, check the initial state and update state with every click.
The example of using cookies can be found here.
So the example will look like this (using js-cookie):
$(document).ready(function() {
var chatVisible = 'chatVisible';
var chatElement = $('#initiallyHidden');
var getCookie = function() {
return JSON.parse(Cookies.get(chatVisible) || 'false');
};
var setCookie = function(value) {
Cookies.set(chatVisible, value)
};
var visible = getCookie();
chatElement.toggle(visible);
setCookie(visible);
$('#hideshow').on('click', function() {
var visible = !getCookie();
setCookie(visible);
chatElement.toggle(visible);
});
});
#chatbox {
position: fixed;
bottom: 0;
right: 0;
float: right;
}
#initiallyHidden {
bottom: 100px;
right: 0;
float: right;
width: 300px;
height: 200px;
border-style: solid;
background-color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/js-cookie@beta/dist/js.cookie.min.js"></script>
<div id="chatbox">
<input type="button" id="hideshow" value="Quick Chat" class="tbox" />
</div>
<br>
<div id="initiallyHidden" style="display: none;">
Content
</div>
Please note, that cookies in chrome work properly when you use web server to serve your files, not just opening the file. If you need that possibility, please refer this answer. Firefox is OK with serving cookies even for static files.
Upvotes: 0
Reputation: 250972
In order to keep the chat window state between pages, you will need to persist the state somewhere.
For example, when the user opens the chat, you could set a cookie to store the new state. When loading each page, you would check the cookie for the current state (open / closed) and default if no cookie is available.
Upvotes: 1