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
}
}
Related
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 π
π
I have a pop-over modal that I am loading on my page on load, I would like to make it once it's closed to not show up again for that user. I've done similar things with localStorage(); but for some reason can't figure out the syntax to make this work.
I tried a solution where it sets a class, but on refresh it will reload the original element, so now I am trying this idea where I change the state of of the modal to "visited". Any ideas what I could be missing to get this to work in the same way I'm hoping?
localStorage function:
$(function() {
if (localStorage) {
if (!localStorage.getItem('visited')) {
$('.projects-takeover').show();
}
} else {
$('.projects-takeover').show();
}
$('.projects-close').click(function() {
$('.projects-takeover').fadeOut();
});
localStorage.setItem('visited', true);
return false;
});
Here is a jsfiddle with the code implemented as well, thanks for the help!
You javascript code is correct. Good thing you added a jsfiddle as the problem becomes very easy to identify - the modal's style is set in such a way that it is always visible. Simply change the display property to nonΠ΅ in the .projects-takeover class and it should work. Check out the updated fiddle
Try this ->
$(function() {
var pt = $('.projects-takeover'); //i just hate repeating myself.
if (localStorage) {
if (!localStorage.getItem('visited')) {
pt.show();
} else {
pt.hide(); //this bit was missing
}
} else {
pt.show();
}
$('.projects-close').click(function() {
pt.fadeOut();
});
localStorage.setItem('visited', true);
return false;
});
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 π
π
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
I have an accordion set up to handle registration. I am wanting to validate the data entered on each panel when the user clicks on a different panel tab. I have a continue button on each panel, and am able to validate to my heart's content when the user uses that to go to the next panel.
My problem is that they can also click independently on the accordion tabs (and I want them to be able to skip around for editing purposes), but I would like to validate on those events too.
I've done a bunch of searching, but have not found a satisfactory answer. I am fairly new to Javascript and super-brand-new to jQuery, so please, if you have code snippets for me, be thorough in explaining them.
This should be a straightforward problem (similar to on-click, etc.). I'm quite surprised and frustrated that I haven't found an answer yet.
Edit:
Eric, I couldn't get this to work. Here is my version. I put it in the head section. I have some test code in there that has worked reliably for me in the past (changing the label on one of the tabs). I'm assuming this code has worked for you? Anyway, thanks for your help and I hope we've understood each other sufficiently.
// add capability to detect when accordion tab has been clicked
RegFormAccordion.addEventListener('click', function(e){
var btnElement;
(function findAccordionButton(el){
//e.target is the original element actually clicked on
//the event bubbles up to ancestor/parent nodes which is why you can listen at
//the container
if(!btnElement){ btnElement = e.target; }
else { btnElement = el; }
if(e.target.className !== 'accordionBtn')
{
findAccordionButton(btnElement.parentNode);
}
else
{
var curr_panel_index = RegFormAccordion.getCurrentPanelIndex();
document.getElementById("verify-reg-panel-label").innerHTML = "Index = " + curr_panel_index; // test code to see if it's even getting here
if (curr_panel_index == 1) // contact section
{
ValidateContact();
}
else if (curr_panel_index == 2) // payment section
{
ValidatePayment();
}
UpdateVerifyPanel(); // update contents of verification panel
}
})()
} );
Event delegation.
someAccordianContainer.addEventListener('click', function(e){
var btnElement;
(function findAccordionButton(el){
//e.target is the original element actually clicked on
//the event bubbles up to ancestor/parent nodes which is why you can listen at
//the container
if(!btnElement){ btnElement = e.target; }
else { btnElement = el; }
if(e.target.className !== 'accordionBtn'){
findAccordionButton(btnElement.parentNode);
}
else { doSomething(btnElement); }
})()
} );
You will have to normalize for IE<=8 however if you're supporting older browsers, since it uses a proprietary attachEvent method. Hit quirksmode.org for the details or just use something like jQuery or MooTools.
OK. I found the function that SpryAccordion.js uses to open a new panel and added my own code. Simple and elegant. It's not what I would normally do (usually I leave "libraries" alone). But if you make it editable without giving me another way to take needed control, then the hack is gonna happen.
If I need to use another accordion somewhere else on my website, I will have to double check that I have the correct accordion before invoking the hack. A trade-off I'm willing to make. It works perfectly now. Here is the code:
Spry.Widget.Accordion.prototype.openPanel = function(elementOrIndex)
{
var panelA = this.currentPanel;
var panelB;
if (typeof elementOrIndex == "number")
panelB = this.getPanels()[elementOrIndex];
else
panelB = this.getElement(elementOrIndex);
if (!panelB || panelA == panelB)
return null;
// Start Becca's code
var panelIndex = this.getPanelIndex(panelA);
if (panelIndex == 1) // contact info panel
{
if (ValidateContact())
UpdateVerifyPanel();
else
return null;
}
else if (panelIndex == 2) // payment info panel
{
if (ValidatePayment())
UpdateVerifyPanel();
else
return null;
}
// End Becca's code
var contentA = panelA ? this.getPanelContent(panelA) : null;
var contentB = this.getPanelContent(panelB);
...
...
...
};
Yes, all I wanted was the same control over the panel tabs as I have over my own user-defined buttons, to make sure I could both validate before moving on, and to update my verification screen after any edit the user makes, not just the ones where they happen to hit my continue button. I'm a happy camper. So glad I took a couple of days off.
I hope this helps someone get more control over their own accordions. So glad I don't have to do a crash-course on jQuery when all I want right now is to get my blasted website up.