Javascript page reload while maintaining current window position - javascript

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!

Related

set cookie and show div on first visit then hide

I am trying to set multiple cookies depending on if the div exists via javascript but I have ran into an issue that I cannot figure out. On first visit, I would like to show the div to the user if the div exists then set a cookie (called redCookie) that expires in 3 days. After cookie is set on page refresh div should not be present. After 3 days I would like the div to be shown again redDiv.show().
At the moment the div shows on all page refreshes. The cookie is set but unfortunately it shows every time. Something must be wrong with my if statement but not sure what.
if ((redCookie = true) && (redDiv.length > 0))
Here is a link to js fiddle: https://jsfiddle.net/9uh96bh7/
Here are my functions:
$( document ).ready(function() {
colourCookies();
});
function colourCookies () {
var redCookie = getCookie("red-cookie-name");
var redDiv = $('.red');
var yellowCookie = getCookie("yellow-cookie-name");
var yellowDiv = $('.yellow');
if ((redCookie = true) && (redDiv.length > 0)) {
redDiv.show();
setCookie("red-cookie-name", redCookie, 3);
console.log ('red cookie is set');
} else {
redDiv.hide();
}
if ((yellowCookie = true) && (yellowDiv.length > 0)) {
yellowDiv.show();
setCookie("yellow-cookie-name", yellowCookie, 3);
console.log ('yellow cookie is set');
} else {
yellowDiv.hide();
}
}
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
var name = cname + "=";
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);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
First, the code.
It should be if ((redCookie == true) && (redDiv.length > 0)) not if ((redCookie = true) && (redDiv.length > 0)).
= is assign, == means equal to.
Second, the logic part.
cookie isset -> hide div
cookie is not set -> show div, set cookie
(correct me if I miss understood.)
So the if statement should be:
if (redCookie == true){
//hide div
} else {
//show div
//set cookie
}
Third, you make a mistake when setting cookies.
you should set you cookie like setCookie("yellow-cookie-name", true, 3);
If you use setCookie("yellow-cookie-name", yellowCookie, 3); and yellowCookie is null, this will cause failure to your if statement.
I think problem is with setting cookie, as some of the browser like chrome not sets cookie when you are running it on local, if you host it on server or run it through visual studio, it will work.. Test once with hosting it in iis if possible, else you can use localStorage like below...
$( document ).ready(function() {
colourCookies();
});
function colourCookies () {
removeIfThreeDaysElapsed('red-ls');
removeIfThreeDaysElapsed('yellow-ls');
if (!localStorage.getItem('red-ls')) {
$(".red").show();
localStorage.setItem("red-ls", new Date().toGMTString());
} else {
$(".red").hide();
}
if (!localStorage.getItem('yellow-ls')) {
$(".yellow").show();
localStorage.setItem("yellow-ls", new Date().toGMTString());
} else {
$(".yellow").hide();
}
}
function removeIfThreeDaysElapsed(lsname){
var d1 = localStorage.getItem(lsname);
if(d1){
if(new Date() > new Date(new Date().getTime()+(3*24*60*60*1000))){
localStorage.removeItem(lsname);
}
}
}
You may need to edit the code to handle all the scenarios!
If you able to see the cookie in browser, then please try with check like below...
if (redCookie) {
redDiv.hide();
} else {
redDiv.show();
setCookie("red-cookie-name", true, 3);
}
Because when you are getting value back from cookie its datatype is not boolean, it gets converted to string, so either you check like above or can use redCookie === "true".
Hope this helps you.

User selectable CSS color schemes with cookie support

