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.
So i have a form that let users upload pictures and youtube videos by URL.
I'm using jquery validation plugin to validate the URL of the images like this :
jQuery.validator.addMethod("complete_url", function(val, elem) {
// if no url, don't do anything
if (val.length == 0) { return true; }
// if user has not entered http:// https:// or ftp:// assume they mean http://
if(!/^(https?|ftp):\/\//i.test(val)) {
val = 'http://'+val; // set both the value
$(elem).val(val); // also update the form element
}
// now check if valid url
// http://docs.jquery.com/Plugins/Validation/Methods/url
// contributed by Scott Gonzalez: http://projects.scottsplayground.com/iri/
return /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*#)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|#)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|#)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|#)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|#)|\/|\?)*)?\.(gif|jpg|jpeg|png)$/i.test(val);
});
And then :
$( "#urlpostform" ).validate({
rules: {
imageurl: {
required: true,
complete_url: true
}
This is how i check that the submitted url ends in JPG|PNG|JPEG|GIF and its working.
Now i want to add the condition to validate if the submitted url is ether a Youtube video or an IMAGE.
This is the regex to check if submitted url is a youtube video:
^http:\/\/(?:www\.)?youtube.com\/watch\?(?=[^?]*v=\w+)(?:[^\s?]+)?$
But i don't know how to make it work together in the same input to validate ether youtube url or image url.
How can i accomplish this?
I have no means of testing but perhaps something like this:
jQuery.validator.addMethod("complete_url", function(val, elem) {
// if no url, don't do anything
if (val.length == 0) { return true; }
// if user has not entered http:// https:// or ftp:// assume they mean http://
if(!/^(https?|ftp):\/\//i.test(val)) {
val = 'http://'+val; // set both the value
$(elem).val(val); // also update the form element
}
var imgRegex = new Regex("/^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*#)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|#)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|#)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|#)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|#)|\/|\?)*)?\. (gif|jpg|jpeg|png))";
var youtubeRegex = new Regex("^http:\/\/(?:www\.)?youtube.com\/watch\?(?=[^?]*v=\w+)(?:[^\s?]+)?$");
//determine the url
if(imgRegex.test(val) == true)
return true;
else if(youtubeRegex.test(val) == true)
return true;
else
return false;
});
The above will first check if it is an image and if it isn't it will check if it is a Youtube URL. The other function remains the same:
$( "#urlpostform" ).validate({
rules: {
imageurl: {
required: true,
complete_url: true
}
Is this something like what you had in mind?
This worked too,
$.validator.addMethod("youtube_url",function(value, element) {
return this.optional(element) || /^https:\/\/(?:www\.)?youtube.com\/watch\?(?=[^?]*v=\w+)(?:[^\s?]+)?$/i.test(value);
},
"Invalid Youtube Url"
);
$( "#urlpostform" ).validate({
rules: {
imageurl: {
required: true,
youtube_url: true
}
im working on a flash game with django backend using swfobject to embed the swf into the view,
however when i do externalinterface.call() from flash in InternetExplorer(Chrome and Firefox are fine), it returns null
the flash game itself works perfectly
Django view and embed code:
<div id="game_container">
<div id='flashContent'></div>
</div>
<script type="text/javascript" src="swfobject.js"></script>
<script type='text/javascript'>
var flashvars={{flashvars|safe}};
var params={wmode:"opaque", allowscriptaccess:"always" };
var attributes={id:"flashContent", name:"flashContent"};
swfobject.embedSWF("{{SWF_URL}}", "flashContent", "{{ appsettings.SWF_WIDTH }}", "{{ appsettings.SWF_HEIGHT }}", "10.0.0", false, flashvars, params, attributes);
</script>
function fqlearn_isEventInteresting(data) {
ln_log(['isEventInteresting',data]);
if (!BASE_URL) BASE_URL = data.baseURL;
ln_log(['got lesson?',fqlearn_findLearningModule(data) != null]);
return fqlearn_findLearningModule(data) != null;
//shuld return either true or false.
}
Flash AS3 code:
var isInteresting:Object = false;
try {
isInteresting = ExternalInterface.call('fqlearn_isEventInteresting', data);
} catch (e:Error) {
trace("error calling external interface");
// Container does not support outgoing calls :/
rpc.forceLogUncaughtError("ExternalInterface.call problem",
e.name, e.toString(), e.getStackTrace());
rest.apply(restThis);
return;
} catch (e:SecurityError) {
// Security sandbox nonsense :/
throw e;
}
if (isInteresting == null) {
// Something went wrong :/
rpc.forceLogUncaughtError("ExternalInterface.call problem", "JS_returned_null_error");
}
if (isInteresting) {
trace("showing learning blackout")
dispatch(CoordinationEvent.newLEARNING_ABOUT_TO_SHOW());
learningPendingData = {
rest: rest,
restThis: restThis
};
ExternalInterface.call() from Flash in InternetExplorer(Chrome and Firefox are fine), it returns null . how do i fix this?
Fixed it: console.debug was choking up Internet Explorer. I removed those and it worked.
I'm looking for a JavaScript solution (or whatever else) that will refresh a webpage ONLY once, after 5 seconds it has been opened. Is this possible without being stuck in a refresh loop?
try this:
setTimeout(function ()
{
if (self.name != '_refreshed_'){
self.name = '_refreshed_';
self.location.reload(true);
} else {
self.name = '';
}
}, 5000);
You could do this in many different ways, but I think the easiest would be to add a query string to the url after the refresh, allowing us to tell if the refresh has already occurred:
//Function to get query string value. Source: http://www.bloggingdeveloper.com/post/JavaScript-QueryString-ParseGet-QueryString-with-Client-Side-JavaScript.aspx
function getQuerystring(key, default_){
if (default_==null) default_="";
key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
var qs = regex.exec(window.location.href);
if(qs == null)
return default_;
else
return qs[1];
}
//check if our query string is already set:
if(getQuerystring(r) !== 1){
setTimeout(function(){window.location.href = window.location.href + '?r=1'},5000)
}
If there is the possibility that a query string is already present, you will have to account for that and change the '?' to an '&'.
Sure, if you don't mind using jquery you can do it via an ajax call after waiting 5 seconds. Just throwing you some sample code:
How to wait 5 seconds with jQuery?
$(document).ready(function() {
// Get data
$.ajax({
url : '/tommyStockExchange/Data',
dataType : 'html',
data : {
'format' : 'H',
'type' : 'E'
},
success : function(data) {
$("#executions").html(data);
},
statusCode : {
404 : function() {
alert('executions url 404 :(');
}
}
});
});
Make it redirect to the same page with a different #hash and in JS only register the redirect if the hash isn't set.
You just need to pass some sort of data between page loads. This can be done in a multitude of ways — use a cookie, a URL query parameter, or something on the server side. Query parameter example:
if (!location.search.match(/(\?|&|^)stopRefreshing(=|&|$)/))
{
setTimeout(function ()
{
var search = location.search;
location.search = search ? search + '&stopRefreshing' : 'stopRefreshing';
}, 5000);
}
Demo: http://jsbin.com/ofawuz/edit
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.