Save dynamic variables on page close - javascript

I'm currently building a website for a school project that loads json data into the page dynamically as the user navigates. Here's the code I'm working with right now:
$(function () {
var $divs = $(".divs > div"),
N = $divs.length,
C = 0; // Current
$divs.hide().eq(C).show();
$("#next, #prev").click(function () {
$divs.stop().fadeOut().eq((this.id == 'next' ? ++C : --C) %N).fadeIn();
}); // close click function
}); // close main function
var content = jSONtexts.texts;
$(document).ready(function () {
$("#content0").html(content[0].content);
$("#content1").html(content[1].content);
$("#content2").html(content[2].content);
$("#content3").html(content[3].content);
$("#content4").html(content[4].content);
$("#content5").html(content[5].content);
$("#content6").html(content[6].content);
$("#content7").html(content[7].content);
$("#content8").html(content[8].content);
});
In my html I have divs set up as containers for the particular json data that I want to be presented. It's rudimentary right now, but the user clicks 'next' or 'previous' and a different section of the json loads into the visible div.
What I need is to be able to save what div is showing (maybe using the 'C' variable?) - into a cookie, and load that div when the user returns. I've tried using js.cookie.js, and it's quite possible that I'm using it wrong, Here's what I'm trying:
$( window ).unload(function() {
Cookies.set('pageState', 'C');
}); //close cookie function
But that doesn't seem to be working. It breaks my json loading when I try to put it anywhere in the .js file that would be relevant to the C variable.
I'm stumped. I've looked everywhere on google, and everything that people are saying to try breaks my json function. Help please!
If someone has any ideas I would be eternally grateful!
Thanks
Sam

Cookie is not a best practice to save these data, as cookies will be send with all requests.
Use need to use HTML5 localStorage to save data at client side.
http://www.w3schools.com/html/html5_webstorage.asp
Made demo for the same
document.getElementById("textInput").value = localStorage.getItem("pageState");
window.addEventListener("unload", function() {
localStorage.setItem("pageState", document.getElementById("textInput").value);
});
<input id="textInput" type="text" />
Demo : http://jsfiddle.net/kishoresahas/vvkdge2q/

as #KishoreSahas already suggested in the comments, I would suggest you to use localStorage instead of cookies.
You could store what you need like this
localStorage.setItem("veryimportantdata", "INeedThisLater");
and get it back later like this
var data = localStorage.getItem("veryimportantdata");
console.log(data); // prints out "INeedThisLater"

Related

Display message for first time viewer only

Im trying to display a welcome message for a few seconds then have it fade out and not return (unless user deletes cookies). I know i can do this 2 ways using either js cookies or localStorage. This is the code i'm using:
$(document).ready(function() {
if(localStorage.getItem('messageState') != 'shown'){
$("#message").delay(2000).fadeOut();
localStorage.setItem('messageState','shown')
}
$('#message').fadeOut();
});
});
But it's not fading out. Any ideas what i'm doing wrong?
Or would i be better using js cookie?
Here's a fiddle: http://jsfiddle.net/Y2D67/1786/
Delete your last line, the }); and the fadeout works.
$(document).ready(function() {
if(localStorage.getItem('messageState') != 'shown'){
$("#message").delay(2000).fadeOut();
localStorage.setItem('messageState','shown')
}
$('#message').fadeOut();
});
Your syntax is wrong, the closing bracket
})
does not belong
Localstorage would be a fine way to store something like this, I usually go by the rule that localstorage is for data I want to read on the front end and cookies are primarily for reading server-side

Save text from a href link threw javascript

I want to store a value to the cache using javascript when clicking an a href link. I'm setting up following code dynamicall
<a align="left" href="projectoverview.html">Test Manager</a>
So I want to save the text Test Manager to the cache, but I don't know how to catch this text when it's clicked. The code below is how that piece of code is setup. Do I need to add an onclick or something or is there a better way?
var text = '<a align=\"left\" href=\"projectoverview.html\">' + project['title']
+ '</a><p align=\"right\">';
If you want to pass data from page to page using javascript/jquery you can do so with sessionStorage. Below is just an example of how you would do it using jQuery.
$('a').each(function() {
$(this).on('click', function() {
var linkText = $(this).text();
// Save data to sessionStorage
sessionStorage.setItem('clickedLink', linkText);
});
});
Then on the next page you can call it by using the .getItem function like so.
$(function() {
var data = sessionStorage.getItem('clickedLink');
alert(data);
});
If implemented correctly the alert box will say "Test Manager".
You can read more about sessionStorage here.
EDIT:
I would add a special class to those links though because the code above will execute on any link you have on the page which may give you unwanted issues.