I'm building a website template for primarily text content.
I would like to have two user switchable color schemes.
One dark background/light text and one light background/dark text to suit different viewing conditions.
How do I plan and design it such that user can toggle color scheme with a click of button and have cookie memorize the user's preference?
Without breaking the design, I would also like to let the user be able to increase the font-size and line-height for certain content block, eg. <div id="article"></font>
Is this feasible?
#GamerNebulae #EliTownsend After studying the answer and making some modification, I come up with a solution that works for my situation.
Not sure if it's heavy when it comes to execution. Any advice for further improvement is appreciated.
CSS
body.dark {
background: #222;
color: #777;
}
HTML
Switch
Javscript
function createCookie(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 = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(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;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
function changeTheme() {
if (jQuery("body").hasClass("dark")) {
jQuery("body").removeClass("dark");
createCookie('theme', 'regular', 7);
}
else {
jQuery("body").addClass("dark");
createCookie('theme', 'dark', 7);
}
}
// initialize page, apply theme color by checking cookie variable 'theme'
var theme = readCookie('theme');
if(theme == "dark") jQuery("body").addClass("dark");
else if (theme == "regular") jQuery("body").removeClass("dark");
else if (jQuery("body").hasClass("dark")) createCookie('theme', 'dark', 7);
Stylesheets
<link rel="stylesheet" type="text/css" title="blue" href="http://example.com/css/blue.css">
<link rel="alternate stylesheet" type="text/css" title="pink" href="http://example.com/css/pink.css">
HTML
<form>
<input type="submit" onclick="switch_style('blue');return false;" name="theme" value="Blue Theme" id="blue">
<input type="submit" onclick="switch_style('pink');return false;" name="theme" value="Pink Theme" id="pink">
</form>
Javascript
//TO BE CUSTOMISED
var style_cookie_name = "style" ;
var style_cookie_duration = 30 ;
var style_domain = "thesitewizard.com" ;
// END OF CUSTOMISABLE SECTION
// You do not need to customise anything below this line
function switch_style ( css_title )
{
// You may use this script on your site free of charge provided
// you do not remove this notice or the URL below. Script from
// http://www.thesitewizard.com/javascripts/change-style-sheets.shtml
var i, link_tag ;
for (i = 0, link_tag = document.getElementsByTagName("link") ;
i < link_tag.length ; i++ ) {
if ((link_tag[i].rel.indexOf( "stylesheet" ) != -1) &&
link_tag[i].title) {
link_tag[i].disabled = true ;
if (link_tag[i].title == css_title) {
link_tag[i].disabled = false ;
}
}
set_cookie( style_cookie_name, css_title,
style_cookie_duration, style_domain );
}
}
function set_style_from_cookie()
{
var css_title = get_cookie( style_cookie_name );
if (css_title.length) {
switch_style( css_title );
}
}
function set_cookie ( cookie_name, cookie_value,
lifespan_in_days, valid_domain )
{
// http://www.thesitewizard.com/javascripts/cookies.shtml
var domain_string = valid_domain ?
("; domain=" + valid_domain) : '' ;
document.cookie = cookie_name +
"=" + encodeURIComponent( cookie_value ) +
"; max-age=" + 60 * 60 *
24 * lifespan_in_days +
"; path=/" + domain_string ;
}
function get_cookie ( cookie_name )
{
// http://www.thesitewizard.com/javascripts/cookies.shtml
var cookie_string = document.cookie ;
if (cookie_string.length != 0) {
var cookie_value = cookie_string.match (
'(^|;)[\s]*' +
cookie_name +
'=([^;]*)' );
return decodeURIComponent ( cookie_value[2] ) ;
}
return '' ;
}
I found this located here How to Use Javascript to Change a CSS

Use javascript cookie to remember which div is shown

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));

How to decode this javascript?

