Issues with javascript properly loading and seeing everything - javascript
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.
Related
else statement not getting executed?
I want to reload my page if the page is not fully loaded. I am using the below if-else loop. If part is working properly but the else part is not getting executed. I have no idea why is this happening??? Can someone help me to overcome this problem?? function loadCensusData(obj) { console.log(objXHR1.responseXML); var vals = objXHR1.responseXML.getElementsByTagName("val"); var noOfCols = 4; var noOfRows = vals.length / noOfCols; var row = 0; while (row < noOfRows) { var Did = vals[row * noOfCols + 0].childNodes[0].nodeValue; var DRevenue = vals[row * noOfCols + 2].childNodes[0].nodeValue; var censusVariable = DRevenue; var div = Did; console.log(div); //console.log(censusVariable); if (censusVariable < censusMin) { censusMin = censusVariable; } if (censusVariable > censusMax) { censusMax = censusVariable; } map.data.getFeatureById(div).setProperty('census_variable', censusVariable); document.getElementById('census-min').textContent = censusMin.toLocaleString(); document.getElementById('census-max').textContent = censusMax.toLocaleString(); row++; } if (document.readyState == 'interactive' || document.readyState == 'complete') { alert('Done'); } else { alert('zzzzzzzzzzzzzzzzzz'); self.location.reload(); } } loadCensusData loads the data from my report. census_variable is used to apply color style I have used the ready state conditions. Can someone help me to overcome this problem??
How to force loop to wait until user press submit button?
I have simple function which checks if entered pin code is valid. But i don't know how to force for-loop to wait until i enter code again to check again it's validity. So how it should be - i type PIN code, then click OK button and it checks whether it's correct (if it is, i can see my account menu; if it's not i have to type it again and i have 2 chances left). My code fails, because PIN when code is wrong program should wait until i type new code and press OK button again. I tried setTimeout(), callback(), but it doesn't work. This is what i have - a function with for-loop that just runs 3 times (as it is suppose to, but not instantly) without giving a chance to correct the PIN code. That's whole, unfinished yet, code: http://jsfiddle.net/j1yz0zuj/ Only function with for-loop, which checks validity of PIN code: var submitKey = function(callback) { console.log("digit status" + digitStatus); if (digitStatus == 0) { correctPIN = 1234; var onScreen = document.getElementById("screen"); for (i=0; i<3; i++) { if (onScreen.innerHTML.slice(15, onScreen.innerHTML.length) == correctPIN) { setTimeout(accountMenu, 1250); //break; } else { onScreen.innerHTML += "<br> Błędny kod PIN! Wpisz PIN ponownie. <br> Pozostało prób: " + (2-i); callback(); //cardInserted = function(function(){console.log("Ponowne wpisanie PINu");}); } if (i=2) console.log("blokada"); } } else if (digitStatus == 1) { } }
Your approach is wrong. You should not make the user wait!!! You need 2 more variables at the top of your programm pincount=0 and pininputallowed. Increase pincount in the submit key function by 1 and then check if pincount<3. Here is a corrected version of your code. http://jsfiddle.net/kvsx0kkx/16/ var pinCount=0, pinAllowed=true; var submitKey = function() { console.log("digit status" + digitStatus); if (digitStatus == 0) { correctPIN = 1234; var onScreen = document.getElementById("screen"); pinCount++; if(pinCount >= 3) { pinAllowed = false; onScreen.innerHTML = "<br>blokada"; } if(pinAllowed){ if (onScreen.innerHTML.slice(15, onScreen.innerHTML.length) == correctPIN) { setTimeout(accountMenu, 1250); //break; } else { onScreen.innerHTML += "<br> Błędny kod PIN! Wpisz PIN ponownie. <br> Pozostało prób: " + (3-pinCount); inputLength = 0; document.getElementById("screen").innerHTML += "<br>Wpisz kod PIN: "; //callback(); //cardInserted = function(function(){console.log("Ponowne wpisanie PINu");}); } } } else if (digitStatus == 1) { } } You need to create much more variables to control your machine. Your add/delete digit function had conditions that were badly written and only worked if the text on the screen was short enough. var inputLength = 0; addDigit = function(digit){ //numKeyValue = numKeyValue instanceof MouseEvent ? this.value : numKeyValue;{ if (inputLength < pinLength) { onScreen.innerHTML += this.value; inputLength++; } //if (onScreen.innerHTML == 1234) console.log("PIN został wprowadzony"); }, delDigit = function(){ if (inputLength >= 0) { onScreen.innerHTML = onScreen.innerHTML.slice(0, -1); inputLength--; } }; If you want to empty the screen at any moment you can insert onScreen.innerHTML = ''; anywhere ps: Thanks for the exercise and nice automat you made there.
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 password generator
I have the following JS code that checks a password strength and also creates a random password as well. What I want to do is edit the code so that instead of putting the generated password inside the password field it will put it inside a span tag with say an id of randompassword. In addition that I would like it so that by default there will be a random password inside the span tag and then when the user clicks the button it will generate another one. And also move the link to be next to span tag rather than the password box. Thanks. Here is the code: $.fn.passwordStrength = function( options ){ return this.each(function(){ var that = this;that.opts = {}; that.opts = $.extend({}, $.fn.passwordStrength.defaults, options); that.div = $(that.opts.targetDiv); that.defaultClass = that.div.attr('class'); that.percents = (that.opts.classes.length) ? 100 / that.opts.classes.length : 100; v = $(this) .keyup(function(){ if( typeof el == "undefined" ) this.el = $(this); var s = getPasswordStrength (this.value); var p = this.percents; var t = Math.floor( s / p ); if( 100 <= s ) t = this.opts.classes.length - 1; this.div .removeAttr('class') .addClass( this.defaultClass ) .addClass( this.opts.classes[ t ] ); }) .after('Generate Password') .next() .click(function(){ $(this).prev().val( randomPassword() ).trigger('keyup'); return false; }); }); function getPasswordStrength(H){ var D=(H.length); if(D>5){ D=5 } var F=H.replace(/[0-9]/g,""); var G=(H.length-F.length); if(G>3){G=3} var A=H.replace(/\W/g,""); var C=(H.length-A.length); if(C>3){C=3} var B=H.replace(/[A-Z]/g,""); var I=(H.length-B.length); if(I>3){I=3} var E=((D*10)-20)+(G*10)+(C*15)+(I*10); if(E<0){E=0} if(E>100){E=100} return E } function randomPassword() { var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!##$_+?%^&)"; var size = 10; var i = 1; var ret = "" while ( i <= size ) { $max = chars.length-1; $num = Math.floor(Math.random()*$max); $temp = chars.substr($num, 1); ret += $temp; i++; } return ret; } }; $(document) .ready(function(){ $('#password1').passwordStrength({targetDiv: '#iSM',classes : Array('weak','medium','strong')}); });
// you can use another improved version to generate password as follows //Define function wpiGenerateRandomNumber(length) { var i = 0; var numkey = ""; var randomNumber; while( i < length) { randomNumber = (Math.floor((Math.random() * 100)) % 94) + 33; if ((randomNumber >=33) && (randomNumber <=47)) { continue; } if ((randomNumber >=58) && (randomNumber <=90)) { continue; } if ((randomNumber >=91) && (randomNumber <=122)) { continue; } if ((randomNumber >=123) && (randomNumber <=126)) { continue; } i++; numkey += String.fromCharCode(randomNumber); } return numkey; } // Call var myKey=wpiGenerateRandomNumber(10); // 10=length alert(myKey); // Output 2606923083
This line: $(this).prev().val( randomPassword() ).trigger('keyup'); is inserting the value after a click. So you can change that value to stick the password wherever you want it. For example you could change it to: $('span#randompassword').html(randomPassword()); You could also run this when the page loads to stick something in that span right away: $(document).ready(function(){ $('span#randompassword').html(randomPassword()); });
//Very simple method to generate random number; can be use to generate random password key as well jq(document).ready( function() { jq("#genCodeLnk").click( function() { d = new Date(); t = d.getTime(); jq("#cstm_invitecode").val(t); }); });
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!