I am trying to show/echo users location on a webpage using maxmind geoip2 paid plan, I also want to show different images based on the state/city names output.
For example, if my webpage shows the user is from New York, I would like to show a simple picture of New York, if the script detects the user is from Washington, the image should load for Washington.
This is the snippet I have tried but doesn't work.
<script type="text/javascript">
if
$('span#region=("New York")') {
// Display your image for New York
document.write("<img src='./images/NY.jpg'>");
}
else {
document.write("<img src='./images/different.jpg'>");
}
</script>
This is the code in the header.
<script src="https://js.maxmind.com/js/apis/geoip2/v2.1/geoip2.js" type="text/javascript"></script>
<script>
var onSuccess = function(geoipResponse) {
var cityElement = document.getElementById('city');
if (cityElement) {
cityElement.textContent = geoipResponse.city.names.en || 'Unknown city';
}
var countryElement = document.getElementById('country');
if (countryElement) {
countryElement.textContent = geoipResponse.country.names.en || 'Unknown country';
}
var regionElement = document.getElementById('region');
if (regionElement) {
regionElement.textContent = geoipResponse.most_specific_subdivision.names.en || 'Unknown region';
}
};
var onError = function(error) {
window.console.log("something went wrong: " + error.error)
};
var onLoad = function() {
geoip2.city(onSuccess, onError);
};
// Run the lookup when the document is loaded and parsed. You could
// also use something like $(document).ready(onLoad) if you use jQuery.
document.addEventListener('DOMContentLoaded', onLoad);
</script>
And this simple span shows the state name in body text of the Html when the page loads.
<span id="region"></span>
now the only issue is the image doesn't change based on users location, what am i doing wrong here?
Your example is missing some code, but it looks like you are running some code immediately and some code in a callback, a better way to do it is to have all the code in the callback:
// whitelist of valid image names
var validImages = ["NJ", "NY"];
// get the main image you want to replace
var mainImage = document.getElementById('mainImage');
if (mainImage) {
// ensure there is a subdivision detected, or load the default
if(geoipResponse.subdivisions[0].iso_code && validImages.includes( && geoipResponse.subdivisions[0].iso_code)){
mainImage.src = "./images/" + geoipResponse.subdivisions[0].iso_code + ".jpg";
} else {
mainImage.src = "./images/different.jpg";
}
}
Then just have the image you want to replace be:
<img src="data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs%3D" id="mainImage" />
Notes:
If you are using a responsive image, make sure your transparent gif is the same ratio height of to width as your final image to avoid page reflows.
You will have to load the different.jpg in the onError callback as well.
I want to route to a js file (may be static or dynamic).
The js file has format same thing:
(function() {
var img = new Image,
url = encodeURIComponent(document.location.href),
title = encodeURIComponent(document.title),
ref = encodeURIComponent(document.referrer);
img.src = '%s/a.gif?url=' + url + '&t=' + title + '&ref=' + ref;
})();
And from client I will run this script from header by:
<script async="" src="https://example.com/a.js"> </script>
without use staticfile, I think we can use it by urlpattern. But I don't know use for javascript file.
I found a solution.
in views.py:
def generatejs(request):
js_str="""
(function() {
var img = new Image,
url = encodeURIComponent(document.location.href),
title = encodeURIComponent(document.title),
ref = encodeURIComponent(document.referrer);
img.src = 'http://127.0.0.1:8000/a.gif?url=' + url + '&t=' + title + '&ref=' + ref;
})();
"""
return HttpResponse(js_str)
And In urlpatterns, insert:
url(r'^gtag/js', collector.generatejs),
My client has asked me to integrate a Wufoo form into their Ember application, and provided the following JS (anonymized):
<script type="text/javascript">var abc123;(function(d, t) {
var s = d.createElement(t), options = {
'userName':'example',
'formHash':'abc123',
'autoResize':true,
'height':'491',
'async':true,
'host':'wufoo.com',
'header':'show',
'ssl':true};
s.src = ('https:' == d.location.protocol ? 'https://' : 'http://') + 'www.wufoo.com/scripts/embed/form.js';
s.onload = s.onreadystatechange = function() {
var rs = this.readyState; if (rs) if (rs != 'complete') if (rs != 'loaded') return;
try { abc123 = new WufooForm();abc123.initialize(options);abc123.display(); } catch (e) {}};
var scr = d.getElementsByTagName(t)[0], par = scr.parentNode; par.insertBefore(s, scr);
})(document, 'script');</script>
I've tried including it in index.html and also creating a custom component, but keep getting an error from Wufoo:
TypeError: Cannot set property 'innerHTML' of null
Is there a way to use the provided Wufoo JS in an Ember.js app?
I have developed a provider hosted app in SharePoint 2013. As you already know, Visual Studio creates web application and SharePoint app. The web application gets hosted inside IIS and the SharePoint App in SharePoint site collection. I'm trying to get data from a list hosted in SharePoint using CSOM. But I get ran insecure content error.
"[blocked] The page at 'https://localhost:44302/Pages/Default.aspx?SPHostUrl=http%3A%2F%2Fecontent&0319c41%2Eecontent%2Eelibrary%2Eapps%2Elocal%2FSharePointApp2%5Fsingeltest'
was loaded over HTTPS, but ran insecure content from 'http://apps-892db5a0319c41.econtent.elibrary.apps.local/sharepointapp2_singeltest/_layouts/15/AppWebProxy.aspx': this content should also be loaded over HTTPS."
here is my code in Default.aspx
<script type="text/javascript" src="../Scripts/jquery-1.8.2.js"></script>
<script type="text/javascript" src="../Scripts/MicrosoftAjax.js"></script>
<script type="text/javascript" src="../Scripts/SP.Core.js"></script>
<script type="text/javascript" src="../Scripts/INIT.JS"></script>
<script type="text/javascript" src="../Scripts/SP.Runtime.js"></script>
<script type="text/javascript" src="../Scripts/SP.js"></script>
<script type="text/javascript" src="../Scripts/SP.RequestExecutor.js"></script>
<script type="text/javascript" src="../Scripts/App.js"></script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<input id="Button1" type="button" value="Get title via CSOM" onclick="execCSOMTitleRequest()" /> <br />
<input id="Button2" type="button" value="Get Lists via CSOM" onclick="execCSOMListRequest()" />
</div>
<p ID="lblResultTitle"></p><br />
<p ID="lblResultLists"></p>
</form>
</body>
</html>
and App.js is:
var hostwebUrl;
var appwebUrl;
// Load the required SharePoint libraries
$(document).ready(function () {
//Get the URI decoded URLs.
hostwebUrl =
decodeURIComponent(
getQueryStringParameter("SPHostUrl")
);
appwebUrl =
decodeURIComponent(
getQueryStringParameter("SPAppWebUrl")
);
// resources are in URLs in the form:
// web_url/_layouts/15/resource
var scriptbase = hostwebUrl + "/_layouts/15/";
// Load the js files and continue to the successHandler
//$.getScript(scriptbase + "/MicrosoftAjax.js",
// function () {
// $.getScript(scriptbase + "SP.Core.js",
// function () {
// $.getScript(scriptbase + "INIT.JS",
// function () {
// $.getScript(scriptbase + "SP.Runtime.js",
// function () {
// $.getScript(scriptbase + "SP.js",
// function () { $.getScript(scriptbase + "SP.RequestExecutor.js", execCrossDomainRequest); }
// );
// }
// );
// });
// });
// });
});
function execCrossDomainRequest() {
alert("scripts loaded");
}
function getQueryStringParameter(paramToRetrieve) {
var params = document.URL.split("?")[1].split("&");
var strParams = "";
for (var i = 0; i < params.length; i = i + 1) {
var singleParam = params[i].split("=");
if (singleParam[0] == paramToRetrieve)
return singleParam[1];
}
}
function execCSOMTitleRequest() {
var context;
var factory;
var appContextSite;
var collList;
//Get the client context of the AppWebUrl
context = new SP.ClientContext(appwebUrl);
//Get the ProxyWebRequestExecutorFactory
factory = new SP.ProxyWebRequestExecutorFactory(appwebUrl);
//Assign the factory to the client context.
context.set_webRequestExecutorFactory(factory);
//Get the app context of the Host Web using the client context of the Application.
appContextSite = new SP.AppContextSite(context, hostwebUrl);
//Get the Web
this.web = context.get_web();
//Load Web.
context.load(this.web);
context.executeQueryAsync(
Function.createDelegate(this, successTitleHandlerCSOM),
Function.createDelegate(this, errorTitleHandlerCSOM)
);
//success Title
function successTitleHandlerCSOM(data) {
$('#lblResultTitle').html("<b>Via CSOM the title is:</b> " + this.web.get_title());
}
//Error Title
function errorTitleHandlerCSOM(data, errorCode, errorMessage) {
$('#lblResultLists').html("Could not complete CSOM call: " + errorMessage);
}
}
function execCSOMListRequest() {
var context;
var factory;
var appContextSite;
var collList;
//Get the client context of the AppWebUrl
context = new SP.ClientContext(appwebUrl);
//Get the ProxyWebRequestExecutorFactory
factory = new SP.ProxyWebRequestExecutorFactory(appwebUrl);
//Assign the factory to the client context.
context.set_webRequestExecutorFactory(factory);
//Get the app context of the Host Web using the client context of the Application.
appContextSite = new SP.AppContextSite(context, hostwebUrl);
//Get the Web
this.web = context.get_web();
// Get the Web lists.
collList = this.web.get_lists();
//Load Lists.
context.load(collList);
context.executeQueryAsync(
Function.createDelegate(this, successListHandlerCSOM),
Function.createDelegate(this, errorListHandlerCSOM)
);
//Success Lists
function successListHandlerCSOM() {
var listEnumerator = collList.getEnumerator();
$('#lblResultLists').html("<b>Via CSOM the lists are:</b><br/>");
while (listEnumerator.moveNext()) {
var oList = listEnumerator.get_current();
$('#lblResultLists').append(oList.get_title() + " (" + oList.get_itemCount() + ")<br/>");
}
}
//Error Lists
function errorListHandlerCSOM(data, errorCode, errorMessage) {
$('#lblResultLists').html("Could not complete CSOM Call: " + errorMessage);
}
};
Any solution is appreciated.
well first off, i can tell you your decodeURIComponent logic isnt working.
Yours:https://localhost:44302/Pages/Default.aspx?SPHostUrl=http%3A%2F%2Fecontent&0319c41%2Eecontent%2Eelibrary%2Eapps%2Elocal%2FSharePointApp2%5Fsingeltest
Mine: https://localhost:44302/Pages/Default.aspx?SPHostUrl=http://econtent&0319c41.econtent.elibrary.apps.local/SharePointApp2_singeltest
Secondly, is the HostURL content supposed to be unsecure? If so, then you may want to change your browser settings. If not, then you need to see why your HostURL is in the Anonymous Zone but your AppURL is in the Secure Zone.
In either case, verify that Everyone has at least Read Access to the location your trying to pull from.
Last thing to do, is to setup a Trusted Host Location if you have access to the Admin Center.
Here is a code snippet for what i used to test:
$(document).ready(function () {
$.getScript(qsHostUrl + "/_layouts/15/SP.RequestExecutor.js", getHostInfo);
function getHostInfo() {
var ctxApp = new SP.ClientContext(qsAppUrl);
var factory = new SP.ProxyWebRequestExecutorFactory(qsAppUrl);
ctxApp.set_webRequestExecutorFactory(factory);
var ctxHost = new SP.AppContextSite(ctxApp, qsHostUrl);
var web = ctxHost.get_web();
ctxApp.load(web);
ctxApp.executeQueryAsync(
Function.createDelegate(this, getHostInfoSuccess),
Function.createDelegate(this, getHostInfoError)
);
function getHostInfoSuccess(sender, args) {
lblData.html(
'Title: ' + web.get_title() + '<br/>' +
'Description: ' + web.get_description()
);
}
function getHostInfoError(sender, args) {
lblData.html(
'Request Failed: ' + args.get_message() + '\n' +
'Stacktrace: ' + args.get_stackTrace()
);
}
}
}
I am working on a new project and have been trying to get a JS controller to decide which dojo widgets are needed for any particular page.
I have this working, but only when I inject / hardcode the dojo widget's JS into the page. As soon as I try to get it working with dojo's provide and require mechanisms, everything stops working and I get the following error:
Could not load 'pf.PasswordStrength'; last tried '../dojopf/widget/PasswordStrength.js'
http://pf-dev-ad/wcsstore/js/dojo131/dojo/dojo.js
Line 16
Firebug shows this error right after it includes the file!
I am having real problems with this as dojo 1.3.1 (which I'm not allowed to upgrade) is very poorly documented and there aren't many tutorials.
The requirement is as follows:
1 site-wide JS controller (lib.js)
1 widget specific JS file (PasswordStrength.js)
1 widget template file (PasswordStrength.html)
1 pointer node
The file structre is setup as follows:
js
dojo131
dijit
dojo
dojotest
widget
templates
PasswordStrength.html
PasswordStrength.css
PasswordStrength.js
dojox
//JS controller (lib.js):
if(!ad){ var ad = {} }
ad.base = new (function(){
// init function will run on page load. Called by dojo.addOnLoad
this.init = function (){
/* This function acts as a controller for Dojo widgets.
// it uses a variable ('pageName') set by the JSTL in the parent JSP of a particular page
switch(ad.pageName){
case 'Home':
_getTemplateAssets('PasswordStrength');
break;
}
}
var $ = dojo.query;
var templatePath = 'js/dojo131/dojotest/widget';
var debug = false; // This should be set to false when on production
/*** PRIVATE FUNCTIONS ***/
function _getTemplateAssets(templateName){
// Injects the JS and CSS template assets into the page head
dojo.registerModulePath("ad", '../dojotest/widget'); // relative to dojo.js
//dojo.provide('ad.' + templateName);
dojo.require('ad.' + templateName);
//var headTag = document.getElementsByTagName('head').item(0);
//dojo.create("script", { src: templatePath + '/' + templateName + '.js', type: 'text/javascript' }, headTag);
//dojo.create("link", { href: templatePath + '/templates/' + templateName + '.css', type: 'text/css', rel: 'stylesheet' }, headTag);
}
});
/*** ONLOAD ***/
dojo.addOnLoad(ad.base.init);
// Widget JS (PasswordStrength.js)
if(!ad){ var ad = {} }
ad.passwordCheck = new (function(){
// init function will run on page load. Called by dojo.addOnLoad
this.init = function (){
_temp_addPasswordCheck();
}
/*** PRIVATE VARIABLES ***/
var $ = dojo.query;
var templateName = 'PasswordStrength';
var insertPointID = 'ins_passStrength';
var minLength = 6;
var objAdvice = { enterPass: 'Please enter a password', addChars: 'Add more characters (min ' + minLength + ')', addSpecials: 'Use special characters (!##$%^&*)', addUppers: 'Use some upper case characters', addLowers: 'Use some lower case characters', addNums: 'Use some numbers', remRepeats: 'Too many repeated repeat characters', passPass: 'Your password has been verified as Excellent!' };
var complexity = ['Bad', 'Very weak', 'Weak', 'Good', 'Strong', 'Excellent'];
var content = {
titles: {
h1: 'Password Strength'
},
labels: {
password: 'Password:',
confirmPassword: 'Confirm Password',
obscure: 'Obscure:',
strength: 'Password strength:',
advice: 'Advice:'
},
content:{
advice: 'Please enter a password',
strength: 'None'
}
}
/*** PRIVATE FUNCTIONS ***/
function _temp_addPasswordCheck(){
// Include extras
dojo.provide("ad.PasswordStrength");
dojo.require("ad.PasswordStrength");
dojo.require("dijit._Widget");
dojo.require("dijit._Templated");
dojo.require("dojo.parser");
dojo.declare(templateName, [dijit._Widget, dijit._Templated], {
// calls the HTML template to be used
templatePath: dojo.moduleUrl ('dojotest.widget','templates/' + templateName + '.html'),
// Content (titles, labels and general content)
label_password: content.labels.password,
label_confirmPassword: content.labels.confirmPassword,
label_obscure: content.labels.obscure,
label_passwordStrength: content.labels.strength,
label_advice: content.labels.advice,
title_passwordStrength: content.titles.h1,
content_advice: content.content.advice,
content_strength: content.content.strength,
obscurePassword: function(){
if(this.obscurePass.checked){ dojo.attr(this.passwordValue, 'type', 'password'); }
else{ dojo.attr(this.passwordValue, 'type', 'text'); }
},
checkPassword: function(){
// This function checks the password strength on keyup and alters the passwordAdvice div to reflect the strength of the password entered
// Runs the password through a validation function which returns the results
var results = _checkPassWord(this.passwordValue.value), score = results['score'];
var ele = dojo.byId('passStrength');
// Update the markup to inform the user of their passwords score
if(results['count'] == 0){
this.complexity.innerHTML = 'None';
ele.className = '';
this.advice.innerHTML = _doInsert([objAdvice.enterPass]);
}
else if(score <= 50){
this.complexity.innerHTML = complexity[0];
ele.className = 'bad';
this.advice.innerHTML = _doInsert(results.advice);
}
if(score == 60){
this.complexity.innerHTML = complexity[1];
ele.className = 'veryWeak';
this.advice.innerHTML = _doInsert(results.advice);
}
if(score == 70){
this.complexity.innerHTML = complexity[2];
ele.className = 'weak';
this.advice.innerHTML = _doInsert(results.advice);
}
if(score == 80){
this.complexity.innerHTML = complexity[3];
ele.className = 'good';
this.advice.innerHTML = _doInsert(results.advice);
}
if(score == 90){
this.complexity.innerHTML = complexity[4];
ele.className = 'strong';
this.advice.innerHTML = _doInsert(results.advice);
}
if(score >= 100){
this.complexity.innerHTML = complexity[5];
ele.className = 'excellent';
this.advice.innerHTML = _doInsert([objAdvice.passPass]);
}
}
});
// Calls the template into the right ID defined as the insert point as the first child
if(dojo.byId(insertPointID)){
var passStrength = new PasswordStrength().placeAt(insertPointID);
}
};
function _doInsert(arrInsert){
var content = '';
dojo.forEach(arrInsert, function(item, i){
content = content + '<p>' + item + '</p>';
});
return content;
}
function _checkPassWord(strPassword){
// Grades the password string and returns the results
var objResults = {}, scoreFactor = 10, score = 0, advice = [], lengthPass, alphaLCpass, alphaUCpass, numPass, specialsPass, repeatPass, count = strPassword.length;
// Check password string for uppercase alphas, lowercase alphas, numerals, special characters and repeated characters
alphaUCpass = strPassword.match(/[A-Z]/g) ? true : false;
alphaLCpass = strPassword.match(/[a-z]/g) ? true : false;
numPass = strPassword.match(/[0-9]/g) ? true: false;
specialsPass = strPassword.match(/[^a-zA-Z0-9]/g) ? true : false;
repeatPass = strPassword.match(/(.)\1\1/g) ? false : true;
lengthPass = count >= minLength ? true : false;
// Score the password based on the results of the check
if(alphaUCpass){ score += scoreFactor; }
else{ advice.push(objAdvice.addUppers); }
if(alphaLCpass){ score += scoreFactor; }
else{ advice.push(objAdvice.addLowers); }
if(numPass){ score += scoreFactor; }
else{ advice.push(objAdvice.addNums); }
if(specialsPass){ score += scoreFactor; }
else{ advice.push(objAdvice.addSpecials); }
if(repeatPass){ score += scoreFactor; }
else{ advice.push(objAdvice.remRepeats); }
if(lengthPass){ score += scoreFactor * 5; }
else{ advice.push(objAdvice.addChars); }
// Inserts the results into object to be returned
objResults = {
'alphaUC': alphaUCpass,
'alphaLC': alphaLCpass,
'numerals': numPass,
'specials': specialsPass,
'length': lengthPass,
'repeat': repeatPass,
'count': count,
'score': score,
'advice': advice
}
// Return results to parent function
return objResults;
}
/*** PUBLIC FUNCTIONS ***/
});
/*** ONLOAD ***/
dojo.addOnLoad(ad.passwordCheck.init);
// Widget HTML template (PasswordStrength.html)
<div>
<h1>${title_passwordStrength}</h1>
<form method="post" action="">
<fieldset>
<div class="formFields">
<label for="password">${label_password}</label>
<input type="password" name="password" id="password" dojoAttachPoint="passwordValue" dojoAttachEvent="onkeyup: checkPassword" />
</div>
<div class="formFields">
<label for="confirmPassword">${label_confirmPassword}</label>
<input type="password" name="confirmPassword" id="confirmPassword" dojoAttachPoint="passwordConfirmValue" dojoAttachEvent="onkeyup: checkPassword" />
</div>
<div class="formFields">
<label for="obscurePassword" class="wAuto">${label_obscure}</label>
<input class="wAuto" type="checkbox" value="true" checked="checked" name="obscurePassword" id="obscurePassword" dojoAttachPoint="obscurePass" dojoAttachEvent="onchange: obscurePassword" />
</div>
<div class="formFields">
<label>${label_passwordStrength}</label>
<div dojoAttachPoint="strength" id="passStrength" class=""></div>
<div dojoAttachPoint="complexity" id="passStrengthCaption">${content_strength}</div>
</div>
<div class="formFields">
<label>${label_advice}</label>
<div dojoAttachPoint="advice" id="passAdvice"><p>${content_advice}</p></div>
</div>
</fieldset>
</form>
The parent file has a HTML pointer in it as follows:
<div id="ins_passStrength" dojoType="PasswordStrength"></div>
If I change the following function in parent controller (lib.js):
function _getTemplateAssets(templateName){
// Injects the JS and CSS template assets into the page head
dojo.registerModulePath("ad", '../dojotest/widget'); // relative to dojo.js
//dojo.provide('ad.' + templateName);
dojo.require('ad.' + templateName);
//var headTag = document.getElementsByTagName('head').item(0);
//dojo.create("script", { src: templatePath + '/' + templateName + '.js', type: 'text/javascript' }, headTag);
//dojo.create("link", { href: templatePath + '/templates/' + templateName + '.css', type: 'text/css', rel: 'stylesheet' }, headTag);
}
To:
function _getTemplateAssets(templateName){
// Injects the JS and CSS template assets into the page head
dojo.registerModulePath("ad", '../dojotest/widget'); // relative to dojo.js
dojo.provide('ad.' + templateName);
dojo.require('ad.' + templateName);
//var headTag = document.getElementsByTagName('head').item(0);
//dojo.create("script", { src: templatePath + '/' + templateName + '.js', type: 'text/javascript' }, headTag);
//dojo.create("link", { href: templatePath + '/templates/' + templateName + '.css', type: 'text/css', rel: 'stylesheet' }, headTag);
}
The error goes away but the widegt JS isn't included.
And if you change it to:
function _getTemplateAssets(templateName){
// Injects the JS and CSS template assets into the page head
dojo.registerModulePath("ad", '../dojotest/widget'); // relative to dojo.js
//dojo.provide('ad.' + templateName);
//dojo.require('ad.' + templateName);
var headTag = document.getElementsByTagName('head').item(0);
dojo.create("script", { src: templatePath + '/' + templateName + '.js', type: 'text/javascript' }, headTag);
dojo.create("link", { href: templatePath + '/templates/' + templateName + '.css', type: 'text/css', rel: 'stylesheet' }, headTag);
}
It works fine but this is a dirty sidestep... I need to use dojo's prescribed methods.
Any help greatly appreciated.
Thank you!
I believe your error is that you have put your dojo.provide("ad.PasswordStrength") inside a bunch of functions. It needs to be at the top of the file. Dojo evaluates the file it believes to be correct (based on module path), but how is it supposed to know if PasswordStrength is in there, unless you tell it "yes, this file provides ad.PasswordStrength".
Edit: considering what you said on IRC, here's how I think PasswordStrength.js should look:
dojo.provide("ad.PasswordStrength");
if(!ad){ var ad = {} }
ad.passwordCheck = new (function(){
// init function will run on page load. Called by dojo.addOnLoad
this.init = function (){
_temp_addPasswordCheck();
dojo.parser.parse();
}
/*** PRIVATE VARIABLES ***/
var $ = dojo.query;
var templateName = 'PasswordStrength';
....
/*** PRIVATE FUNCTIONS ***/
function _temp_addPasswordCheck(){
// Include extras
dojo.require("dijit._Widget");
dojo.require("dijit._Templated");
dojo.require("dojo.parser");
dojo.declare("ad." + templateName, [dijit._Widget, dijit._Templated], {
// calls the HTML template to be used
templatePath: dojo.moduleUrl ('dojotest.widget','templates/' + templateName + '.html'),
// Content (titles, labels and general content)
label_password: content.labels.password,
label_confirmPassword: content.labels.confirmPassword,
label_obscure: content.labels.obscure,
label_passwordStrength: content.labels.strength,
label_advice: content.labels.advice,
title_passwordStrength: content.titles.h1,
content_advice: content.content.advice,
content_strength: content.content.strength,
obscurePassword: function(){
....
},
checkPassword: function(){
....
}
});
/*
if(dojo.byId(insertPointID)){
var passStrength = new PasswordStrength().placeAt(insertPointID);
}
*/
};
function _doInsert(arrInsert){
....
}
function _checkPassWord(strPassword){
....
}
/*** PUBLIC FUNCTIONS ***/
});
/*** ONLOAD ***/
dojo.addOnLoad(ad.passwordCheck.init);
Moved dojo.provide("ad.PasswordStrength"); to the top of the file.
Removed dojo.require("ad.PasswordStrength"); from _temp_addPasswordCheck() - if this code is executed, ad.PasswordStrength (PasswordStrength.js) has obviously already been required and loaded.
Added dojo.parser.parse(); to the end of init(), so that after the widget has been declared, any widget dojoTypes in the HTML will be parsed. However, I still don't understand why you have to declare the widget inside _temp_addPasswordCheck. Why not have the widget in it's on file, and ad.passwordCheck wherever your applications other "page" files are?
Added "ad." to the widget declaration (dojo.declare("ad." + templateName)), it needs to have the full namespaced name here.
Commented out new PasswordStrength().placeAt(.... Since you want to insert your widgets declaratively in your HTML, it doesn't make sense to manually instantiate one here, and place it manually.
Now you should be able to put PasswordStrength widgets in your HTML, like so:
<script type="text/javascript" src="js/dojo131/dojo/dojo.js"></script>
<script type="text/javascript" src="js/dojo131/dojotest/lib.js"></script>
....
<div id="ins_passStrength" dojoType="ad.PasswordStrength"></div>
<div id="anotherOne" dojoType="ad.PasswordStrength"></div>
Remember that you need the whole namespaced name here as well (i.e. the ad. prerfix).
This worked nicely for me, using Dojo 1.3.3. Uploaded the sandbox if it's any use.
Your error:
Could not load 'pf.PasswordStrength'; last tried '../dojopf/widget/PasswordStrength.js'
http://pf-dev-ad/wcsstore/js/dojo131/dojo/dojo.js
Line 16
Is this a typo? Because it should be trying ../dojotest/widget/PasswordStrength.js
Do you have another dojo.require that is referring to dojopf? Or any other line like dojo.require("pf.PasswordStrength")?
If not, perhaps the registering of the module path is not happening before dojo tries to load your .js. Perhaps try using dojo.require to load your lib.js.