My question is how can I decode this JavaScript and how is encoded (with which program or online tool).
Here is the JavaScript that I want to decode:
http://pastebin.com/hZvKySjj
Every obfuscated script needs some kind of eval. In here, the lines
_L = 'constr\x75\x63\x74\x6F\x72';
[][_L][_L](_Z[_h._t4](_F))();
are doing this. _L is the string "constructor", and [].constructor.constructor is the Function constructor. It will be called with the decoded script, and the resulting function will be called. We can substitute it with an alert, paste the script in the console*, and wait for the result - we don't even need to understand how the decoding works. In your case, the result is (yes, including all the comments and linebreaks):
var alarm ="0";
var content = document;
if ((content.getElementById("wrapper") != null))
{
document.getElementById('wrapper').style.display = 'block';
}
function a ()
{
if ((content.getElementById("links") != null))
{
var temp = content.getElementById("links").innerHTML;
if ((temp.indexOf('nofollow')+1) > 0) alarm = "1";
else if ((temp.indexOf('noindex')+1) > 0) alarm = "1";
}
else alarm = "1";
}
function b ()
{
if ((content.getElementById("aa") != null) && (content.getElementById("ab") != null))
{
temp = document.getElementById("aa").href;
if ("http://uc-portaller.ru/" != temp) alarm = "1";
temp = document.getElementById("ab").innerHTML;
if ("скрипты для ucoz" != temp) alarm = "1";
}
else alarm = "1";
}
function c ()
{
if ((content.getElementById("ba") != null) && (content.getElementById("bb") != null))
{
temp = content.getElementById("ba").href;
if ("http://austere.ru/" != temp) alarm = "1";
temp = content.getElementById("bb").innerHTML;
if ("доска объявлений" != temp) alarm = "1";
}
else alarm = "1";
}
function d ()
{
if ((content.getElementById("ca") != null) && (content.getElementById("cb") != null))
{
temp = content.getElementById("ca").href;
if ("http://www.for-creative.com/" != temp) alarm = "1";
temp = content.getElementById("cb").innerHTML;
if ("темы для ucoz" != temp) alarm = "1";
}
else alarm = "1";
}
a ();
if (alarm == "0") b ();
if (alarm == "0") c ();
if (alarm == "0") d ();
if (alarm == "1") prompt('Нарушены условия использования, по всем вопросам обращайтесь в ICQ:', '376880395');
$(document).ready(function(){
//When you click on a link with class of poplight and the href starts with a #
$('a.poplight[href^=#]').click(function() {
var popID = $(this).attr('rel'); //Get Popup Name
var popURL = $(this).attr('href'); //Get Popup href to define size
//Pull Query & Variables from href URL
var query= popURL.split('?');
var dim= query[1].split('&');
var popWidth = dim[0].split('=')[1]; //Gets the first query string value
//Fade in the Popup and add close button
$('#' + popID).fadeIn().css({ 'width': Number( popWidth ) }).prepend('');
//Define margin for center alignment (vertical + horizontal) - we add 80 to the height/width to accomodate for the padding + border width defined in the css
var popMargTop = ($('#' + popID).height() + 80) / 2;
var popMargLeft = ($('#' + popID).width() + 80) / 2;
//Apply Margin to Popup
$('#' + popID).css({
'margin-top' : -popMargTop,
'margin-left' : -popMargLeft
});
//Fade in Background
$('body').append('<div id="fade"></div>'); //Add the fade layer to bottom of the body tag.
$('#fade').css({'filter' : 'alpha(opacity=0)'}).fadeIn(); //Fade in the fade layer
return false;
});
//Close Popups and Fade Layer
$('a.close, #fade').live('click', function() { //When clicking on the close or fade layer...
$('#fade , .popup_block').fadeOut(function() {
$('#fade, a.close').remove();
}); //fade them both out
return false;
});
});
$.fn.tabs = function () {
return this.each(function () {
var $tabwrapper = $(this);
var $panels = $tabwrapper.find('> div');
var $tabs = $tabwrapper.find('> ul a');
$tabs.click(function () {
$tabs.removeClass('selected');
$(this).addClass('selected');
$panels
.hide() // hide ALL the panels
.filter(this.hash) // filter down to 'this.hash'
.show(); // show only this one
return false;
}).filter(window.location.hash ? '[hash=' + window.location.hash + ']' : ':first').click();
});
};
$(document).ready(function () {
// console.log(window.location.hash);
$('div.tabs').tabs();
});
*) Of course you need to be sure what you're doing. There's always a small risk that it's a malicious script, and you might have not found all evals. #jfriend00's tip on executing the decoding snippets line-by-line is a safer way.
The only way I know of to understand what this code does is to find a safe environment (in case the code has malicious intent) and execute it line-by-line in a debugger and watch what it does as it deobfuscates itself to turn itself into normal javascript. The variable names will often stay obscured, but the giant string in _O will get decoded into something (probably javascript code).
Have a look at: http://www.labnol.org/software/deobfuscate-javascript/19815/
They show you how can you do something like that, it's basically a matter of using chrome debugger to "beautify" the code and make it easier to read.
Some versions of chrome don't have the command on a context menu, just look for the command "Pretty print" (has a icon like -> {})
Once done that, you can use a javascript console to evaluate small snippets of code to reverse engineer it. Eg. the expression (at the beginning of your code)
1) (s\u0065lf + ([] * 0) * 1)
2) '\x5B'
3) ((s\u0065lf + ([] * 0) * 1)[0 ^ 0] == '\x5B')
returns this string on my browser
1) "[object Window]0"
2) "["
3) true
Just find the starting point and follow from there. Obfuscated code follows the same rules as normal one, it's just all messed up.

jQuery DOMWindow script doesn't release memory

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.

Categories