Sitecore 8 Speak UI - Call Pagecode Javascript from HTMLTemplate link

I am working on ListControl and one of the columns has Delete link which I am formatting using HTMLTemplate as follows:
<a href="javascript: app.showConfirmation()" >Delete</a>
My Javascript looks as follows:
define(["sitecore", function (Sitecore) {
var DestinationRules = Sitecore.Definitions.App.extend({
initialized: function () {
this.processDestinationRules();
},
showConfirmation: function () {
alert('here');
},
});
return DestinationRules;
});
For some reason, I am not able to call showConfirmation(). It says is undefined. I even tried Sitecore.Speak.app.showconfirmation() but not working.
I tried my best to search online but not able to find much help around calling function through controls embedded inside HTMLTemplate.
My next step is to call DialogWindow.
Please if you can help me with the syntax of the above. Thanks in advance.
Fixed it in a different way.
I wanted to show in-line Delete button in each row of the Listcontrol. Could not figure out way to call the
javascript: app.showConfirmation()
I changed the way to delete the record:
Have one Delete button outside the ListControl.
Enable/Disable the Delete button based on binding ListControl.HasSelectedItem.
On click of the Delete button, call showConfirmation()
As of now seems to be a better way. Sitecore itself uses similar approach for "Kicking off" users. Can be found here:
/sitecore/client/Applications/LicenseOptions/KickUser
Hope that helps. Thanks.
Finally, managed to do this. Always knew that it can be done this way but did not like the way its done.
The Delete link in List control opens up a confirmation Dialogue window. And if user selects Yes then it calls the app.onDeleteYes()
The HtmlMarkup for the column:
Delete
Added a button called btnDelete with visibility set to false.
Added following function, outside the scope of App:
var destinationRulePage = (function () {
var self = this;
self.showDeleteDialog = function (id) {
$("button[data-sc-id='btnYes']").attr("data-sc-click",
"javascript:app.onDeleteYes(" + id + ");");
$("button[data-sc-id='btnDelete']").click();
}
return self;
}())
This does the job for me. Thanks.

Call a function only once

I've 3 divs (#Mask #Intro #Container) so if you click on Mask, Intro gets hidden and Container appears.
The problem is that I just want to load this only one time, not every time I refresh the page or anytime I click on the menu or a link, etc.
How can I do this?
This is the script I'm using for now:
$(document).ready(function(){
$("div#mask").click(function() {
$("div#intro").fadeToggle('slow');
$("div#container").fadeToggle('slow');
$("div#mask").css("z-index", "-99");
});
});
Thank you!
You can try using a simple counter.
// count how many times click event is triggered
var eventsFired = 0;
$(document).ready(function(){
$("div#mask").click(function() {
if (eventsFired == 0) {
$("div#intro").fadeToggle('slow');
$("div#container").fadeToggle('slow');
$("div#mask").css("z-index", "-99");
eventsFired++; // <-- now equals 1, won't fire again until reload
}
});
});
To persist this you will need to set a cookie. (e.g. $.cookie() if you use that plugin).
// example using $.cookie plugin
var eventsFired = ($.cookie('eventsFired') != null)
? $.cookie('eventsFired')
: 0;
$(document).ready(function(){
$("div#mask").click(function() {
if (eventsFired == 0) {
$("div#intro").fadeToggle('slow');
$("div#container").fadeToggle('slow');
$("div#mask").css("z-index", "-99");
eventsFired++; // <-- now equals 1, won't fire again until reload
$.cookie('eventsFired', eventsFired);
}
});
});
To delete the cookie later on:
$.cookie('eventsFired', null);
Just point to an empty function once it has been called.
var myFunc = function(){
myFunc = function(){}; // kill it
console.log('Done once!'); // your stuff here
};
Web pages are stateless in that they don't hold states between page refreshes. When you reload the page it has no clue what has happened in the past.
Cookies to the rescue! You can use Javascript (and jQuery has some nice plugins to make it easier) to store variables on the client's browser. Store a cookie when the mask is clicked, so that when the page is next loaded it never shows.
this code with will work perfect for you and it is the standard way provided by jquery to bind events that you want to execute only once
$(document).ready(function(){
$("div#mask").one('click', function() {
$("div#intro").fadeToggle('slow');
$("div#container").fadeToggle('slow');
$("div#mask").css("z-index", "-99");
});
});

Django Admin - RelatedObjectLookups - How Does it refresh and set the select on the parent window?

I want one of my forms to work just like the admin page does so I figured I'd look in the code and see how it works.
Specifically I want the user to be able to click a "+" icon next to a select list and be taken to the admin page's popup form to add a new item.
When they enter a new item there, I want that new item to appear in the select box, and be selected (Just like how this feature works on the admin pages).
I copied the admin js libraries into my own template, and I made my link call the same JS function and the popup windows does open correctly, but after I save a new object the popup window goes blank instead of closing, and nothing happens on the parent page.
Here's what I put in my page:
...
<td>
<div class="fieldWrapper">
<select name="form-0-plasmid" id="id_form-0-plasmid">
...
</select>
<img src="/media/admin/img/admin/icon_addlink.gif" width="10" height="10" alt="Add Another"/>
</div>
</td>
...
I tried stepping through the javascript on the admin form to see how it's working, but I'm not seeing anything that would close the window or populate the parent window's select.
Thanks in advance for any help.
Update 3
I'm getting this javascript error when dismissAddAnotherPopup is run
"SelectBox is not defined"
Which is pointing to this line in dismissAddAnotherPopup
SelectBox.add_to_cache(toId, o);
I thought I knew Javascript, but I don't see where that variable is supposed to come from :-(
Update 2
Everything seems to be firing properly. After I click save on the popup window I get a blank page. This is the source of that page:
<script type="text/javascript">opener.dismissAddAnotherPopup(window, "9", "CMV_flex_myr_GENE1_._._WPRE_BGH");</script>
So it would seem that this javascript isn't being executed or is failing.
Update
Here is the relevant code that Daniel mentioned. So the only problem is that this code either isn't firing, or is firing incorrectly.
django/contrib/admin/options.py:
...
if request.POST.has_key("_popup"):
return HttpResponse('<script type="text/javascript">opener.dismissAddAnotherPopup(window, "%s", "%s");</script>' % \
# escape() calls force_unicode.
(escape(pk_value), escapejs(obj)))
...
/media/admin/js/admin/RelatedObjectLookups.js:
function dismissAddAnotherPopup(win, newId, newRepr) {
// newId and newRepr are expected to have previously been escaped by
// django.utils.html.escape.
newId = html_unescape(newId);
newRepr = html_unescape(newRepr);
var name = windowname_to_id(win.name);
var elem = document.getElementById(name);
if (elem) {
if (elem.nodeName == 'SELECT') {
var o = new Option(newRepr, newId);
elem.options[elem.options.length] = o;
o.selected = true;
} else if (elem.nodeName == 'INPUT') {
if (elem.className.indexOf('vManyToManyRawIdAdminField') != -1 && elem.value) {
elem.value += ',' + newId;
} else {
elem.value = newId;
}
}
} else {
var toId = name + "_to";
elem = document.getElementById(toId);
var o = new Option(newRepr, newId);
SelectBox.add_to_cache(toId, o);
SelectBox.redisplay(toId);
}
win.close();
}
Ok, the javascript simply uses the id attribute of the launching element to identify the select field to update. (after removing 'add_' from the beginig).
So I simply changed the link's id attribute to match the select element's id in my template:
<img src="/media/admin/img/admin/icon_addlink.gif" width="10" height="10" alt="Add Another"/>
Wow I wish this had been documented somewhere! I lost a few hours on this.
(See my updates to the question for more technical details on how it all works.)
The trick - and it's a bit of a hack, actually - is what happens when you click save on the popup in the admin.
If you look at the code of response_add in django.contrib.options.ModelAdmin, you'll see that when you save an item in the popup, the admin returns an HttpResponse consisting solely of a piece of Javascript. This JS calls the dismissAddAnotherPopup function in the parent window, which closes the popup and sets the form value appropriately.
It's fairly simple to copy this functionality into your own app.
Edited after updates If admin javascript doesn't work, it's usually because it has a dependency on the jsi18n code - which you include via a URL (not a static path):
<script type="text/javascript" src="/admin/jsi18n/"></script>
I was having the same problem refreshing the select in the parent window, and I solved following this doc
Everything is working fine now
Edit 1:
I was trying to use Select2 to make the select pretty, the single select works fine, the multiple select is giving me headaches for some reason is not updating the info in the parent form.
Anyone tried this before?

Categories

Resources