How to decode this javascript? - 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.

Related

javascript not working on IE10 / No errors. Works fine on other normal browsers

var depth = 0;
var moving = false;
var answers = new Array();
var qNo = 0;
var rangeCarousel;
var productCarousel;
var ih, iw, orient;
var sidebarOpen = false;
var focused = "range";
var currentRange = 0;
$(document).ready(function () {
document.getElementById('intro').addEventListener('click', clickHandler);
document.getElementById('q1').addEventListener('click', clickHandler);
document.getElementById('q2').addEventListener('click', clickHandler);
document.getElementById('q3').addEventListener('click', clickHandler);
document.getElementById('q4').addEventListener('click', clickHandler);
document.getElementById('intro').addEventListener('webkitTransitionEnd', transitionEnd);
document.getElementById('intro').addEventListener('transitionend', transitionEnd);
document.getElementById('intro').addEventListener('transition', transitionEnd);
});
function clickHandler(e) {
if ((qNo < 4) && (e.target.id != 'intro')) {
qNo++;
if (!moving) {
depth -= 100;
document.getElementById('intro').style.top = (depth + '%');
document.getElementById('q1').style.top = (depth + '%');
document.getElementById('q2').style.top = (depth + '%');
document.getElementById('q3').style.top = (depth + '%');
document.getElementById('q4').style.top = (depth + '%');
moving = true;
}
} else if (qNo == 4) {
var c = e.target.parentNode.classList[0];
switch (c) {
case 'one':
window.open("test.html","_self");
break;
case 'two':
window.open("test.html","_self");
break;
case 'three':
window.open("test.html","_self");
break;
case 'four':
window.open("test.html","_self");
break;
}
}
}
function transitionEnd() {
moving = false;
}
i m trying to create a quiz where users clicks on the images then loads the answer. It works fine on ie11 but i also need to make it work on ie10. I cant see any errors or anything to show me whats wrong
Any help or suggestion will be great
Some old IE does not support target property. You can use e.srcElement which is an alias of target as an alias of target
((e.target || e.srcElement).id) === "intro"
& also use it to find the parentNode
Side Note :As mentioned in comment section you can use jquery as which will also reduce the number of lines in your code beside efficiently handling events
You can also use jquery multiple selector instead of writing same lines of code for attaching event to every selector.
$('sel1 ,selector2 , selector 3 ...').click(function(event){.. rest of code})

How can I change to a default background image

I use the following function to create dynamic elements using an ajax response.
function itemGroupSelection(elem,majorGroupId,itemGroupId){
var itemGroup;
var majorGroup;
if(elem == undefined || elem == null || elem == ""){
var itemGroup = itemGroupId;
var majorGroup = majorGroupId;
}else if(majorGroupId == null && itemGroupId == null){
var itemGroup = elem.attr("id");
var majorGroup = elem.attr("majorgroup");
}
$('.breadcrumb a').removeClass('active');
if(elem == ""){
$('.breadcrumb a').first().addClass('active');
}else{
elem.addClass('active');
}
var selectedOutlet = $('#outlets select').children(":selected").attr("id");
$('.item').show();
$('.breadcrumb').show('1');
var data = "majorGroupId=" + majorGroup + "&itemGroupId=" + itemGroup + "&outletCode=" + selectedOutlet;
if(selectedOutlet == undefined){
getSystemMessage('Please select an outlet.');
}else{
ajaxCall("/getItems","POST",data,function(result){
var element = $('#model-item').find('.item').first();
$('#item-list-section').empty();
for(var i = 0; i < result.items.length; i++){
var clone = element.clone();
clone.attr("id", result.items[i].itemId);
clone.find('.item-price').html("<h4>" + result.items[i].rate.toFixed(2) + "</h4>");
if(result.items[i].itemName.length >= 20){
clone.find('.item-name').css('overflow','hidden');
clone.attr('title', result.items[i].itemName )
}
clone.find('.item-name').html("<h4>"+ result.items[i].itemName + "</h4>");
clone.css('background-image','c:/zharaimages/' + result.items[i].itemId + '/image.jpg');
clone.draggable({
revert : false,
zIndex: 1,
containment: "window",
opacity: 0.5,
cursor: "move",
helper: function() { return $(this).clone().appendTo('body').show(); }
});
$('#item-list-section').append(clone);
}
});
}
}
Using the following command I try to select the background image in the local disc.
clone.css('background-image','c:/zharaimages/' + result.items[i].itemId + '/image.jpg');
How can i switch to a default image if there is no image in the path defined. I'm using jQuery 1.9.
Try using the onerror attribute of img, if the link given in src attribute fails to load, ur function in error is called and u can set your default image there (w3schools.com/jsref/event_img_onerror.asp)
You need to handle the onerror event of this image, which will occur whenever the file cannot be found:
$('#image').error(function(){
$(this).off('error'); // otherwise, inexistence of the default image is a real pain
$(this).attr('src', 'http://www.google.ca/images/srpr/logo4w.png');
});
Take a look at this working FIDDLE.
Then,
in your situation, you could have something like this:
var path='the path';
clone.css('background-image', 'url('+path+')');
$('<img src="'+path+'" />').error(function(){
$(this).off('error');
clone.css('background-image', 'url('+default_path+')');
});
Hope this helps :-)

