I've been trying to combine two javascript codes, one that makes other divs close when a new one is opened and one that uses cookies to remember whether a div was opened by a viewer.
As it is now it succeeds in remembering which div was open, but when I click to open the other div, it doesn't close the first div. If I click again to reopen the first div, it closes the second just like it's supposed to, and after that, if I click to open the second div it closes the first div like it's supposed to. And then it works perfectly fine after that. But I can't figure out why it won't close the first div on the initial click.
I'm very new to javascript, so I don't know much about how to manipulate it.
<body>
<script language="javascript">
function setCookie (name, value, expires, path, domain, secure) {
document.cookie = name + "=" + escape(value) +
((expires) ? "; expires=" + expires : "") +
((path) ? "; path=" + path : "") +
((domain) ? "; domain=" + domain : "") +
((secure) ? "; secure" : "");
}
function getCookie (name) {
var cookie = " " + document.cookie;
var search = " " + name + "=";
var setStr = null;
var offset = 0;
var end = 0;
if (cookie.length > 0) {
offset = cookie.indexOf(search);
if (offset != -1) {
offset += search.length;
end = cookie.indexOf(";", offset);
if (end == -1) {
end = cookie.length;
}
setStr = unescape(cookie.substring(offset, end));
}
}
if (setStr == 'false') {
setStr = false;
}
if (setStr == 'true') {
setStr = true;
}
if (setStr == 'null') {
setStr = null;
}
return(setStr);
}
function MyFunction2(divName){
setCookie('bookmark_state', false);
//hidden val
var hiddenVal = document.getElementById("tempDivName");
//hide old
if(hiddenVal.Value != undefined){
var oldDiv = document.getElementById(hiddenVal.Value);
oldDiv.style.display = 'none';
}
//show div
var tempDiv = document.getElementById(divName);
tempDiv.style.display = 'block';
//save div ID
hiddenVal.Value = document.getElementById(divName).getAttribute("id");
}
function MyFunction3(divName){
setCookie('bookmark_state', null);
//hidden val
var hiddenVal = document.getElementById("tempDivName");
//hide old
if(hiddenVal.Value != undefined){
var oldDiv = document.getElementById(hiddenVal.Value);
oldDiv.style.display = 'none';
}
//show div
var tempDiv = document.getElementById(divName);
tempDiv.style.display = 'block';
//save div ID
hiddenVal.Value = document.getElementById(divName).getAttribute("id");
}
function checkBookmark() {
if (getCookie('bookmark_state') == null) {
document.getElementById('bookmark').style.display = 'block';
}
if (getCookie('bookmark_state') == false) {
document.getElementById('bookmark2').style.display = 'block';
}
}
</script>
<input id="tempDivName" type="hidden"/>
<div id="bookmark" style="display:none"><a style="color:black" href="#" OnClick="MyFunction2('bookmark2'); return false;">*</a></div>
<div id="bookmark2" style="display:none"><a style="color:red" href="#" OnClick="MyFunction3('bookmark');">*</a></div>
<script>
checkBookmark();
</script>
</body>
Also, is there a way to use a single cookie to remember which of several divs is open (instead of just two divs)?
Yes, simply store the states of your open divs in an object and serialize it via JSON, e.g.
var states = {
"div1": true, // open
"div2": false // closed
}
setCookie("div_states", JSON.stringify(states));
Related
I have created a notification bar on my site that I don't want to be shown to users again on subsequent visits after they close it the first time. The bar works as expected, but I can't seem to get the cookie to work to not display it again
js
$(document).ready(function(){
$(".m-close").click(function(){
$(".m-bar").hide(600);
});
});
html code
<center>
<div class="m-bar m-red">
<a class="m-microphone"><i class="material-icons" style="font-size:26px;">mic</i></a>
<a class="m-content" style="color: white;">Something Text</a>
<a class="m-close" href="#"><i class="material-icons">close</i></a>
</div>
</center> <br><br>
Here is a code example:
function addCookie(name, value, days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
document.cookie = name + "=" + value + expires + "; path=/";
}
function getCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
// When clicking the close button
addCookie('hidden', 'yes', 30);
// Checks if the user chose to hide the announcement
const isHidden = getCookie('hidden');
if (isHidden == 'yes') {
// Hide the announcement
$(".m-bar").hide(600);
}
else {
// Show the announcement
// ...
}
First you can use the addCookie() function to add a cookie when you close the announcement.
After that when you display the announcement, check if the cookie hidden is set to yes, if it is set to yes then hide the announcement, otherwise show it.
Also of course you can use different names and values and expiration dates for your cookies, I recommend setting a long expiration date.
I donĀ“t choose use a Cookie for this, I will use the localStorage because is a simple notification:
$(window).on('load', function(){
//Create a variable for localStorage return
var confirm = {
notification: false
};
//Get the Data from localStorage
let dataconfirm = localStorage.getItem('confirm');
if(dataconfirm != null){
confirm.notification = dataconfirm;
}
console.log(confirm);
$(document).ready(function(){
$('form').on('click', function(e){
e.preventDefault();
if(!confirm.notification === true){
localStorage.setItem('confirm', true);
}
});
});
});
I need help getting started.
I have a listview webpart on my Wiki page. I would like to highlight the rows of the listview where the modified date is => 90 days old.
Can someone point me to a tutorial or something to get me started?
Conditional Formatting with SharePoint Designer
The type of behavior you're looking for is known as conditional formatting. Ordinarily, you can add conditional formatting to a list view web part by editing the page it's on using SharePoint Designer; conditional formatting is one of the options that will appear in the ribbon menu when you click on the list view web part in SharePoint Designer.
However, you may not be able to edit a wiki page using SharePoint Designer.
A JavaScript-based Alternative
In your case, you may be better off doing something with JavaScript to find the modified field for each row, compare its value to today's date, and apply highlighting as necessary.
One thing you can do is take the code below, copy it into a text file, and save that text file into a library in your SharePoint site. Then add a content editor web part to your wiki page, edit its properties, and set the "content link" property of the web part to point to the URL of the text file. Save the page and get out of edit mode, and you'll see a link to add conditional formatting rules through the browser. This requires you to have access to create lists and list items on the site.
<div id="_conditional_formatting_link" style="display:none; ">
<div unselectable="on" style="display:inline-block; user-select:none; cursor:pointer; padding: 3px; background-color:#9b9b9b; color:white; border:1px solid #888;" onclick="javascript:var rules = document.getElementById('_conditional_formatting'); if(rules.style.display == 'none'){rules.style.display = 'inline-block'}else{rules.style.display = 'none'}">
Conditional Formatting
</div>
</div>
<div id="_conditional_formatting" style="display:none;background-color:#dfdfdf; border: 1px solid black; width:95%; max-width:1100px;">
<a style="border:0px;padding:5px;float:right;" title="Reapply Formatting" href="javascript:getConditions(false);">
<img style="border:0px;" src="/_layouts/images/staticrefresh.gif"/>
</a>
<ol id="_conditional_formatting_rules">
</ol>
<div style="text-align:right; ">
<div id="_add_conditional_formatting_rule" unselectable="on" onclick="javascript: Add_Conditional_Formatting();" style="user-select:none; cursor:pointer; padding: 3px; margin: 3px; display:inline-block; background-color:#9b9b9b; border:1px solid #888; color:white;">Add Rule</div>
</div>
</div>
<script>
function target() { var column; var comparison; var value; var style; var scope; var type; var id; var offset; } /* structure for storing formatting rules */
var conditionalFormattingList = "Conditional Formatting";
function getConditions(reloadRules) {
/* if reloadRules, query the conditions list and get all the rules. Otherwise just reapply the ones in memory to the current document. */
if (typeof (reloadRules) == "undefined") { reloadRules = true; }
if (reloadRules) {
while (document.getElementById("_conditional_formatting_rules").children.length > 0) { /* Clear out the currently displayed list of rules. */
document.getElementById("_conditional_formatting_rules").removeChild(document.getElementById("_conditional_formatting_rules").children[0]);
}
this.clientContext = new SP.ClientContext();
var list = clientContext.get_web().get_lists().getByTitle(conditionalFormattingList);
var camlQuery = new SP.CamlQuery();
var folder = list.get_rootFolder();
camlQuery.set_viewXml('<View><Query><Where><Eq><FieldRef Name=\'URL\' /><Value Type=\'Text\'>' + document.location.pathname + '</Value></Eq></Where><OrderBy><FieldRef Name=\'Priority\' /><FieldRef Name=\'Name\' /></OrderBy></Query></View>');
this.items = list.getItems(camlQuery);
clientContext.load(list, 'EffectiveBasePermissions');
clientContext.load(items);
clientContext.load(folder);
}
this.clientContext.executeQueryAsync(
Function.createDelegate(this,
function () {
/*Get the current user name from the drop-down box*/
var Me = document.querySelector("#RibbonContainer-TabRowRight span[title='Open Menu'] [accesskey='W'] span").innerHTML;
if (reloadRules) {
var baseFormUrl = folder.get_serverRelativeUrl() + "/EditForm.aspx?ID=";
/* Figure out if the current user has access to create or edit items on the Conditional Formatting list */
var perms = list.get_effectiveBasePermissions();
this.hasEdit = perms.has(SP.PermissionKind.editListItems);
this.hasCreate = perms.has(SP.PermissionKind.addListItems);
/* Fill an array with our formatting rules */
this.targets = [];
var itemEnumerator = this.items.getEnumerator();
while (itemEnumerator.moveNext()) {
var item = itemEnumerator.get_current();
var targ = new target();
targ.column = item.get_item("Column");
targ.comparison = item.get_item("Comparison");
targ.style = item.get_item("Style");
targ.scope = item.get_item("Scope");
targ.type = item.get_item("Type");
targ.value = item.get_item("Value"); if (targ.value == null) { targ.value = ""; }
targ.id = item.get_item("ID");
targ.offset = item.get_item("Offset");
targets.push(targ);
}
}
if (!this.hasCreate) { document.getElementById("_add_conditional_formatting_rule").style.display = "none"; }
for (var targetIterator = 0; targetIterator < targets.length; targetIterator++) {
if (reloadRules) {
var rulelist = document.getElementById("_conditional_formatting_rules");
var ruletoadd = document.createElement("li");
var comparisondisplay = targets[targetIterator].type.indexOf("Field") != -1 ? "value of the <b>" + targets[targetIterator].value + "</b> column" : "<b>'" + targets[targetIterator].value + "'</b>";
if (targets[targetIterator].type == "Special" || targets[targetIterator].type == "Number") {
if (targets[targetIterator].value.toString().toLowerCase() == "[me]") { comparisondisplay = "<b>[Me](" + Me + ")</b>"; }
else { comparisondisplay = "<b>" + targets[targetIterator].value + "</b>"; }
}
if (targets[targetIterator].value == "") { comparisondisplay = "<b>(blank)</b>"; }
if (targets[targetIterator].offset != null) {
comparisondisplay += "<b>" + (targets[targetIterator].offset < 0 ? " " : " +") + targets[targetIterator].offset + "</b>"
}
var editLink = this.hasEdit ? "<div style='display:inline-block;cursor:pointer;' onclick='SP.UI.ModalDialog.commonModalDialogOpen(" + '"' + baseFormUrl + targets[targetIterator].id + '&Source=' + document.location.pathname + '"' + ",{},refreshPageConditions); '>" + "<img src='/_layouts/images/EDITITEM.GIF' style='vertical-align:middle;' title='Customize' alt='Customize'/>" + " </div>" : "";
ruletoadd.innerHTML = editLink + "When <b>" + targets[targetIterator].column + "</b> "
+ targets[targetIterator].comparison + " " + comparisondisplay
+ ", apply {" + (targets[targetIterator].style == null ? "remove all formatting" : "<span style='" + targets[targetIterator].style + "'>" + targets[targetIterator].style + "</span>") + "} to the <b>" + targets[targetIterator].scope + "</b>" + ((targets[targetIterator].scope != "Cell" && targets[targetIterator].scope != "Row") ? " column" : "");
rulelist.appendChild(ruletoadd);
}
var tables = document.querySelectorAll("table.ms-listviewtable"); /* Should get all the list view web parts on the page. */
var t_i = 0;
while (t_i < tables.length) {
var columnIndex = null; /* Index of the column to compare against */
var valueIndex = null; /* Index of a second column from which to pull the value to compare */
var styleTargetIndex = null; /* Index of a column to apply formatting to */
var thisTable = tables[t_i];
var headings = thisTable.rows[0].cells;
var h_i = 0;
while (h_i < headings.length) { /* Check all the column headings... */
var thisHeading = headings[h_i].querySelector("div:first-child");
if (thisHeading != null) {
/* In Internet Explorer, the headings have a DisplayName attribute you can grab. If that's not there, just grab the innerText or textContent */
var dispname = thisHeading.DisplayName ? thisHeading.DisplayName : (thisHeading.innerText ? thisHeading.innerText : thisHeading.textContent);
dispname = dispname.replace(/^\s+|\s+$/g, '');/* removes leading and trailing whitespace */
if (targets[targetIterator].scope != "Cell" && targets[targetIterator].scope != "Row") {
/*If the scope isn't Cell or Row, see if this is the cell to which the formatting should applied */
if (dispname == targets[targetIterator].scope) { styleTargetIndex = h_i; }
}
if (targets[targetIterator].type.indexOf("Field") != -1) {
/*If the value type is a Field, check to see if this is the field whose value we care about */
if (dispname == targets[targetIterator].value.toString()) { valueIndex = h_i; }
}
if (dispname == targets[targetIterator].column) { columnIndex = h_i; }
}
h_i += 1;
}
if (columnIndex != null) { /* If we found a matching heading, let's try to apply the rules... */
var rows = thisTable.rows;
for (var i = (rows.length > 0 ? 1 : 0) ; i < rows.length; i++) {
var cells = rows[i].children;
if (cells.length <= columnIndex) { continue }
var innerLink = cells[columnIndex].querySelector("a"); /* I want to specifically target links so that we can change their text color if necessary */
/* Populate valueToEval with the text value of the current cell, or its inner link if it has one */
var valueToEval = cells[columnIndex].innerText ? (innerLink != null ? innerLink.innerText : cells[columnIndex].innerText) : (innerLink != null ? innerLink.textContent : cells[columnIndex].textContent);
if (typeof (valueToEval) == "undefined") { valueToEval = "" } /* Treat empties as blanks */
var listValueToCompareAgainst = null;
if (valueIndex != null) { /* valueIndex only has a value if we need to grab the comparison value from another column on the list */
valueLink = cells[valueIndex].querySelector("a");
listValueToCompareAgainst = cells[valueIndex].innerText ? (valueLink != null ? valueLink.innerText : cells[valueIndex].innerText) : (valueLink != null ? valueLink.textContent : cells[valueIndex].textContent);
}
var needsStyling = false;
switch (targets[targetIterator].type) {
case "Number":
if (!isNaN(Number(valueToEval))) {
valueToEval = Number(valueToEval);
}
if (!isNaN(Number(targets[targetIterator].value))) {
targets[targetIterator].value = Number(targets[targetIterator].value);
}
break;
case "Date":
valueToEval = new Date(valueToEval);
targets[targetIterator].value = new Date(targets[targetIterator].value);
if (targets[targetIterator].offset != null) {
targets[targetIterator].value.setDate(targets[targetIterator].value.getDate() + Number(targets[targetIterator].offset));
}
break;
case "Text": /* Already covered, bro */ break;
case "Date Field":
valueToEval = new Date(valueToEval);
targets[targetIterator].value = new Date(listValueToCompareAgainst);
if (targets[targetIterator].offset != null) {
targets[targetIterator].value.setDate(targets[targetIterator].value.getDate() + Number(targets[targetIterator].offset));
}
break;
case "Text Field": targets[targetIterator].value = listValueToCompareAgainst; break;
case "Number Field":
if (!isNaN(Number(listValueToCompareAgainst))) {
targets[targetIterator].value = listValueToCompareAgainst;
if (targets[targetIterator].offset != null) {
targets[targetIterator].value += Number(targets[targetIterator].offset);
}
}
if (!isNaN(Number(valueToEval))) {
valueToEval = Number(valueToEval);
}
break;
case "Special":
if (targets[targetIterator].value.toLowerCase) {
if (targets[targetIterator].value.toLowerCase() == "[me]") { targets[targetIterator].value = Me }
else if (targets[targetIterator].value.toLowerCase().indexOf("[today]") != -1) {
var dateDifference = Number(targets[targetIterator].value.toLowerCase().replace("[today]", "").replace(" ", "").replace("+", ""));
targets[targetIterator].value = new Date();
if (!isNaN(dateDifference)) { targets[targetIterator].value.setDate(targets[targetIterator].value.getDate() + dateDifference); }
if (targets[targetIterator].offset != null) {
targets[targetIterator].value.setDate(targets[targetIterator].value.getDate() + Number(targets[targetIterator].offset));
}
valueToEval = new Date(valueToEval);
}
} else { valueToEval = new Date(valueToEval); }
break;
}
switch (targets[targetIterator].comparison) {
case "Greater Than or Equal To": needsStyling = (valueToEval >= targets[targetIterator].value); break;
case "Greater Than": needsStyling = (valueToEval > targets[targetIterator].value); break;
case "Less Than or Equal To": needsStyling = (valueToEval <= targets[targetIterator].value); break;
case "Less Than": needsStyling = (valueToEval < targets[targetIterator].value); break;
case "Equal To": needsStyling = (valueToEval == targets[targetIterator].value); break;
case "Not Equal To": needsStyling = (valueToEval != targets[targetIterator].value); break;
case "Contains": needsStyling = (valueToEval.indexOf(targets[targetIterator].value) != -1); break;
case "Does Not Contain": needsStyling = (valueToEval.indexOf(targets[targetIterator].value) == -1); break;
}
if (needsStyling) {
var links;
if (targets[targetIterator].scope != "Row") {
var targetIndex = (styleTargetIndex != null) ? styleTargetIndex : columnIndex;
cells[targetIndex].setAttribute("style", targets[targetIterator].style);
links = cells[targetIndex].querySelectorAll("a");
} else {
rows[i].setAttribute("style", targets[targetIterator].style);
for (var j = 0; j < cells.length; j++) {
cells[j].setAttribute("style", targets[targetIterator].style);
}
links = rows[i].querySelectorAll("a");
}
for (var j = 0; j < links.length; j++) {
if (links[j].title != "Open Menu") {
links[j].setAttribute("style", targets[targetIterator].style);
links[j].style.backgroundColor = "";
}
links[j].style.border = "0px";
}
}
}
}
t_i += 1;
}
}
document.getElementById("_conditional_formatting_link").style.display = "inline-block";
}
),
Function.createDelegate(this,
function (sender, args) { /* There was an error accessing the list. Time to create it! */
var lci = new SP.ListCreationInformation();
lci.set_title(conditionalFormattingList);
lci.set_templateType(SP.ListTemplateType.genericList);
var condition_list = clientContext.get_web().get_lists().add(lci);
clientContext.load(condition_list);
/* Drop the Title field */
var colTitle = condition_list.get_fields().getByTitle("Title");
colTitle.set_required(false);
colTitle.set_hidden(true);
colTitle.update();
condition_list.update();
/* Add New Fields */
var colColumn = condition_list.get_fields().addFieldAsXml('<Field Description=\'The column to compare (must be visible on the page)\' DisplayName=\'Column\' Type=\'Text\'/>', true, SP.AddFieldOptions.defaultValue);
var colComparison = condition_list.get_fields().addFieldAsXml('<Field Description=\'\' Type=\'Choice\' DisplayName=\'Comparison\' Format=\'Dropdown\' FillInChoice=\'FALSE\'><Default>Equal To</Default><CHOICES><CHOICE>Greater Than</CHOICE><CHOICE>Greater Than or Equal To</CHOICE><CHOICE>Equal To</CHOICE><CHOICE>Less Than or Equal To</CHOICE><CHOICE>Less Than</CHOICE><CHOICE>Not Equal To</CHOICE><CHOICE>Contains</CHOICE><CHOICE>Does Not Contain</CHOICE></CHOICES></Field>', true, SP.AddFieldOptions.defaultValue);
var colValue = condition_list.get_fields().addFieldAsXml('<Field Description=\'The value or the name of a column to compare against\' DisplayName=\'Value\' Type=\'Text\'/>', true, SP.AddFieldOptions.defaultValue);
var colType = condition_list.get_fields().addFieldAsXml('<Field Description=\'Indicate the type of value you are comparing against. Choose Special if using the [Me] or [Today] placeholders.\' Type=\'Choice\' DisplayName=\'Type\' Format=\'Dropdown\' FillInChoice=\'FALSE\'><Default>Text</Default><CHOICES><CHOICE>Date</CHOICE><CHOICE>Number</CHOICE><CHOICE>Text</CHOICE><CHOICE>Date Field</CHOICE><CHOICE>Number Field</CHOICE><CHOICE>Text Field</CHOICE><CHOICE>Special</CHOICE></CHOICES></Field>');
var colOffset = condition_list.get_fields().addFieldAsXml('<Field Description=\'Optionally specify a number to offset the value by when comparing against a number or date.\' DisplayName=\'Offset\' Type=\'Number\' />', true, SP.AddFieldOptions.defaultValue);
var colStyle = condition_list.get_fields().addFieldAsXml('<Field NumLines=\'4\' Description=\'The CSS to apply to when the condition is met. Leave blank to remove formatting. Example syntax: background-color:darkred; color:white; font-weight:bold;\' DisplayName=\'Style\' Type=\'Note\' />', true, SP.AddFieldOptions.defaultValue);
var colScope = condition_list.get_fields().addFieldAsXml('<Field Description=\'The scope to which the style should be applied. Choose Row, Cell, or specify a column name.\' Type=\'Choice\' DisplayName=\'Scope\' Format=\'Dropdown\' FillInChoice=\'TRUE\'><Default>Cell</Default><CHOICES><CHOICE>Cell</CHOICE><CHOICE>Row</CHOICE></CHOICES></Field>', true, SP.AddFieldOptions.defaultValue);
var colPriority = condition_list.get_fields().addFieldAsXml('<Field Description=\'Priority determines which styles are applied in case of overlapping conditions. Higher numbers are applied later.\' DisplayName=\'Priority\' Type=\'Number\' />', true, SP.AddFieldOptions.defaultValue);
var colUrl = condition_list.get_fields().addFieldAsXml('<Field Description=\'Page where this rule should be applied\' DisplayName=\'URL\' Type=\'Text\'/>', true, SP.AddFieldOptions.defaultValue);
clientContext.executeQueryAsync(
Function.createDelegate(this, function () { getConditions(); }),
Function.createDelegate(this, function (sender, args) { document.getElementById("_conditional_formatting").innerHTML = ("An error occcurred while trying to apply conditional formatting to the list for you. Error details: " + args.get_message() + " " + args.get_stackTrace()); document.getElementById("_conditional_formatting_link").style.display = "inline-block"; }));
}
));
}
/* This method is called when the Add Rule button is clicked. */
function Add_Conditional_Formatting() {
/* Create a new item with only the URL and Priority fields filled out */
var currUrl = document.location.pathname;
var clientContext = new SP.ClientContext();
var itemCreateInfo = new SP.ListItemCreationInformation();
var newItem = clientContext.get_web().get_lists().getByTitle(conditionalFormattingList).addItem(itemCreateInfo);
newItem.set_item('URL', currUrl);
/* Give the new item a priority that will put it at the end of the list. This is kind of a hack since the highest priority is not necessarily the rulecount. */
newItem.set_item('Priority', document.getElementById("_conditional_formatting_rules").children.length + 1);
newItem.update();
clientContext.load(newItem);
clientContext.executeQueryAsync(Function.createDelegate(this, function () {
getConditions(); /* Reload to refresh the rules list after adding the item */
}), Function.createDelegate(this, function (sender, args) { alert(args.get_message()); }));
}
/* This method is called when the Edit Item dialog box is closed. It refreshes the page it the item was saved. */
function refreshPageConditions(result) { if (result != SP.UI.DialogResult.cancel) { window.location.replace(document.location.href) } }
ExecuteOrDelayUntilScriptLoaded(function () {
getConditions();
/* If there are any collapsible sections on the page, keep checking to see whether formatting needs to be reapplied */
this.TableRowCount = 0;
if (document.querySelector("img[alt='expand']") != null) {
setInterval(function () {
var tempTableRowCount = document.querySelectorAll("tr").length;
if (tempTableRowCount != this.TableRowCount) {
/* Only reapply formatting if the count of table rows is different than it was previously */
this.TableRowCount = tempTableRowCount;
getConditions(false) /* Passing false reapplies loaded rules without re-querying the SharePoint list */
}
}, 1000)
}
}, "SP.JS");
</script>
You would then want to add a rule that looks like this:
That script handles the nitty gritty tasks of creating a list of conditional formatting rules, checking those rules against list view web parts on the page, and applying them when the page loads. So all you need to do then is add the rules!
I need to add cookies so that when one div is open (showing) and the user clicks refresh it remmber the the last state.
I know it should be easy but im a total noob at js script and have been scrathing more than my head over this one. Any help would be more than appreciated. I have looked though different examples on this forum but they are complectaed and not clear. Looking for a simple solution to a simple bit of code. Thank you!
<script type="text/JavaScript">
$(document).ready(function(){
$('a.row_view').click(function() {
$('.contentPadd.r_view').css('display', 'block');
$('.contentPadd.l_view').css('display', 'none')
$('.contentPadd.t_view').css('display', 'none');
});
$('a.list_view').click(function() {
$('.contentPadd.r_view').css('display', 'none') //horizontal
$('.contentPadd.l_view').css('display', 'block') //list
$('.contentPadd.t_view').css('display', 'none') //thumbnails
});
$('a.table_view').click(function() {
$('.contentPadd.r_view').css('display', 'none')
$('.contentPadd.l_view').css('display', 'none')
$('.contentPadd.t_view').css('display', 'block')
});
});
</script>
<a class="row_view">1</a> <a class="list_view">2</a> <a class="table_view">3</a>
<div class="contentPadd r_view">NUMBER 1</div>
<div class="contentPadd t_view">NUMBER 2</div>
<div class="contentPadd l_view">NUMBER 3</div>
I wrote a cookie handler that you can find here: http://forrst.com/posts/JavaScript_cookie_handler-JE9
To use it, create a new instance of the Ovenmitts object. Then, pass in two parameters to the bakeCookie method: name and value. Within your click function, do the following:
$('a.row_view').click(function() {
var cookieObj = new Ovenmitts();
cookieObj.bakeCookie('opened', 'a.row_view');
$('.contentPadd.r_view').css('display', 'block');
$('.contentPadd.l_view').css('display', 'none')
$('.contentPadd.t_view').css('display', 'none');
});
Then, on page load, call the admireCookie method:
$(document).ready(function() {
var cookieObj = new Ovenmitts();
var cookie = cookieObj.admireCookie('opened');
if (cookie === 'a.row_view') {
$('.contentPadd.r_view').css('display', 'block');
$('.contentPadd.l_view').css('display', 'none')
$('.contentPadd.t_view').css('display', 'none');
}
});
Let me know if you have any issues implementing this.
Also, instead of .css('display', 'block') and .css('display', 'none') you can use the jQuery .show() and .hide() functions.
You can overwrite the cookie by calling the bakeCookie method and passing in the same name (e.g. 'opened'). That way, you can pass in a value to it to remember which drawer is open.
Thanks to Nick.
create or add this to your .js file:
//cookie handler for listing layouts // to instantiate a new object,
create a variable and call the new operator // e.g. var myCookie = new
Ovenmitts(); // then you can access the methods of Ovenmitts through
myCookie.bakeCookie(), etc. var Ovenmitts = function() { var ctx =
this; // create a cookie // accepts 3 parameters: name, value,
days // cookie takes a key / value pair for name / value, expires /
days // days is optional, defaults to session end ctx.bakeCookie =
function(name, value, days) {
if ( days ) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
} else { var expires = ""; }
return document.cookie = name + "=" + value + expires + "; path=/"; }; // reads a cookie // accepts the name parameter (
first value in the cookie ) ctx.admireCookie = function(name) {
var nameEQ = name + '=';
var ca = document.cookie.split(';');
for ( var i = 0; i < ca.length; i += 1 ) {
var c = ca[i];
while (c.charAt(0) === ' ' ) { c = c.substring(1, c.length); }
if ( c.indexOf(nameEQ) === 0 ) { return c.substring(nameEQ.length, c.length); }
}
return null; }; }; //end of cookie handler.
$(document).ready(function(){ //Product listing layout div switch
$('a.row_view').click(function() { var cookieObj = new
Ovenmitts();
cookieObj.bakeCookie('opened', 'a.row_view');
$('.contentPadd.r_view').show();
$('.contentPadd.l_view').hide();
$('.contentPadd.t_view').hide(); });
$('a.list_view').click(function() { var cookieObj = new
Ovenmitts();
cookieObj.bakeCookie('opened', 'a.list_view'); $('.contentPadd.r_view').hide();//horizontal
$('.contentPadd.l_view').show(); //list
$('.contentPadd.t_view').hide(); //thumbnails });
$('a.table_view').click(function() { var cookieObj = new
Ovenmitts();
cookieObj.bakeCookie('opened', 'a.table_view'); $('.contentPadd.r_view').hide(); $('.contentPadd.l_view').hide();
$('.contentPadd.t_view').show(); }); var cookieObj = new
Ovenmitts(); var cookie = cookieObj.admireCookie('opened'); if
(cookie === 'a.row_view') {
$('.contentPadd.r_view').show();
$('.contentPadd.l_view').hide();
$('.contentPadd.t_view').hide(); } var cookieObj = new Ovenmitts(); var cookie = cookieObj.admireCookie('opened'); if
(cookie === 'a.list_view') {
$('.contentPadd.r_view').hide();//horizontal
$('.contentPadd.l_view').show(); //list
$('.contentPadd.t_view').hide(); //thumbnails }
var cookieObj = new Ovenmitts(); var cookie = cookieObj.admireCookie('opened'); if (cookie === 'a.table_view') {
$('.contentPadd.r_view').hide(); $('.contentPadd.l_view').hide();
$('.contentPadd.t_view').show(); } //END Product listing layout
div switch
added this to my test.html page. Also add the js file:
<script language="javascript" src="YOURJSFILE.js"></script>
<script language="javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js.js"></script>
<a class="row_view">TEST 1</a>
<a class="list_view">TEST 2</a>
<a class="table_view">TEST 3</a>
added this to to my test.html page
<div class="contentPadd r_view">TEST 1</div>
<div class="contentPadd t_view">TEST 2</div>
<div class="contentPadd l_view">TEST 3</div>
THATS IT. - ADD TO PHP -ADD IMAGES - EXPAND - Etc.
How do I refresh the page using Javascript without the page returning to
the top.
My page refreshes using a timer but the problem is it goes back to the top every time it reloads. It should be able to retain the current position of the page as it reloads.
P.S.
Additional mouse events are welcome if necessary to be a part of your suggestion.
I'm actually thinking of #idname to target on refresh but my HTML elements don't have IDs, only classes.
If you use JavaScript, this code will do the trick.
var cookieName = "page_scroll";
var expdays = 365;
// An adaptation of Dorcht's cookie functions.
function setCookie(name, value, expires, path, domain, secure) {
if (!expires) expires = new Date();
document.cookie = name + "=" + escape(value) +
((expires == null) ? "" : "; expires=" + expires.toGMTString()) +
((path == null) ? "" : "; path=" + path) +
((domain == null) ? "" : "; domain=" + domain) +
((secure == null) ? "" : "; secure");
}
function getCookie(name) {
var arg = name + "=";
var alen = arg.length;
var clen = document.cookie.length;
var i = 0;
while (i < clen) {
var j = i + alen;
if (document.cookie.substring(i, j) == arg) {
return getCookieVal(j);
}
i = document.cookie.indexOf(" ", i) + 1;
if (i == 0) break;
}
return null;
}
function getCookieVal(offset) {
var endstr = document.cookie.indexOf(";", offset);
if (endstr == -1) endstr = document.cookie.length;
return unescape(document.cookie.substring(offset, endstr));
}
function deleteCookie(name, path, domain) {
document.cookie = name + "=" +
((path == null) ? "" : "; path=" + path) +
((domain == null) ? "" : "; domain=" + domain) +
"; expires=Thu, 01-Jan-00 00:00:01 GMT";
}
function saveScroll() {
var expdate = new Date();
expdate.setTime(expdate.getTime() + (expdays*24*60*60*1000)); // expiry date
var x = document.pageXOffset || document.body.scrollLeft;
var y = document.pageYOffset || document.body.scrollTop;
var data = x + "_" + y;
setCookie(cookieName, data, expdate);
}
function loadScroll() {
var inf = getCookie(cookieName);
if (!inf) { return; }
var ar = inf.split("_");
if (ar.length == 2) {
window.scrollTo(parseInt(ar[0]), parseInt(ar[1]));
}
}
This works by using a cookie to remember the scroll position.
Now just add
onload="loadScroll()" onunload="saveScroll()"
to your body tag and all will be well.
Source(s): http://www.huntingground.freeserve.co.uk/main/mainfram.htm?../scripts/cookies/scrollpos.htm
If there is a certain set of specific sections of the page that are possible initial "scroll to" points, then you can assign those sections CSS ids and refresh the page with an appended ID hash at the end. For example, window.location = http://example.com#section2 will reload the page and automatically scroll it down to the element with the id "section2".
If it's not that specific, you can grab the current scroll position prior to refresh using jQuery's .scrollTop() method on the window: $(window).scrollTop(). You can then append this to the refresh URL, and include JS on the page that checks for this in order to automatically scroll to the correct position upon page load:
Grab current scroll position
var currentScroll = $(window).scrollTop();
window.location = 'http://example.com#' + currentScroll;
JS that must run when DOM is ready in order to check for a currentScroll hash
$(function(){
if(window.location.hash !== ''){
var scrollPos = parseInt(window.location.hash.substring(1),10);
$(window).scrollTo(scrollPos);
}
});
If you don't like the idea of modifying the URL in the address bar (because you really want to hide what you're doing from the user for some reason), you could store the scrollTo() value in a cookie instead of the URL.
You can do it using a cookie based method:
<html>
<head>
<script type="text/javascript">
var refreshPeriod = 120; // 120 Seconds
function refresh()
{
document.cookie = 'scrollTop=' + filterScrollTop();
document.cookie = 'scrollLeft=' + filterScrollLeft();
document.location.reload(true);
}
function getCookie(name)
{
var start = document.cookie.indexOf(name + "=");
var len = start + name.length + 1;
if(((!start) && (name != document.cookie.substring(0, name.length))) || start == -1)
return null;
var end = document.cookie.indexOf(";", len);
if(end == -1)
end = document.cookie.length;
return unescape(document.cookie.substring(len, end));
}
function deleteCookie(name)
{
document.cookie = name + "=" + ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}
function setupRefresh()
{
var scrollTop = getCookie("scrollTop");
var scrollLeft = getCookie("scrollLeft");
if (!isNaN(scrollTop))
{
document.body.scrollTop = scrollTop;
document.documentElement.scrollTop = scrollTop;
}
if (!isNaN(scrollLeft))
{
document.body.scrollLeft = scrollLeft;
document.documentElement.scrollLeft = scrollLeft;
}
deleteCookie("scrollTop");
deleteCookie("scrollLeft");
setTimeout("refresh()", refreshPeriod * 1000);
}
function filterResults(win, docEl, body)
{
var result = win ? win : 0;
if (docEl && (!result || (result > docEl)))
result = docEl;
return body && (!result || (result > body)) ? body : result;
}
// Setting the cookie for vertical position
function filterScrollTop()
{
var win = window.pageYOffset ? window.pageYOffset : 0;
var docEl = document.documentElement ? document.documentElement.scrollTop : 0;
var body = document.body ? document.body.scrollTop : 0;
return filterResults(win, docEl, body);
}
// Setting the cookie for horizontal position
function filterScrollLeft()
{
var win = window.pageXOffset ? window.pageXOffset : 0;
var docEl = document.documentElement ? document.documentElement.scrollLeft : 0;
var body = document.body ? document.body.scrollLeft : 0;
return filterResults(win, docEl, body);
}
</script>
</head>
<body onload="setupRefresh()">
<!-- content here -->
</body>
</html>
or you can do it with a form method:
<html>
<head>
<script type="text/javascript">
// Saves scroll position
function scroll(value)
{
var hidScroll = document.getElementById('hidScroll');
hidScroll.value = value.scrollTop;
}
// Moves scroll position to saved value
function scrollMove(el)
{
var hidScroll = document.getElementById('hidScroll');
document.getElementById(el).scrollTop = hidScroll.value;
}
</script>
</head>
<body onload="scrollMove('divScroll');" onunload="document.forms(0).submit()";>
<form>
<input type="text" id="hidScroll" name="a"><br />
<div id="divScroll" onscroll="scroll(this);"
style="overflow:auto;height:100px;width:100px;">
<!-- content here -->
</div>
</form>
</body>
</html>
Just depends on your application's requirements and restrictions.
I would recommend refreshing only the part of the page you are interested in changing, using ajax. I mean, just replacing the content using javascript depending on the response of the ajax call. I would say you take a look at jQuery's ajax or get methods.
If you can give more information about what you are trying to do maybe I can be of more assistance. Anyway, I hope this helps a little bit.
Cheers!
I'm attempting to use a jQuery script I've found on
http://swip.codylindley.com/DOMWindowDemo.html
on my website to create a lightbox/domwindow popup when a visitor clicks a link.
Unfortunately, it appears the script isn't releasing memory when the user closes the dom window. If the user opens and closes the window several times, it causes the page to slow down dramatically and crash the user's browser.
Here is the jQuery script from the above website:
(function($){
//closeDOMWindow
$.fn.closeDOMWindow = function(settings){
if(!settings){settings={};}
var run = function(passingThis){
if(settings.anchoredClassName){
var $anchorClassName = $('.'+settings.anchoredClassName);
$anchorClassName.fadeOut('fast',function(){
if($.fn.draggable){
$anchorClassName.draggable('destory').trigger("unload").remove();
}else{
$anchorClassName.trigger("unload").remove();
}
});
if(settings.functionCallOnClose) {
settings.functionCallAfterClose();
}
}else{
var $DOMWindowOverlay = $('#DOMWindowOverlay');
var $DOMWindow = $('#DOMWindow');
$DOMWindowOverlay.fadeOut('fast',function(){
$DOMWindowOverlay.trigger('unload').unbind().remove();
});
$DOMWindow.fadeOut('fast',function(){
if($.fn.draggable){
$DOMWindow.draggable("destroy").trigger("unload").remove();
}else{
$DOMWindow.trigger("unload").remove();
}
});
$(window).unbind('scroll.DOMWindow');
$(window).unbind('resize.DOMWindow');
if($.fn.openDOMWindow.isIE6){$('#DOMWindowIE6FixIframe').remove();}
if(settings.functionCallOnClose){settings.functionCallAfterClose();}
}
};
if(settings.eventType){//if used with $().
return this.each(function(index){
$(this).bind(settings.eventType, function(){
run(this);
return false;
});
});
}else{//else called as $.function
run();
}
};
//allow for public call, pass settings
$.closeDOMWindow = function(s){$.fn.closeDOMWindow(s);};
//openDOMWindow
$.fn.openDOMWindow = function(instanceSettings){
var shortcut = $.fn.openDOMWindow;
//default settings combined with callerSettings////////////////////////////////////////////////////////////////////////
shortcut.defaultsSettings = {
anchoredClassName:'',
anchoredSelector:'',
borderColor:'#ccc',
borderSize:'4',
draggable:0,
eventType:null, //click, blur, change, dblclick, error, focus, load, mousedown, mouseout, mouseup etc...
fixedWindowY:100,
functionCallOnOpen:null,
functionCallOnClose:null,
height:500,
loader:0,
loaderHeight:0,
loaderImagePath:'',
loaderWidth:0,
modal:0,
overlay:1,
overlayColor:'#000',
overlayOpacity:'85',
positionLeft:0,
positionTop:0,
positionType:'centered', // centered, anchored, absolute, fixed
width:500,
windowBGColor:'#fff',
windowBGImage:null, // http path
windowHTTPType:'get',
windowPadding:10,
windowSource:'inline', //inline, ajax, iframe
windowSourceID:'',
windowSourceURL:'',
windowSourceAttrURL:'href'
};
var settings = $.extend({}, $.fn.openDOMWindow.defaultsSettings , instanceSettings || {});
//Public functions
shortcut.viewPortHeight = function(){ return self.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;};
shortcut.viewPortWidth = function(){ return self.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;};
shortcut.scrollOffsetHeight = function(){ return self.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;};
shortcut.scrollOffsetWidth = function(){ return self.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft;};
shortcut.isIE6 = typeof document.body.style.maxHeight === "undefined";
//Private Functions/////////////////////////////////////////////////////////////////////////////////////////////////////////
var sizeOverlay = function(){
var $DOMWindowOverlay = $('#DOMWindowOverlay');
if(shortcut.isIE6){//if IE 6
var overlayViewportHeight = document.documentElement.offsetHeight + document.documentElement.scrollTop - 4;
var overlayViewportWidth = document.documentElement.offsetWidth - 21;
$DOMWindowOverlay.css({'height':overlayViewportHeight +'px','width':overlayViewportWidth+'px'});
}else{//else Firefox, safari, opera, IE 7+
$DOMWindowOverlay.css({'height':'100%','width':'100%','position':'fixed'});
}
};
var sizeIE6Iframe = function(){
var overlayViewportHeight = document.documentElement.offsetHeight + document.documentElement.scrollTop - 4;
var overlayViewportWidth = document.documentElement.offsetWidth - 21;
$('#DOMWindowIE6FixIframe').css({'height':overlayViewportHeight +'px','width':overlayViewportWidth+'px'});
};
var centerDOMWindow = function() {
var $DOMWindow = $('#DOMWindow');
if(settings.height + 50 > shortcut.viewPortHeight()){//added 50 to be safe
$DOMWindow.css('left',Math.round(shortcut.viewPortWidth()/2) + shortcut.scrollOffsetWidth() - Math.round(($DOMWindow.outerWidth())/2));
}else{
$DOMWindow.css('left',Math.round(shortcut.viewPortWidth()/2) + shortcut.scrollOffsetWidth() - Math.round(($DOMWindow.outerWidth())/2));
$DOMWindow.css('top',Math.round(shortcut.viewPortHeight()/2) + shortcut.scrollOffsetHeight() - Math.round(($DOMWindow.outerHeight())/2));
}
};
var centerLoader = function() {
var $DOMWindowLoader = $('#DOMWindowLoader');
if(shortcut.isIE6){//if IE 6
$DOMWindowLoader.css({'left':Math.round(shortcut.viewPortWidth()/2) + shortcut.scrollOffsetWidth() - Math.round(($DOMWindowLoader.innerWidth())/2),'position':'absolute'});
$DOMWindowLoader.css({'top':Math.round(shortcut.viewPortHeight()/2) + shortcut.scrollOffsetHeight() - Math.round(($DOMWindowLoader.innerHeight())/2),'position':'absolute'});
}else{
$DOMWindowLoader.css({'left':'50%','top':'50%','position':'fixed'});
}
};
var fixedDOMWindow = function(){
var $DOMWindow = $('#DOMWindow');
$DOMWindow.css('left', settings.positionLeft + shortcut.scrollOffsetWidth());
$DOMWindow.css('top', + settings.positionTop + shortcut.scrollOffsetHeight());
};
var showDOMWindow = function(instance){
if(arguments[0]){
$('.'+instance+' #DOMWindowLoader').remove();
$('.'+instance+' #DOMWindowContent').fadeIn('fast',function(){if(settings.functionCallOnOpen){settings.functionCallOnOpen();}});
$('.'+instance+ '.closeDOMWindow').click(function(){
$.closeDOMWindow();
return false;
});
}else{
$('#DOMWindowLoader').remove();
$('#DOMWindow').fadeIn('fast',function(){if(settings.functionCallOnOpen){settings.functionCallOnOpen();}});
$('#DOMWindow .closeDOMWindow').click(function(){
$.closeDOMWindow();
return false;
});
}
};
var urlQueryToObject = function(s){
var query = {};
s.replace(/b([^&=]*)=([^&=]*)b/g, function (m, a, d) {
if (typeof query[a] != 'undefined') {
query[a] += ',' + d;
} else {
query[a] = d;
}
});
return query;
};
//Run Routine ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
var run = function(passingThis){
//get values from element clicked, or assume its passed as an option
settings.windowSourceID = $(passingThis).attr('href') || settings.windowSourceID;
settings.windowSourceURL = $(passingThis).attr(settings.windowSourceAttrURL) || settings.windowSourceURL;
settings.windowBGImage = settings.windowBGImage ? 'background-image:url('+settings.windowBGImage+')' : '';
var urlOnly, urlQueryObject;
if(settings.positionType == 'anchored'){//anchored DOM window
var anchoredPositions = $(settings.anchoredSelector).position();
var anchoredPositionX = anchoredPositions.left + settings.positionLeft;
var anchoredPositionY = anchoredPositions.top + settings.positionTop;
$('body').append('<div class="'+settings.anchoredClassName+'" style="'+settings.windowBGImage+';background-repeat:no-repeat;padding:'+settings.windowPadding+'px;overflow:auto;position:absolute;top:'+anchoredPositionY+'px;left:'+anchoredPositionX+'px;height:'+settings.height+'px;width:'+settings.width+'px;background-color:'+settings.windowBGColor+';border:'+settings.borderSize+'px solid '+settings.borderColor+';z-index:10001"><div id="DOMWindowContent" style="display:none"></div></div>');
//loader
if(settings.loader && settings.loaderImagePath !== ''){
$('.'+settings.anchoredClassName).append('<div id="DOMWindowLoader" style="width:'+settings.loaderWidth+'px;height:'+settings.loaderHeight+'px;"><img src="'+settings.loaderImagePath+'" /></div>');
}
if($.fn.draggable){
if(settings.draggable){$('.' + settings.anchoredClassName).draggable({cursor:'move'});}
}
switch(settings.windowSource){
case 'inline'://////////////////////////////// inline //////////////////////////////////////////
$('.' + settings.anchoredClassName+" #DOMWindowContent").append($(settings.windowSourceID).children());
$('.' + settings.anchoredClassName).unload(function(){// move elements back when you're finished
$('.' + settings.windowSourceID).append( $('.' + settings.anchoredClassName+" #DOMWindowContent").children());
});
showDOMWindow(settings.anchoredClassName);
break;
case 'iframe'://////////////////////////////// iframe //////////////////////////////////////////
$('.' + settings.anchoredClassName+" #DOMWindowContent").append('<iframe frameborder="0" hspace="0" wspace="0" src="'+settings.windowSourceURL+'" name="DOMWindowIframe'+Math.round(Math.random()*1000)+'" style="width:100%;height:100%;border:none;background-color:#fff;" class="'+settings.anchoredClassName+'Iframe" ></iframe>');
$('.'+settings.anchoredClassName+'Iframe').load(showDOMWindow(settings.anchoredClassName));
break;
case 'ajax'://////////////////////////////// ajax //////////////////////////////////////////
if(settings.windowHTTPType == 'post'){
if(settings.windowSourceURL.indexOf("?") !== -1){//has a query string
urlOnly = settings.windowSourceURL.substr(0, settings.windowSourceURL.indexOf("?"));
urlQueryObject = urlQueryToObject(settings.windowSourceURL);
}else{
urlOnly = settings.windowSourceURL;
urlQueryObject = {};
}
$('.' + settings.anchoredClassName+" #DOMWindowContent").load(urlOnly,urlQueryObject,function(){
showDOMWindow(settings.anchoredClassName);
});
}else{
if(settings.windowSourceURL.indexOf("?") == -1){ //no query string, so add one
settings.windowSourceURL += '?';
}
$('.' + settings.anchoredClassName+" #DOMWindowContent").load(
settings.windowSourceURL + '&random=' + (new Date().getTime()),function(){
showDOMWindow(settings.anchoredClassName);
});
}
break;
}
}else{//centered, fixed, absolute DOM window
//overlay & modal
if(settings.overlay){
$('body').append('<div id="DOMWindowOverlay" style="z-index:10000;display:none;position:absolute;top:0;left:0;background-color:'+settings.overlayColor+';filter:alpha(opacity='+settings.overlayOpacity+');-moz-opacity: 0.'+settings.overlayOpacity+';opacity: 0.'+settings.overlayOpacity+';"></div>');
if(shortcut.isIE6){//if IE 6
$('body').append('<iframe id="DOMWindowIE6FixIframe" src="blank.html" style="width:100%;height:100%;z-index:9999;position:absolute;top:0;left:0;filter:alpha(opacity=0);"></iframe>');
sizeIE6Iframe();
}
sizeOverlay();
var $DOMWindowOverlay = $('#DOMWindowOverlay');
$DOMWindowOverlay.fadeIn('fast');
if(!settings.modal){$DOMWindowOverlay.click(function(){$.closeDOMWindow();});}
}
//loader
if(settings.loader && settings.loaderImagePath !== ''){
$('body').append('<div id="DOMWindowLoader" style="z-index:10002;width:'+settings.loaderWidth+'px;height:'+settings.loaderHeight+'px;"><img src="'+settings.loaderImagePath+'" /></div>');
centerLoader();
}
//add DOMwindow
$('body').append('<div id="DOMWindow" style="background-repeat:no-repeat;'+settings.windowBGImage+';overflow:auto;padding:'+settings.windowPadding+'px;display:none;height:'+settings.height+'px;width:'+settings.width+'px;background-color:'+settings.windowBGColor+';border:'+settings.borderSize+'px solid '+settings.borderColor+'; position:absolute;z-index:10001"></div>');
var $DOMWindow = $('#DOMWindow');
//centered, absolute, or fixed
switch(settings.positionType){
case 'centered':
centerDOMWindow();
if(settings.height + 50 > shortcut.viewPortHeight()){//added 50 to be safe
$DOMWindow.css('top', (settings.fixedWindowY + shortcut.scrollOffsetHeight()) + 'px');
}
break;
case 'absolute':
$DOMWindow.css({'top':(settings.positionTop+shortcut.scrollOffsetHeight())+'px','left':(settings.positionLeft+shortcut.scrollOffsetWidth())+'px'});
if($.fn.draggable){
if(settings.draggable){$DOMWindow.draggable({cursor:'move'});}
}
break;
case 'fixed':
fixedDOMWindow();
break;
case 'anchoredSingleWindow':
var anchoredPositions = $(settings.anchoredSelector).position();
var anchoredPositionX = anchoredPositions.left + settings.positionLeft;
var anchoredPositionY = anchoredPositions.top + settings.positionTop;
$DOMWindow.css({'top':anchoredPositionY + 'px','left':anchoredPositionX+'px'});
break;
}
$(window).bind('scroll.DOMWindow',function(){
if(settings.overlay){sizeOverlay();}
if(shortcut.isIE6){sizeIE6Iframe();}
if(settings.positionType == 'centered'){centerDOMWindow();}
if(settings.positionType == 'fixed'){fixedDOMWindow();}
});
$(window).bind('resize.DOMWindow',function(){
if(shortcut.isIE6){sizeIE6Iframe();}
if(settings.overlay){sizeOverlay();}
if(settings.positionType == 'centered'){centerDOMWindow();}
});
switch(settings.windowSource){
case 'inline'://////////////////////////////// inline //////////////////////////////////////////
$DOMWindow.append($(settings.windowSourceID).children());
$DOMWindow.unload(function(){// move elements back when you're finished
$(settings.windowSourceID).append($DOMWindow.children());
});
showDOMWindow();
break;
case 'iframe'://////////////////////////////// iframe //////////////////////////////////////////
$DOMWindow.append('<iframe frameborder="0" hspace="0" wspace="0" src="'+settings.windowSourceURL+'" name="DOMWindowIframe'+Math.round(Math.random()*1000)+'" style="width:100%;height:100%;border:none;background-color:#fff;" id="DOMWindowIframe" ></iframe>');
$('#DOMWindowIframe').load(showDOMWindow());
break;
case 'ajax'://////////////////////////////// ajax //////////////////////////////////////////
if(settings.windowHTTPType == 'post'){
if(settings.windowSourceURL.indexOf("?") !== -1){//has a query string
urlOnly = settings.windowSourceURL.substr(0, settings.windowSourceURL.indexOf("?"));
urlQueryObject = urlQueryToObject(settings.windowSourceURL);
}else{
urlOnly = settings.windowSourceURL;
urlQueryObject = {};
}
$DOMWindow.load(urlOnly,urlQueryObject,function(){
showDOMWindow();
});
}else{
if(settings.windowSourceURL.indexOf("?") == -1){ //no query string, so add one
settings.windowSourceURL += '?';
}
$DOMWindow.load(
settings.windowSourceURL + '&random=' + (new Date().getTime()),function(){
showDOMWindow();
});
}
break;
}
}//end if anchored, or absolute, fixed, centered
};//end run()
if(settings.eventType){//if used with $().
return this.each(function(index){
$(this).bind(settings.eventType,function(){
run(this);
return false;
});
});
}else{//else called as $.function
run();
}
};//end function openDOMWindow
//allow for public call, pass settings
$.openDOMWindow = function(s){$.fn.openDOMWindow(s);};
})(jQuery);
And here is the hyperlink tag from my HTML that opens up the light box.
Change Icon
Here is a screenshot from siege detailing the memory step increase every time the user opens and closes the DOM window from that link. Any help is greatly appreciated. Thanks!
The problem is, that remove() removes nodes from the document-tree, but they still are available(for example you can use them again and put them back to the document).
In MSIE you can set the outerHTML-property of nodes to an empty string to really delete them, in other browsers I'm not sure how. You may have a look at this: http://www.josh-davis.org/node/7 .
The author uses there the delete-statement, but I'm not sure if it really deletes the nodes.