Hide div permanently until next visit - javascript

I have the following div with class "fullscreen"
<div class="fullscreen">
</div>
Inside that div, there is a button that once clicked, it will scroll down to anther div that has an ID of "#page".
The question is, how do I permanently hide the div with the class "fullscreen" once scrolled to "#page" and settled down? It has not to show again at all until the website has been visited again, even if navigated away from the page and went back to it.
Please find the live example here, as it will clarify everything: http://loaistudio.com/anita/
The HTML code of the button:
Find Out How
The JS:
//Smooth Scroll
$('a').click(function(){
$('html, body').animate({
scrollTop: $( $(this).attr('href') ).offset().top
}, 1500);
return false;
});

Final Update:
I have outlined how to store a value with cookies, localStorage, or server-side sessions below. This is how I would implement these solutions with your posted code:
//Smooth Scroll
$('a').click(function(){
$('html, body').animate({
scrollTop: $( $(this).attr('href') ).offset().top
}, 1500);
/* We have animated, lets set the variable to never do this again */
if(supports_storage()) localStorage['nofullscreen'] = true;
return false;
});
Above, we are setting our localStorage variable (i've named it 'nofullscreen', feel free to replace with whatever makes sense to you) to true, so we know the user has seen our fullscreen already. Now, when the page loads, we want to check for the variable, and act accordingly:
$( document ).ready(function() {
if(localStorage['nofullscreen'] == 'true') $('.fullscreen').hide();
});
This should hide the div with class "fullscreen" on page load, if the storage variable exists and is 'true'.
You'll want to store a cookie on the users machine to know they have visited in the past. You can do so with basic Javascript, like so:
document.cookie="nofullscreen=true";
The line above will create a cookie in local storage, run this once you've scrolled to #page.
function doFullscreen(){
var name = "nofullscreen=";
var cookies = document.cookies.split(';');
cookies.forEach(function(n){
var c = cookies[i].trim();
if(c.indexOf(name)==0) return c.substring(name.length,c.length);
}
return false;
});
The function above can run on page load, it will return True if the user has been here before and you should go right to #page, or false if its a new user and you should display the fullscreen div.
UPDATE: Others have suggested using localStorage, this is also a good idea. here is a small example of that.
Checking for compatibility:
function supports_storage(){
try{
return 'localStorage' in window && window['localStorage'] !== null;
} catch (e) {
return false;
}
}
Writing to storage:
if(supports_storage()) localStorage['sitename.nofullscreen'] = true;
Checking the storage:
if(localStorage['sitename.nofullscreen'] == "true"){
//go right to #page
}
Update #2: PHP Session Storage
You've explained in the comments that your using PHP as well. I feel like either of the above solutions would work just as well, but I'll add some PHP code here for completeness.
First, you'll need to start the session:
<?php session_start() ?>
You are now able to write to the session with PHP like so:
<?php $_SESSION['nofullscreen']='true'; ?>
And check if the session variable is set later with:
<?php if($_SESSION['nofullscreen'] == 'true') { //print css rules to hide #fullscreen here? } ?>
If you need to clear the session variable, you can use unset:
<?php unset($_SESSION['nofullscreen']) ?>
Hope this helps!

Since you mention the requirement 'even if navigated away from the page and went back to it', you need a way to store state.
There are a few options:
sessions
cookies
local storage (might not work on older browsers)
Take your pick :)
In this case I would probably go with session storage

Related

How to Make PopUp Not Showing Again After User Close the Popup [duplicate]

There have already been answers to this question but I am still unsure exactly how it works.
I am using the following HTML in my footer.php:
<div id="popup">
<div>
<div id="popup-close">X</div>
<h2>Content Goes Here</h2>
</div>
</div>
and the following Javascript:
$j(document).ready(function() {
$j("#popup").delay(2000).fadeIn();
$j('#popup-close').click(function(e) // You are clicking the close button
{
$j('#popup').fadeOut(); // Now the pop up is hiden.
});
$j('#popup').click(function(e)
{
$j('#popup').fadeOut();
});
});
Everything works great, but I want to only show the pop up once per user (maybe using the cookie thing all the forum posts go on about) but I do not know exactly how to incorporate it into the JS above.
I know that I will have to load the cookie JS in my footer with this:
<script type="text/javascript" src="scripts/jquery.cookies.2.2.0.min.js"></script>
But that is all I understand, can anyone tell me exactly how the JS/jQuery should look with the cookie stuff added?
Thanks
James
*Note : This will show popup once per browser as the data is stored in browser memory.
Try HTML localStorage.
Methods :
localStorage.getItem('key');
localStorage.setItem('key','value');
$j(document).ready(function() {
if(localStorage.getItem('popState') != 'shown'){
$j('#popup').delay(2000).fadeIn();
localStorage.setItem('popState','shown')
}
$j('#popup-close, #popup').click(function() // You are clicking the close button
{
$j('#popup').fadeOut(); // Now the pop up is hidden.
});
});
Working Demo
This example uses jquery-cookie
Check if the cookie exists and has not expired - if either of those fails, then show the popup and set the cookie (Semi pseudo code):
if($.cookie('popup') != 'seen'){
$.cookie('popup', 'seen', { expires: 365, path: '/' }); // Set it to last a year, for example.
$j("#popup").delay(2000).fadeIn();
$j('#popup-close').click(function(e) // You are clicking the close button
{
$j('#popup').fadeOut(); // Now the pop up is hiden.
});
$j('#popup').click(function(e)
{
$j('#popup').fadeOut();
});
};
You could get around this issue using php. You only echo out the code for the popup on first page load.
The other way... Is to set a cookie which is basically a file that sits in your browser and contains some kind of data. On the first page load you would create a cookie. Then every page after that you check if your cookie is set. If it is set do not display the pop up. However if its not set set the cookie and display the popup.
Pseudo code:
if(cookie_is_not_set) {
show_pop_up;
set_cookie;
}
Offering a quick answer for people using Ionic. I need to show a tooltip only once so I used the $localStorage to achieve this. This is for playing a track, so when they push play, it shows the tooltip once.
$scope.storage = $localStorage; //connects an object to $localstorage
$scope.storage.hasSeenPopup = "false"; // they haven't seen it
$scope.showPopup = function() { // popup to tell people to turn sound on
$scope.data = {}
// An elaborate, custom popup
var myPopup = $ionicPopup.show({
template: '<p class="popuptext">Turn Sound On!</p>',
cssClass: 'popup'
});
$timeout(function() {
myPopup.close(); //close the popup after 3 seconds for some reason
}, 2000);
$scope.storage.hasSeenPopup = "true"; // they've now seen it
};
$scope.playStream = function(show) {
PlayerService.play(show);
$scope.audioObject = audioObject; // this allow for styling the play/pause icons
if ($scope.storage.hasSeenPopup === "false"){ //only show if they haven't seen it.
$scope.showPopup();
}
}
You can use removeItem() class of localStorage to destroy that key on browser close with:
window.onbeforeunload = function{
localStorage.removeItem('your key');
};
The code to show only one time the popup (Bootstrap Modal in the case) :
modal.js
$(document).ready(function() {
if (Cookies('pop') == null) {
$('#ModalIdName').modal('show');
Cookies('pop', '365');
}
});
Here is the full code snipet for Rails :
Add the script above to your js repo (in Rails : app/javascript/packs)
In Rails we have a specific packing way for script, so :
Download the js-cookie plugin (needed to work with Javascript Cokkies) https://github.com/js-cookie/js-cookie (the name should be : 'js.cookie.js')
/*!
* JavaScript Cookie v2.2.0
* https://github.com/js-cookie/js-cookie
*
* Copyright 2006, 2015 Klaus Hartl & Fagner Brack
* Released under the MIT license
*/
;(function (factory) {
var registeredInModuleLoader = false;
if (typeof define === 'function' && define.amd) {
define(factory);
registeredInModul
...
Add //= require js.cookie to application.js
It will works perfectly for 365 days!
You might be using an API for fetching user from database, so use any unique data like id or email or name to identify user then use localstorage method suggested by #Shaunak D. Just replace key with user's unique field and value with popup state.
Like:
ID : popup_state
Sorry for the mistakes in the reply. I am not on my pc today 😅😛

Remembering jquery toggle across site?

I want to be able to hide and unhide a lengthy menu with a button click, and that I have been able to do. But I don't want visitors to have to hide the menu every time they visit a new page, so I would like their last click to be remembered. This I have not been able to do. Any help is appreciated. I am even open to a better way to do this.
The code I thought would work, but doesn't, is:
$(document).ready(function(){
$("button").click(function(){
$("div.themenu").toggle(100);
});
});
$(function(){
if($.cookie){
$("#themenu").toggle(!(!!$.cookie("toggle-state")) || $.cookie("toggle-state") === 'true');
}
$('#menubutton').on('click', function(){
$("#themenu").toggle();
$.cookie("toggle-state", $("#themenu").is(':visible'), {expires: 1, path:'/'});
});
});
The code for the button they click is:
<button id="menubutton" class="myButton">Show / Hide Menu</button>
And the long, long menu is shown like this:
<div class="themenu">Long Long Menu Code</div>
Just for fun: here's an alternative solution which doesn't require a cookie, but sets a URL parameter:
//on page load
if (location.href.match('menu=show'))
$("#themenu").toggle();
//for every link click, block & redirect with menu=show if menu is visible
$(document.body).on('mousedown', 'a', function(e) {
e.preventDefault();
var menuParam = (location.href.match('?') ? '&' : '?') + 'menu=show';
location.href = $("#themenu").is(':visible') ? this.href + menuParam: this.href;
});
localStorage is a good place to store this kind of state. Setting is as easy as localStorage.menu = 'hidden' or localStorage.menu = 'visible', checking can be done with (localStorage && localStorage.menu==='hidden'). People with REALLY old browsers won't get the feature but that's a very small slice of users. This setting will live across visits to the site but only in the same browser. There is an issue with some browsers in 'private browsing' mode. They sometimes make localStorage cause an error when modified.

Scroll to specific area on page load AND perform Ajax Query

Good day folks. I need to figure out how to perform an action using Ajax once I have linked to a specific section on a page. I already know how to get to the designated DOM element on the other page, but I would like to go further as to perform some action using ajax once it has taken the visitor to that point.
eg.
<nav>
<ul><li></li></ul>
</nav>
Will take me to this about.php page to the "team" div
<div>
<div><a name="team"></a></div>
</div>
But then I would like to run some Ajax automatically that would usually be executed when the user clicks on some object in the "team" div. So should the user get to this section by way of the link up above, it will take them straight to the content. Does that make sense?
I'm going to go out on a limb and assume you're using jQuery's animate() for the scrolling:
$('html, body').animate(
{ scrollTop: $("#something").offset().top },
1000,
function() {
someAjaxFunction();
}
);
var someAjaxFunction = function() {
$.ajax({
url: '/something/'
}).done(function(data) {
// Done!
});
};
We're using the callback function argument given to animate() to fire off our ajax request.
You can use jQuery's scrollTo() to scroll to the area on the page, then use the complete function to call you ajax after the scroll has finished.
Detailed Description here
$('body').scrollTo('#target', function()
{
// Do your AJAX Thaaang
});
This check can be run to determine if the user has navigated directly to the teamDiv. Running it on page load would allow you to catch it in the event that the user was deep linked to the teamDiv from another page:
if (/#team/.test(window.location.href)) { // perform Ajax query here... }
Note: In the example link, you use the id team whereas the div's ID attribute is set to teamDiv. They need to be the same for this to work.
So the code would run if the user clicks some object in the "team" div?
In that case, is this an option?
<div>
<div id="teamDiv"><a name="team"></a>some element</div>
</div>
<script type="text/javascript">
$(function() {
$("#teamDiv").click(function() {
//put what you want to happen when the user clicks something in
//teamDiv here
});
})
</script>
My suggestion would be to read the current loaded url:
$(document).ready(function () {
var location = window.location.href;
if(location.indexOf('#team' > -1) {
// do something
}
}
You can check location.hash (http://www.w3schools.com/jsref/prop_loc_hash.asp) to determine if hash existed.
If you want to do something in each variants of navigation to this div: click and scroll you can use something like this:
$(document).bind('scroll', function() {
if($(this).scrollTop() > $('.your-div').top()) {
alert('do something');
}
})

Display A Popup Only Once Per User

There have already been answers to this question but I am still unsure exactly how it works.
I am using the following HTML in my footer.php:
<div id="popup">
<div>
<div id="popup-close">X</div>
<h2>Content Goes Here</h2>
</div>
</div>
and the following Javascript:
$j(document).ready(function() {
$j("#popup").delay(2000).fadeIn();
$j('#popup-close').click(function(e) // You are clicking the close button
{
$j('#popup').fadeOut(); // Now the pop up is hiden.
});
$j('#popup').click(function(e)
{
$j('#popup').fadeOut();
});
});
Everything works great, but I want to only show the pop up once per user (maybe using the cookie thing all the forum posts go on about) but I do not know exactly how to incorporate it into the JS above.
I know that I will have to load the cookie JS in my footer with this:
<script type="text/javascript" src="scripts/jquery.cookies.2.2.0.min.js"></script>
But that is all I understand, can anyone tell me exactly how the JS/jQuery should look with the cookie stuff added?
Thanks
James
*Note : This will show popup once per browser as the data is stored in browser memory.
Try HTML localStorage.
Methods :
localStorage.getItem('key');
localStorage.setItem('key','value');
$j(document).ready(function() {
if(localStorage.getItem('popState') != 'shown'){
$j('#popup').delay(2000).fadeIn();
localStorage.setItem('popState','shown')
}
$j('#popup-close, #popup').click(function() // You are clicking the close button
{
$j('#popup').fadeOut(); // Now the pop up is hidden.
});
});
Working Demo
This example uses jquery-cookie
Check if the cookie exists and has not expired - if either of those fails, then show the popup and set the cookie (Semi pseudo code):
if($.cookie('popup') != 'seen'){
$.cookie('popup', 'seen', { expires: 365, path: '/' }); // Set it to last a year, for example.
$j("#popup").delay(2000).fadeIn();
$j('#popup-close').click(function(e) // You are clicking the close button
{
$j('#popup').fadeOut(); // Now the pop up is hiden.
});
$j('#popup').click(function(e)
{
$j('#popup').fadeOut();
});
};
You could get around this issue using php. You only echo out the code for the popup on first page load.
The other way... Is to set a cookie which is basically a file that sits in your browser and contains some kind of data. On the first page load you would create a cookie. Then every page after that you check if your cookie is set. If it is set do not display the pop up. However if its not set set the cookie and display the popup.
Pseudo code:
if(cookie_is_not_set) {
show_pop_up;
set_cookie;
}
Offering a quick answer for people using Ionic. I need to show a tooltip only once so I used the $localStorage to achieve this. This is for playing a track, so when they push play, it shows the tooltip once.
$scope.storage = $localStorage; //connects an object to $localstorage
$scope.storage.hasSeenPopup = "false"; // they haven't seen it
$scope.showPopup = function() { // popup to tell people to turn sound on
$scope.data = {}
// An elaborate, custom popup
var myPopup = $ionicPopup.show({
template: '<p class="popuptext">Turn Sound On!</p>',
cssClass: 'popup'
});
$timeout(function() {
myPopup.close(); //close the popup after 3 seconds for some reason
}, 2000);
$scope.storage.hasSeenPopup = "true"; // they've now seen it
};
$scope.playStream = function(show) {
PlayerService.play(show);
$scope.audioObject = audioObject; // this allow for styling the play/pause icons
if ($scope.storage.hasSeenPopup === "false"){ //only show if they haven't seen it.
$scope.showPopup();
}
}
You can use removeItem() class of localStorage to destroy that key on browser close with:
window.onbeforeunload = function{
localStorage.removeItem('your key');
};
The code to show only one time the popup (Bootstrap Modal in the case) :
modal.js
$(document).ready(function() {
if (Cookies('pop') == null) {
$('#ModalIdName').modal('show');
Cookies('pop', '365');
}
});
Here is the full code snipet for Rails :
Add the script above to your js repo (in Rails : app/javascript/packs)
In Rails we have a specific packing way for script, so :
Download the js-cookie plugin (needed to work with Javascript Cokkies) https://github.com/js-cookie/js-cookie (the name should be : 'js.cookie.js')
/*!
* JavaScript Cookie v2.2.0
* https://github.com/js-cookie/js-cookie
*
* Copyright 2006, 2015 Klaus Hartl & Fagner Brack
* Released under the MIT license
*/
;(function (factory) {
var registeredInModuleLoader = false;
if (typeof define === 'function' && define.amd) {
define(factory);
registeredInModul
...
Add //= require js.cookie to application.js
It will works perfectly for 365 days!
You might be using an API for fetching user from database, so use any unique data like id or email or name to identify user then use localstorage method suggested by #Shaunak D. Just replace key with user's unique field and value with popup state.
Like:
ID : popup_state
Sorry for the mistakes in the reply. I am not on my pc today 😅😛

javascript variables not setting - checked via firebug

I'm new to stackoverflow!
I'm having problems with a piece of code for my companies website, using jquery. I'm trying to track the clicks on two button and set a variable/s which can then be used to determine a course of action. Basically its a sliding dropdown that animates one way if the variable is set to true and another if it is set to false. I've initiallised the variables both to be false to begin with and then through the course of clicking they should be set to true or false depending on the situation:
var boollogin = false;
var boolregister = false;
$(document).ready(function(){
$('#slidedownlogin').hide();
$('#details_add_area').hide();
$('#emailconfirmation').hide();
$('#register').toggle(function(){
if(boollogin == false){
$('#login_area').hide();
$('#register_area').show();
$('#details_add_area').hide();
$('#slidedownlogin').animate({'height':'235px'},1500, 'easeOutExpo');
}else{
$('#slidedownlogin').animate({'height':'0px'},1500, 'easeOutExpo',function(){
$('#login_area').hide();
$('#details_add_area').hide();
$('#register_area').show();
$('#slidedownlogin').animate({'height':'235px'},1500, 'easeOutExpo');
});
}
boolregister = true;
} , function(){
$('#slidedownlogin').animate({'height':'0px'},1500, 'easeOutExpo', function(){
$('#slidedownlogin').children().hide();
});
boolregister = false;
boollogin = false;
});
$('#login').toggle(function(){
if(boolregister == false){
$('#register_area').hide();
$('#details_add_area').hide();
$('#login_area').show();
$('#slidedownlogin').animate({'height':'220px'},1500, 'easeOutExpo');
}else{
$('#slidedownlogin').animate({'height':'0px'},1500, 'easeOutExpo',function(){
$('#register_area').hide();
$('#details_add_area').hide();
$('#login_area').show();
$('#slidedownlogin').animate({'height':'220px'},1500, 'easeOutExpo');
});
}
boollogin = true;
} , function(){
$('#slidedownlogin').animate({'height':'0px'},1500, 'easeOutExpo', function(){
$('#slidedownlogin').children().hide();
});
boollogin = false;
boolregister= false;
});
});
The page I'm working on is at http://www.premiersoftware.co.uk/index94.php. Full code is in the php file at the moment so you can look at it there too. You should be able to get an idea of what I'm trying to do by clicking the two links (Register and Login) at the top right of the page.These are supposed to reset the variables boollogin or boolregister, but inspecting these two variables in firebug reveals they aren't being reset and don't change. As a result the page initially acts as expected but after a while and a few clicks it gets really quirky. The form valitation and stuff hasn't been done yet as I'm trying to get the animation sorted first.
I was hoping someone here would be able to shed some light on why the variables aren't being reset and suggest how I could fix the code. If there is another way to create the same kind of functionality I'm also open to suggestion.
Thanks in advance
Dan
I think instead of closing the div that drops down and then opening it up again when the user switches between login and register, it may be more intuitive to just display the correct register or login form within the opened div.
This code may help you regardless, but it implements what I suggested above.
http://jsbin.com/etezo5
edit link so you can see the code:
http://jsbin.com/etezo5/edit
have you tried doing something like:
$('Register').appendTo('#support').css({'float':'right','margin-right':'10px'});
$('Login').appendTo('#support').css({'float':'right','margin-right':'10px'});
Then in your JS,
function toggleTheCorrectDiv(toggleRegister){
if (toggleRegister){
//Show Register Content
}else{
//Show Login Content
}
}

Categories