Issues with javascript properly loading and seeing everything

Ok, so I have a form that loads from a request through a zip code widget from another page. THe widget populates two of the form fields immediately, on submit, on the new page. My problem is that I have a pretty complicated piece of flash on there as well that has ONE main issue. My flash is essentially a pie chart that lights up on mouseOver events and onClick events in the form check boxes. It works like it should except for the fact that on initially loading the page the javascript will not see the pre-populated check box and perform the corresponding highlighting action. This only happens in fields that are populated through the widgets, if a user checks the boxes it works fine as I have an onClick event handler attached to it. I wrote a preselect function that will determine if the field is preselected or not by a widget and then pass that on down the line to highlight it correctly (which it does as long as I have the alert functioning). Now, if I add an alert inside of the script (it doesn't matter where, as I've tried them in every function) it works like it suppose to and sees the fields that are populated immediately by the widget and highlights the corresponding field as it is suppose to. Why would an alert box be the only thing keeping this working. It is the simplest of alerts, but removing that breaks my code. Any ideas?
Here is my code: (I placed three * on either side of the alert that I am talking about)
YAHOO.namespace("SOME.Place.QuoteRequest");
/**
* #projectDescription SOME.util.QuoteRequest is the namespace for all quote request related functions. This is a supplemental controller for quote request pages.
* #return (object) function executes automatically when parsed and returns references to it's public members
* #author web development
* #version 1.0
*/
SOME.PLACE.QuoteRequest = function () {
/**
* shortcuts to global objects
*/
var Dom = YAHOO.util.Dom, Event = YAHOO.util.Event;
/**
* Function to add the special error handler to the zip code area of the form. Zip code errors display in this area. Also the continue button is sometimes a submit and sometimes a button depending on whether the rest of the form is visible.
* #param {Object} frm the quote request form object
*/
var addQuoteRequestZipCodeHandler = function(frm){
if(frm.continueBtn){
Event.addListener(frm.submitBtn, "click", function(e){
var errP = Dom.get("error"), errMsg;
if(errP) errP.parentNode.removeChild(errP);
errMsg = SOME.util.Forms.validateFormField(this.zipCode.name, frm)
if(errMsg){
Event.preventDefault(e);
var p = document.createElement("p");
p.id = "error";
var pText = document.createTextNode(errMsg);
p.appendChild(pText);
Dom.insertBefore(p, "quoteZipLabel");
}
},frm, true);
}
};
/**
* Function to manage the interaction between the product checkboxes and the financial security flash wheel
*/
var CheckboxCollection = function()
{
var odom = Dom.get("finwheel");
var ochklist = Dom.getElementsByClassName("checkbox", "input", odom);
var boolArray = [false,false,false,false,false,false];
var ctr = 0;
for(var c = 0 ; c < ochklist.length ; c++)
{
switch(ochklist[c].value.toUpperCase())
{
case "AUTO": case "HOME": case "UMBRELLA": case "FARM": case "BUSINESS": //[Auto , Farm/Ranch/Crop, Home/Reuters, Umbrella, business]
if(ochklist[c].checked && ctr == 0)
{
***alert("auto checked");***
boolArray[ctr] = ochklist[c].checked;
ctr = ctr+1;
}
break;
case "LIFE": // [Life]
if(ctr == 0)
{
boolArray[ctr] = false;
ctr = ctr+1;
}
if(ochklist[c].checked && ctr == 1)
{
boolArray[ctr] = ochklist[c].checked;
ctr = ctr+1;
}
break;
case "DI": case "LTC": case "MEDSUP": // [disability income , Medicare , Long term]
if(ctr == 1)
{
boolArray[ctr] = false;
ctr = ctr+1;
}
if(ochklist[c].checked && ctr == 2)
{
boolArray[ctr] = ochklist[c].checked;
ctr = ctr+1;
}
break;
case "RETIREMENT":
if(ctr == 2)
{
boolArray[ctr] = false;
ctr = ctr+1;
}
if(ochklist[c].checked && ctr == 3)
{
boolArray[ctr] = ochklist[c].checked;
ctr = ctr+1;
}
break;
case "EDUCATION":
if(ctr == 3)
{
boolArray[ctr] = false;
ctr = ctr+1;
}
if(ochklist[c].checked && ctr == 4)
{
boolArray[ctr] = ochklist[c].checked;
ctr = ctr+1;
}
break;
case "FINANCIAL":
if(ctr == 4)
{
boolArray[ctr] = false;
ctr = ctr+1;
}
if(ochklist[c].checked && ctr == 5)
{
boolArray[ctr] = ochklist[c].checked;
ctr = ctr+1;
}
break;
}
}
return boolArray;
};
/**
* Function to add handlers to highlight the flash wheel
* #param {Object} frm the quote request form object
*/
var addQuoteRequestProductHandlers = function(frm){
if(document.URL.indexOf("#financialSecurityPlan") >= 0){
document.getElementById("finSection").style.display = "none";
}
var imgs = Dom.getElementsByClassName("infoImg", "IMG", "quoteRequest");
var oflash = Dom.get("flashfsWheel");
for(var i=0; i<imgs.length; i++){
Event.addListener(imgs[i], 'mouseover', function(e){
var titlenm = this.parentNode.id.substring(0,this.parentNode.id.indexOf("Title"));
if(oflash) oflash.HighlightWheel(titlenm,"true","TITLE");
});
Event.addListener(imgs[i], 'mouseout', function(e){
var titlenm = this.parentNode.id.substring(0,this.parentNode.id.indexOf("Title"));
if(oflash) oflash.HighlightWheel(titlenm,"false","TITLE");
});
}
// Check to make sure pre-selected check box higlights corresponding flash pieces
var preselect = CheckboxCollection();
if(!preselect[5])
{
for(var f = 0 ; f < preselect.length ; f++ )
{
if(f == 0)
oflash.HighlightWheel("property",preselect[f],"CLICK");
else if(f == 1)
oflash.HighlightWheel("income",preselect[f],"CLICK");
else if(f == 2)
oflash.HighlightWheel("health",preselect[f],"CLICK");
else if(f == 3)
oflash.HighlightWheel("retirement",preselect[f],"CLICK");
else if(f == 4)
oflash.HighlightWheel("education",preselect[f],"CLICK");
}
}
var secs = Dom.getElementsByClassName("formSection", "DIV", frm);
Event.addListener(secs[2], "click", function(e) {
var elTarget = Event.getTarget(e);
var oflash = Dom.get("flashfsWheel");
if(elTarget.nodeName.toUpperCase() == "INPUT"){
elTarget.value = elTarget.value.toLowerCase();
//(pass elTarget.checked as the parm to say whether to light up or turn off)
if(elTarget.value == "auto" || elTarget.value == "home" || elTarget.value == "farm" || elTarget.value == "umbrella" || elTarget.value == "business"){
//call flash piece to light up property piece
var bool = CheckboxCollection();
if( oflash && !bool[5] ) oflash.HighlightWheel("property",bool[0],"CLICK");
if(bool[0]) frm.needs[0].value = "property";
else frm.needs[0].value = "";
}
else if (elTarget.value == "life"){
//call flash to light up income piece
var bool = CheckboxCollection();
if(oflash && !bool[5]) oflash.HighlightWheel("income",bool[1],"CLICK");
if(bool[1]) frm.needs[1].value= "income";
else frm.needs[1].value= "";
}
else if(elTarget.value == "di" || elTarget.value == "ltc" || elTarget.value == "medsup"){
//call flash to light up health piece
var bool = CheckboxCollection();
if(oflash && !bool[5]) oflash.HighlightWheel("health",bool[2],"CLICK");
if(bool[2]) frm.needs[2].value= "health";
else frm.needs[2].value= "";
}
else if(elTarget.value == "retirement"){
var bool = CheckboxCollection();
if(oflash && !bool[5] ) oflash.HighlightWheel("retirement",bool[3],"CLICK");
if(bool[3]) frm.needs[3].value= "retirementSavings";
else frm.needs[3].value= "";
}
else if(elTarget.value == "education"){
var bool = CheckboxCollection();
if(oflash && !bool[5] ) oflash.HighlightWheel("education",bool[4],"CLICK");
if(bool[4]) frm.needs[4].value= "education";
else frm.needs[4].value= "";
}
else if(elTarget.value == "financial"){
var bool = CheckboxCollection();
if(oflash) oflash.HighlightWheel("center",bool[5],"CLICK");
if(!bool[5])
{
for(var f = 0 ; f < bool.length ; f++ )
{
if(f == 0)
oflash.HighlightWheel("property",bool[f],"CLICK");
else if(f == 1)
oflash.HighlightWheel("income",bool[f],"CLICK");
else if(f == 2)
oflash.HighlightWheel("health",bool[f],"CLICK");
else if(f == 3)
oflash.HighlightWheel("retirement",bool[f],"CLICK");
else if(f == 4)
oflash.HighlightWheel("education",bool[f],"CLICK");
}
}
//call flash to light up whole thing
}
}
});
};
/**
* External method to call to highlight a product group for use by the financial needs flash wheel
* id is the id of the product group title to highlight - propertyTitle, incomeTitle, healthTitle, retirementTitle, educationTitle, financialTitle
* highlight is a boolean true or false to highlight or turn off highlight
*/
var highlightProductGroup = function(id, highlight){
if(highlight)
Dom.addClass(id, id + "Highlight");
else
Dom.removeClass(id, id+ "Highlight");
};
/**
* function to kick off additional controllers for the quote request form
* #param {Object} frm the quote request form object
*/
var init = function(frm){
//add zip code handler
addQuoteRequestZipCodeHandler(frm);
if(frm.submitBtn){
var quoteRep = Dom.get("quoteRep");
if(quoteRep){
//add flash wheel
var output = '';
if(SOME.domain.indexOf("cottonstates") != -1){
output += '<object height="370" width="390" data="flash/cottonStates/fiveNeedsWheel2.swf" type="application/x-shockwave-flash" id="flashfsWheel"><param value="flash/SOMEStates/fiveNeedsWheel2.swf" name="movie"/><param value="always" name="allowScriptAccess"/><param name="wmode" value="window"/><a class="external" href="http://www.adobe.com/go/getflashplayer"><img alt="Get Flash Player" src="images/button_getFlashPlayer.gif"/></a></object>';
//create the autocomplete object
SOME.widget.AutoComplete.init(quoteRep, "acResults", "/SiteController?url=/#AutoCompleteCS&forward=agentList.jsp", frm );
}else{
output += '<object height="370" width="390" data="flash/financial/fiveNeedsWheel2.swf" type="application/x-shockwave-flash" id="flashfsWheel"><param value="flash/financial/fiveNeedsWheel2.swf" name="movie"/><param value="always" name="allowScriptAccess"/><param name="wmode" value="window"/><a class="external" href="http://www.adobe.com/go/getflashplayer"><img alt="Get Flash Player" src="images/button_getFlashPlayer.gif"/></a></object>';
//create the autocomplete object
SOME.widget.AutoComplete.init(quoteRep, "acResults", "/SiteController?url=/#allRepresentativesAutoComplete&forward=agentList.jsp", frm );
}
if(document.getElementById("fsWheel"))
document.getElementById("fsWheel").innerHTML = output;
Dom.addClass(["infoPos5", "quoteEmailLabel", "quoteEmail"], "noDisplay");
}
//add phone or email handler
SOME.util.Forms.initPhoneEmailFields(frm.phone, frm.customerEmail, true);
//add flash product handlers
addQuoteRequestProductHandlers(frm);
//add submit handler
Event.addListener(frm.submitBtn, "click", function(e){
var errs = SOME.util.Forms.validateForm(frm, {replaceErrorCodes: true, autoInsert : true, insertNode : Dom.getElementsByClassName("formSection")[0], showErrorHeader: true});
if(errs.length > 0){
Event.preventDefault(e);
window.scrollTo(0,0);
}
else{
this.businessSubject.value = this.businessSubject.value + frm.firstName.value + " " + frm.lastName.value;
}
},frm, true);
}
};
/**
* return the public members of this singleton
*/
return {
init:init,
highlightProductGroup:highlightProductGroup
};
}();
Just a guess, but could it be that the script is executing and trying to communicate with Flash before the Flash object is loaded, and by putting the alert in there you're breaking the execution long enough for the Flash to load?
If so you have a few options:
Delay the execution of the the script until the Flash element is loaded.
Execute the script immediately and write any changes to the checkboxes to a flashvar that Flash can read on startup
Execute the script immediately, but instead of calling to Flash, store the values and have Flash call back to the page using ExternalInterface when it is loaded and ready to display.

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.

Trouble with onclick attribute for img when used in combination with setInterval

I am trying to make images that move around the screen that do something when they are clicked. I am using setInterval to call a function to move the images. Each image has the onclick attribute set. The problem is that the clicks are not registering.
If I take out the setInterval and just keep the images still, then the clicks do register.
My code is here (html, css, JavaScript): https://jsfiddle.net/contini/nLc404x7/4/
The JavaScript is copied here:
var smiley_screen_params = {
smiley_size : 100, // needs to agree with width/height from css file
num_smilies: 20
}
var smiley = {
top_position : 0,
left_position : 0,
jump_speed : 2,
h_direction : 1,
v_direction : 1,
intvl_speed : 10, // advance smiley every x milliseconds
id : "smiley"
}
function randomise_direction(s) {
var hd = parseInt(Math.random()*2);
var vd = parseInt(Math.random()*2);
if (hd === 0)
s.h_direction = -1;
if (vd === 0)
s.v_direction = -1;
}
function plotSmiley(sp /* sp = smiley params */) {
var existing_smiley = document.getElementById(sp.id);
if (existing_smiley !== null)
// delete existing smiley so we can move it
document.getElementById("smileybox").removeChild(existing_smiley);
var smiley_to_plot = document.createElement('img');
smiley_to_plot.setAttribute('src', "http://i.imgur.com/C0BiXJx.png");
smiley_to_plot.setAttribute('id', sp.id);
smiley_to_plot.setAttribute('onclick', "my_click_count()");
smiley_to_plot.style.position = 'absolute';
smiley_to_plot.style.top = sp.top_position + "px";
smiley_to_plot.style.left = sp.left_position + "px";
document.getElementById("smileybox").appendChild(smiley_to_plot);
}
function random_direction_change() {
var r = parseInt(Math.random()*200);
if (r===0)
return true;
else
return false;
}
function moveFace(sp_array /* sp_array = smiley params array */) {
var i;
var sp;
for (i=0; i < sp_array.length; ++i) {
// move ith element
sp = sp_array[i];
if (
(sp.h_direction > 0 && sp.left_position >= smiley_screen_params.width - smiley_screen_params.smiley_size) ||
(sp.h_direction < 0 && sp.left_position <= 0) ||
(random_direction_change())
) {
sp.h_direction = -sp.h_direction; // hit left/right, bounce off (or random direction change)
}
if (
(sp.v_direction > 0 && sp.top_position >= smiley_screen_params.height - smiley_screen_params.smiley_size) ||
(sp.v_direction < 0 && sp.top_position <= 0) ||
(random_direction_change())
) {
sp.v_direction = -sp.v_direction; // hit top/bottom, bounce off (or random direction change)
}
sp.top_position += sp.v_direction * sp.jump_speed;
sp.left_position += sp.h_direction * sp.jump_speed;
plotSmiley(sp);
}
}
if (typeof Object.create !== 'function') {
Object.create = function(o) {
var F = function () {};
F.prototype = o;
return new F();
};
}
function generateFaces() {
var smilies = new Array();
var s;
var i;
var css_smileybox=document.getElementById("smileybox");
var sb_style = getComputedStyle(css_smileybox, null);
// add info to the screen params
smiley_screen_params.width = parseInt(sb_style.width);
smiley_screen_params.height = parseInt(sb_style.height);
// create the smileys
for (i=0; i < smiley_screen_params.num_smilies; ++i) {
s = Object.create(smiley);
s.id = "smiley" + i;
s.top_position = parseInt(Math.random() * (smiley_screen_params.height - smiley_screen_params.smiley_size)),
s.left_position = parseInt(Math.random() * (smiley_screen_params.width - smiley_screen_params.smiley_size)),
randomise_direction(s);
smilies.push(s);
}
setInterval( function(){ moveFace(smilies) }, smiley.intvl_speed );
}
var click_count=0;
function my_click_count() {
++click_count;
document.getElementById("mg").innerHTML = "Number of clicks: " + click_count;
}
generateFaces();
The generateFaces() will generate parameters (for example, coordinates of where they are placed) for a bunch of smiley face images. The setInterval is within this function, and calls the moveFace function to make the smiley faces move at a fixed interval of time. moveFace computes the new coordinates of each smiley face image and then calls plotSmiley to plot each one on the screen in its new location (removing it from the old location). The plotSmiley sets the onclick attribute of each image to call a dummy function just to see if the clicks are registering.
Thanks in advance.
This is not a complete answer but it could give you some perspective to improve your code.
First of all, your idea of deleting the existing img so wrong. If it does exist, all you need is to just change its position so instead of this
if (existing_smiley !== null)
// delete existing smiley so we can move it
document.getElementById("smileybox").removeChild(existing_smiley);
you should do something like this:
if (existing_smiley !== null)
var smiley_to_plot = existing_smiley;
else {
var smiley_to_plot = document.createElement('img');
smiley_to_plot.setAttribute('src', "http://i.imgur.com/C0BiXJx.png");
smiley_to_plot.setAttribute('id', sp.id);
smiley_to_plot.style.position = 'absolute';
document.getElementById("smileybox").appendChild(smiley_to_plot);
smiley_to_plot.addEventListener('click', my_click_count);
}
smiley_to_plot.style.top = sp.top_position + "px";
smiley_to_plot.style.left = sp.left_position + "px";
As you can see new image is only being added if it's not already there. Also notice that adding events by using .setAttribute('onclick', "my_click_count()"); is not a good way to do. You should use .addEventListener('click', my_click_count); like I did.
Like I said this is not a complete answer but at least this way they response to the click events now.
FIDDLE UPDATE
Good luck!

Categories