When I run the javascript code below, it load specified amount of images from Flickr.
By var photos = photoGroup.getPhotos(10) code, I get 10 images from cache.
Then, I can see the object has exactly 10 items by checking console.log(photos);
But actual image appeared on the page is less than 10 items...
I have no idea why this work this way..
Thank you in advance.
<html>
<head>
<script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<script>
var PhotoGroup = function(nativePhotos, callback) {
var _cache = new Array();
var numberOfPhotosLoaded = 0;
var containerWidth = $("#contents").css('max-width');
var containerHeight = $("#contents").css('max-height');
$(nativePhotos).each(function(key, photo) {
$("<img src='"+"http://farm" + photo["farm"] + ".staticflickr.com/" + photo["server"] + "/" + photo["id"] + "_" + photo["secret"] + "_b.jpg"+"'/>")
.attr("alt", photo['title'])
.attr("data-cycle-title", photo['ownername'])
.load(function() {
if(this.naturalWidth >= this.naturalHeight) {
$(this).attr("width", containerWidth);
} else {
$(this).attr("height", containerHeight);
}
_cache.push(this);
if(nativePhotos.length == ++numberOfPhotosLoaded)
callback();
})
});
var getRandom = function(max) {
return Math.floor((Math.random()*max)+1);
}
this.getPhotos = function(numberOfPhotos) {
var photoPool = new Array();
var maxRandomNumber = _cache.length-1;
while(photoPool.length != numberOfPhotos) {
var index = getRandom(maxRandomNumber);
if($.inArray(_cache[index], photoPool))
photoPool.push(_cache[index]);
}
return photoPool;
}
}
var Contents = function() {
var self = this;
var contentTypes = ["#slideShowWrapper", "#video"];
var switchTo = function(nameOfContent) {
$(contentTypes).each(function(contentType) {
$(contentType).hide();
});
switch(nameOfContent) {
case("EHTV") :
$("#video").show();
break;
case("slideShow") :
$("#slideShowWrapper").show();
break;
default :
break;
}
}
this.startEHTV = function() {
switchTo("EHTV");
document._video = document.getElementById("video");
document._video.addEventListener("loadstart", function() {
document._video.playbackRate = 0.3;
}, false);
document._video.addEventListener("ended", startSlideShow, false);
document._video.play();
}
this.startSlideShow = function() {
switchTo("slideShow");
var photos = photoGroup.getPhotos(10)
console.log(photos);
$('#slideShow').html(photos);
}
var api_key = '6242dcd053cd0ad8d791edd975217606';
var group_id = '2359176#N25';
var flickerAPI = 'http://api.flickr.com/services/rest/?jsoncallback=?';
var photoGroup;
$.getJSON(flickerAPI, {
api_key: api_key,
group_id: group_id,
format: "json",
method: "flickr.groups.pools.getPhotos",
}).done(function(data) {
photoGroup = new PhotoGroup(data['photos']['photo'], self.startSlideShow);
});
}
var contents = new Contents();
</script>
</head>
<body>
<div id="slideShow"></div>
</body>
</html>
I fix your method getRandom() according to this article, and completely re-write method getPhotos():
this.getPhotos = function(numberOfPhotos) {
var available = _cache.length;
if (numberOfPhotos >= available) {
// just clone existing array
return _cache.slice(0);
}
var result = [];
var indices = [];
while (result.length != numberOfPhotos) {
var r = getRandom(available);
if ($.inArray(r, indices) == -1) {
indices.push(r);
result.push(_cache[r]);
}
}
return result;
}
Check full solution here: http://jsfiddle.net/JtDzZ/
But this method still slow, because loop may be quite long to execute due to same random numbers occurred.
If you care about performance, you need to create other stable solution. For ex., randomize only first index of your images sequence.
Related
Below is my code. if we use set timeout function we got all data but we not use we are not getting inspection data which is coming from my local db. i want use deferred and promises in my code. Thanks in advance.
function onclickToCall() {
this.$('.check-list > .check-list-box').each(function (i) {
var j = i + 1;
var answer_req = $(this).attr("data-isReq");
var checklist_guid = $(this).attr("data-guid");
var question_type = $(this).attr("data-type");
var yes_no = $("input:radio[name='radio_" + j + "']:checked").val();
var notes = $(this).find('#txtAreaNotes_' + j).val();
var attachment_url = $(this).find(".txtCameraImage").attr("data-path");
var appConfig = DriverConnectApp.State.get('config_settings');
var item = {};
item.checklist_guid = checklist_guid;
item.yes_no = yes_no;
item.attachment_url = attachment_url;
item.notes = notes;
if (question_type == 2) { // For Vehical visual inspection
var dataPromise = that.getInspectionData(checklist_guid);
dataPromise.done(function (response, vh_image) {
var inspectionItem = {};
inspectionItem.vh_url = vh_image;
inspectionItem.details = response;
item.vh_inspection = inspectionItem;
that.detailsArr.push(item);
});
} else {
item.vh_inspection = {};
that.detailsArr.push(item);
}
});
// after finish and push all data we need to call function here
test();
}
getInspectionData: function (checklist_guid) {
var that = this;
var deferred = $.Deferred();
that.dbchecklist.getVehicleInspectionlist(checklist_guid, function (data, res) {
var details = [];
if (data.length) {
var img = data[0].vh_image;
var arr = JSON.parse(data[0].vh_details);
for (var k = 0; k < arr.length; k++) {
var items = {};
items.number = arr[k].number;
items.notes = arr[k].notes;
items.attachment_url = arr[k].attachment_url;
details.push(items);
}
deferred.resolve(details, img);
} else {
deferred.resolve(details, img);
}
});
return deferred.promise();
}
I am looking to query any attachments of layers based on the results of an Identify Task. If there are attachments on the layer, I would like to add the links to the bottom of the infoTemplate.
I am having trouble working the multiple dojo Deferred objects. I know they are being resolved because the return values are logged in the console, but my infoWindow is never populated.
So what is the proper way to deal with several nested deferreds? Deferred Lists seem to be a step in the right direction, but I am unsure how I would format one in this situation.
Thanks,
Joe
Update:
I have updated my working code below.
map.on('click',executeIdentify);
function executeIdentify(evt) {
identifyParams.width = map.width;
identifyParams.height = map.height;
identifyParams.geometry = evt.mapPoint;
identifyParams.mapExtent = map.extent;
var deferred = identifyTask.execute(identifyParams);
deferred.addCallback(function(deferredResult){
var promiseList = []
var features = array.map(deferredResult,function(result) {
var feature = result.feature;
var content = "";
array.forEach(Object.keys(feature.attributes),function(attr) {
content += attr + ": " + feature.attributes[attr] + "<br>"
});
var url = identifyTask.url + "/" + result.layerId + "/" + result.feature.attributes.OBJECTID + "/attachments?f=json"
var req = esriRequest({url:url}).then(function(newDef) {
if (Object.keys(newDef).toString() == "attachmentInfos,_ssl") {
content += "<br><b>Attachments:</b><hr>"
array.forEach(newDef.attachmentInfos,function(attach) {
content += "<a href=" + identifyTask.url + "/" + result.layerId + "/" + result.feature.attributes.OBJECTID + "/attachments/" + attach.id + " target='_blank'>" + attach.name + "</a><br>"
})
}
content += "<br><br>";
console.log(result)
feature.infoTemplate = new InfoTemplate(result.layerName + " " + result.feature.attributes.OBJECTID,content)
// console.log(feature)
return feature
},function(newDef) {
feature.infoTemplate = new InfoTemplate(result.layerName + " " + result.feature.attributes.OBJECTID,content);
// console.log(feature)
return feature
});
promiseList.push(req);
});
var promiseAll = new all(promiseList)
promiseAll.then(function(r) {promiseFun(r)})
})
function promiseFun(r) {
map.infoWindow.setFeatures(r);
map.infoWindow.show(evt.mapPoint);
}
}
You should look at using dojo/promise/all to handle multiple deferred results. Here's an example that uses it to return the results from multiple services, with some extra code to identify which service the result is coming from.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<!--The viewport meta tag is used to improve the presentation and behavior of the samples
on iOS devices-->
<meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no">
<title>Identify with Popup</title>
<link rel="stylesheet" href="http://js.arcgis.com/3.8/js/esri/css/esri.css">
<style>
html, body, #map {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
}
</style>
<script>var dojoConfig = { parseOnLoad: true };</script>
<script src="http://js.arcgis.com/3.8/"></script>
<script>
var map;
var identifyTask, identifyParams, idPoint;
var identifyResults;
require([
"esri/map", "esri/dijit/Popup", "dojo/promise/all", "dojo/domReady!"
], function (
Map, Popup, All
) {
var popup = new Popup({
fillSymbol: new esri.symbol.SimpleFillSymbol(esri.symbol.SimpleFillSymbol.STYLE_SOLID, new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([255, 0, 0]), 2), new dojo.Color([255, 255, 0, 0.25]))
}, dojo.create("div"));
map = new Map("map", {
basemap: "satellite",
center: [-83.275, 42.573],
zoom: 18,
infoWindow: popup
});
dojo.connect(map, "onLoad", mapReady);
var landBaseLayer = new esri.layers.ArcGISDynamicMapServiceLayer("http://sampleserver3.arcgisonline.com/ArcGIS/rest/services/BloomfieldHillsMichigan/Parcels/MapServer", { opacity: .55 });
map.addLayer(landBaseLayer);
var militaryLayer = new esri.layers.ArcGISDynamicMapServiceLayer("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Military/MapServer", { opacity: .55 });
map.addLayer(militaryLayer);
function mapReady(map) {
dojo.connect(map, "onClick", runIdentifies);
}
function runIdentifies(evt) {
identifyResults = [];
idPoint = evt.mapPoint;
var layers = dojo.map(map.layerIds, function (layerId) {
return map.getLayer(layerId);
});
layers = dojo.filter(layers, function (layer) {
if (layer.visibleLayers[0] !== -1) {
return layer.getImageUrl && layer.visible
}
}); //Only dynamic layers have the getImageUrl function. Filter so you only query visible dynamic layers
var tasks = dojo.map(layers, function (layer) {
return new esri.tasks.IdentifyTask(layer.url);
}); //map each visible dynamic layer to a new identify task, using the layer url
var defTasks = dojo.map(tasks, function (task) {
return new dojo.Deferred();
}); //map each identify task to a new dojo.Deferred
var params = createIdentifyParams(layers, evt);
var promises = [];
for (i = 0; i < tasks.length; i++) {
promises.push(tasks[i].execute(params[i])); //Execute each task
}
var allPromises = new All(promises);
allPromises.then(function (r) { showIdentifyResults(r, tasks); });
}
function showIdentifyResults(r, tasks) {
var results = [];
var taskUrls = [];
r = dojo.filter(r, function (result) {
return r[0];
});
for (i = 0; i < r.length; i++) {
results = results.concat(r[i]);
for (j = 0; j < r[i].length; j++) {
taskUrls = taskUrls.concat(tasks[i].url);
}
}
results = dojo.map(results, function (result, index) {
var feature = result.feature;
var layerName = result.layerName;
var serviceUrl = taskUrls[index];
feature.attributes.layerName = result.layerName;
var template = new esri.InfoTemplate("", "Service Url: " + serviceUrl + "<br/><br/>Layer name: " + result.layerName + "<br/><br/> Object Id: ${OBJECTID}");
feature.setInfoTemplate(template);
var resultGeometry = feature.geometry;
var resultType = resultGeometry.type;
return feature;
});
if (results.length === 0) {
map.infoWindow.clearFeatures();
} else {
map.infoWindow.setFeatures(results);
}
map.infoWindow.show(idPoint);
return results;
}
function createIdentifyParams(layers, evt) {
var identifyParamsList = [];
identifyParamsList.length = 0;
dojo.forEach(layers, function (layer) {
var idParams = new esri.tasks.IdentifyParameters();
idParams.width = map.width;
idParams.height = map.height;
idParams.geometry = evt.mapPoint;
idParams.mapExtent = map.extent;
idParams.layerOption = esri.tasks.IdentifyParameters.LAYER_OPTION_VISIBLE;
var visLayers = layer.visibleLayers;
if (visLayers !== -1) {
var subLayers = [];
for (var i = 0; i < layer.layerInfos.length; i++) {
if (layer.layerInfos[i].subLayerIds == null)
subLayers.push(layer.layerInfos[i].id);
}
idParams.layerIds = subLayers;
} else {
idParams.layerIds = [];
}
idParams.tolerance = 3;
idParams.returnGeometry = true;
identifyParamsList.push(idParams);
});
return identifyParamsList;
}
});
</script>
</head>
<body>
<div id="map"></div>
</body>
</html>
I want to create a array containing objects, and I'm using Parse to query all the data.
However, the for loop which loops over the results doesn't does that in the correct order but randomly loops over the data. If I log i each iteration, the logs show different results every time.
Here is my code:
for (var i = 0; i < results.length; i++)
{
Parse.Cloud.useMasterKey();
// retrieve params
var objectid = results[i];
var self = request.params.userid;
// start query
var Payment = Parse.Object.extend("Payments");
var query = new Parse.Query(Payment);
query.get(objectid, {
success: function (payment) {
// get all the correct variables
var from_user_id = payment.get("from_user_id");
var to_user_id = payment.get("to_user_id");
var amount = payment.get("amount");
var createdAt = payment.updatedAt;
var note = payment.get("note");
var img = payment.get("photo");
var location = payment.get("location");
var status = payment.get("status");
var fromquery = new Parse.Query(Parse.User);
fromquery.get(from_user_id, {
success: function(userObject) {
var fromusername = userObject.get("name");
var currency = userObject.get("currency");
var toquery = new Parse.Query(Parse.User);
toquery.get(to_user_id, {
success: function(touser)
{
var tousername = touser.get("name");
if(tousername !== null || tousername !== "")
{
sendArray(tousername);
}
},
error: function(touser, error)
{
var tousername = to_user_id;
if(tousername !== null || tousername !== "")
{
sendArray(tousername);
}
}
});
function sendArray(tousername) {
var array = new Array();
// create the time and date
var day = createdAt.getDate();
var year = createdAt.getFullYear();
var month = createdAt.getMonth();
var hour = createdAt.getHours();
var minutes = createdAt.getMinutes();
// create the timestamp
var time = "" + hour + ":" + minutes;
var date = "" + day + " " + month + " " + year;
var associativeArray = {};
if(self == from_user_id)
{
fromusername = "self";
}
if(self == to_user_id)
{
tousername = "self";
}
associativeArray["from"] = fromusername;
associativeArray["to"] = tousername;
associativeArray["amount"] = amount;
associativeArray["currency"] = currency;
associativeArray["date"] = date;
associativeArray["time"] = time;
associativeArray["status"] = status;
if(note == "" || note == null)
{
associativeArray["note"] = null;
}
else
{
associativeArray["note"] = note;
}
if(img == "" || img == null)
{
associativeArray["img"] = null;
}
else
{
associativeArray["img"] = img;
}
if(location == "" || location == null)
{
associativeArray["location"] = null;
}
else
{
associativeArray["location"] = location;
}
array[i] = associativeArray;
if((i + 1) == results.length)
{
response.success(array);
}
},
error: function(userObject, error)
{
response.error(106);
}
});
},
error: function(payment, error) {
response.error(125);
}
});
}
But the i var is always set to seven, so the associative arrays are appended at array[7] instead of the correct i (like 1,2,3,4,5)
The reason that this is so important is because I want to order the payment chronologically (which I have done in the query providing the results).
What can I do to solve this issue?
Success is a callback that happens at a later point in time. So what happens is, the for loop runs 7 times and calls parse 7 times. Then after it has run each of parse success calls will be executed, they look at i which is now at 7.
A simple way to fix this is to wrap the whole thing in an immediate function and create a new closure for i. Something like this
for(var i = 0; i < results.length; i++){
function(iClosure) {
//rest of code goes here, replace i's with iClosure
}(i);
}
Now what will happen is that each success function will have access to it's own iClosure variable and they will be set to the value of i at the point they were created in the loop.
I was using the code from Kejun's Blog .
I want to parse a .lrc (which is basically a lyrics file) so as to get the time variable as well as the string(read lyrics) . I tried out this code and could not seem to get the output .
<html>
<head>
<script src="jquery-1.7.1.js"></script>
<script>
$(document).ready(function () {
$.ajax({
type: "GET",
url: "a.txt",
dataType: "text",
success: function (data) {
parseLyric(data);
}
});
});
var _current_lyric = new Array();
function convertLRCLyric(inf) {
inf += "n";
var lyric = inf.match(/([(d{2}:d{2}(.d{1,2}){0,1})]){1,}W*n|([(d{2}:d{2}:d{2}(.d{1,2}){0,1})]){1,}W*n/ig);
var l_s = '',
l_tt, l_ww, l_i, l_ii;
if (!lyric || !lyric.length) {
return;
}
for (l_i = 0; l_i < lyric.length; l_i++) {
l_tt = lyric[l_i].match(/([d{2}:d{2}(.d{1,2}){0,1}])|([d{2}:d{2}:d{2}(.d{1,2}){0,1}])/ig);
l_ww = lyric[l_i].replace(/[S+]/ig, '').replace(/n{1,}/ig, '');
for (l_ii = 0; l_ii < l_tt.length; l_ii++) {
l_tt[l_ii] = l_tt[l_ii].replace(/[/,'').replace(/]/, '');
if (l_tt[l_ii].search(/d{2}:d{2}:d{2}.d{2}/g) >= 0) {
_current_lyric[l_tt[l_ii].substring(0, l_tt[l_ii].length - 1)] = l_ww;
} else if (l_tt[l_ii].search(/d{2}:d{2}:d{2}.d{1}/g) >= 0) {
_current_lyric[l_tt[l_ii]] = l_ww;
} else if (l_tt[l_ii].search(/d{2}:d{2}:d{2}/g) >= 0) {
_current_lyric[l_tt[l_ii] + ".0"] = l_ww;
} else if (l_tt[l_ii].search(/d{2}:d{2}.d{2}/g) >= 0) {
_current_lyric["00:" + l_tt[l_ii].substring(0, l_tt[l_ii].length - 1)] = l_ww;
} else if (l_tt[l_ii].search(/d{2}:d{2}.d{1}/g) >= 0) {
_current_lyric["00:" + l_tt[l_ii]] = l_ww;
} else if (l_tt[l_ii].search(/d{2}:d{2}/g) >= 0) {
_current_lyric["00:" + l_tt[l_ii] + ".0"] = l_ww;
}
}
}
}
function parseLyric(allText) {
_current_lyric = [];
convertLRCLyric(allText);
var ly = "";
for (var time in _current_lyric) {
ly += time + "--" + _current_lyric[time] + "n";
}
alert(ly);
}
</script>
</head>
<body>
</body>
</html>
But i keep getting a blank alert . Any help would be great . Thanks in advance .
Answer :
Ok so i built my own parser ,Here is the code
var contents = " " ;
function readMultipleFiles(evt) {
//Retrieve all the files from the FileList object
var files = evt.target.files;
if (files) {
for (var i = 0, f; f = files[i]; i++) {
var r = new FileReader();
r.onload = (function (f) {
return function (e) {
contents = e.target.result;
processData(contents);
};
})(f);
r.readAsText(f);
}
} else {
alert("Failed to load files");
}
}
document.getElementById('fileinput').addEventListener('change', readMultipleFiles, false);
var allTextLines = " ";
var lyrics = [];
var tim = [] ;
var line = " ";
// parsing the Lyrics
function processData(allText) { // This will only divide with respect to new lines
allTextLines = allText.split(/\r\n|\n/);
next();
}
function next()
{
for (i=0;i<allTextLines.length;i++)
{
if (allTextLines[i].search(/^(\[)(\d*)(:)(.*)(\])(.*)/i)>=0 )// any line without the prescribed format wont enter this loop
{
line = allTextLines[i].match(/^(\[)(\d*)(:)(.*)(\])(.*)/i);
tim[i] = (parseInt(line[2])*60)+ parseInt(line[4]); // will give seconds
lyrics[i]= line[6] ;//will give lyrics
}
}
}
Code php : with format
public function get_lrc_song($song) {
$lyrics_file = $song ['lyrics_file'];
$json = curlClass::getInstance ( true )->fetchURL ( $lyrics_file );
$content = explode ( "\n", $json );
$regix = "$\][^>]+$";
$result = "";
foreach ( $content as $item ) {
$isHas = preg_match ( $regix, $item, $data );
$dt = str_replace ( "]", "", $data[0] );
if ($dt != ""){
$result .= $dt . "\n";
}
}
echo $result;
}
I've made an plugin related to this which you can find here
There is an tutorial on how to use this and also i think this is most probably the simplest one I've seen while researching about this topic.
there is another lrc-parser for this purpose, I've tried it but, it lack some features like playing on command and other necessary features.
So i made them all
the code looks like this:
//view the tutorial of this usage on https://multimentality.000webhostapp.com/others
var lyricPlayer = {
"set_divval":function(){var all_lyrics = "";var mose;if(lyricPlayer.Mode=="Long"){mose="block"}else if(lyricPlayer.Mode=="Line"){mose="none"}else{alert("mode property: undefined value. lyricPlayer.Mode has two values 'Long' and 'Line'");mose="block"}for(let y=lyricPlayer.countt;y<lyricPlayer.lyrics.length;y++){all_lyrics+=`<span id='lyricsItem_${lyricPlayer.tim[y]}' class='lyricsItem_class' style='display:${mose};'>${lyricPlayer.lyrics[y]}</span>`;lyricPlayer.tmp_count=lyricPlayer.countt;lyricPlayer.main_dict[lyricPlayer.tim[y]]=lyricPlayer.tmp_count;lyricPlayer.tmp_count++;}document.getElementById('lyrics_playerMain').innerHTML=all_lyrics;},
"processData":function(allText){lyricPlayer.allTextLines = allText.split(/\r\n|\n/);lyricPlayer.next();},
"next":function()
{for (i=0;i<lyricPlayer.allTextLines.length;i++){if (lyricPlayer.allTextLines[i].search(/^(\[)(\d*)(:)(.*)(\])(.*)/i)>=0 ){lyricPlayer.line = lyricPlayer.allTextLines[i].match(/^(\[)(\d*)(:)(.*)(\])(.*)/i);lyricPlayer.tim[i] = (parseInt(lyricPlayer.line[2])*60)+ parseInt(lyricPlayer.line[4]);lyricPlayer.lyrics[i]= lyricPlayer.line[6] ;}else{lyricPlayer.countt++;}}lyricPlayer.set_divval();},
"set_scview":function(id){if(lyricPlayer.Mode=="Long"){var classes = document.getElementsByClassName("lyricsItem_class");for(let u=0;u<classes.length;u++){classes[u].style.color=lyricPlayer.Tcolor;}document.getElementById(`lyricsItem_${id}`).style.color=lyricPlayer.Scolor;var element = document.getElementById(`lyricsItem_${id}`);element.scrollIntoView({behavior: 'smooth',block: 'start'});}if(lyricPlayer.Mode=="Line"){var classes = document.getElementsByClassName("lyricsItem_class");
for(let u=0;u<classes.length;u++){
classes[u].style.display="none";
classes[u].style.color=lyricPlayer.Tcolor;}document.getElementById(`lyricsItem_${id}`).style.color=lyricPlayer.Scolor;document.getElementById(`lyricsItem_${id}`).style.display="block";}},
"change_lrc":function(elem){var time = parseInt(elem.currentTime);if(lyricPlayer.main_dict[time]!=undefined){lyricPlayer.set_scview(time)}},
"allTextLines":"",
"lyrics":[],
"tim":[],
"main_dict":{},
"h_lyrics":"",
"countt":0,
"Scolor":"white",
"line":"",
"tmp_count":0,
"Mode":"Long",
"Tcolor":document.getElementById("lyrics_playerMain").style.color,
"setLyrics":function(val){lyricPlayer.h_lyrics=val;lyricPlayer.main_dict={};lyricPlayer.countt=0;lyricPlayer.tim=[];lyricPlayer.lyrics=[];lyricPlayer.allTextLines="";lyricPlayer.processData(lyricPlayer.h_lyrics);lyricPlayer.tmp_count=lyricPlayer.countt;}
}
this works totally fine and perfect
This is my first attempt at a plugin but I think I'm missing the whole "How to" on this.
Ok here goes:
Trying to write an error popup box for form validation.
I like the look and functionality on this JavaScript code on this page, See demo here and source here.
It's basically what I want to do if the user enters invalid data.
Now I have tried to create a jQuery plugin with this code but it's not working, any help would be great :-)
(function($){
/* Might use the fadein fadeout functions */
var MSGTIMER = 20;
var MSGSPEED = 5;
var MSGOFFSET = 3;
var MSGHIDE = 3;
var errorBox = function(target, string, autohide, options)
{
var ebox = $(ebox);
var eboxcontent = $(eboxcontent);
var target = $(target);
var string = $(string);
var autohide = $(autohide);
var obj = this;
if (!document.getElementById('ebox')) {
ebox = document.createElement('div');
ebox.id = 'ebox';
eboxcontent = document.createElement('div');
eboxcontent.id = 'eboxcontent';
document.body.appendChild(ebox);
ebox.appendChild(eboxcontent);
ebox.style.filter = 'alpha(opacity=0)';
ebox.style.opacity = 0;
ebox.alpha = 0;
}
else {
ebox = document.getElementById('ebox');
eboxcontent = document.getElementById('eboxcontent');
}
eboxcontent.innerHTML = string;
ebox.style.display = 'block';
var msgheight = ebox.offsetHeight;
var targetdiv = document.getElementById(target);
targetdiv.focus();
var targetheight = targetdiv.offsetHeight;
var targetwidth = targetdiv.offsetWidth;
var topposition = topPosition(targetdiv) - ((msgheight - targetheight) / 2);
var leftposition = leftPosition(targetdiv) + targetwidth + MSGOFFSET;
ebox.style.top = topposition + 'px';
ebox.style.left = leftposition + 'px';
clearInterval(ebox.timer);
ebox.timer = setInterval("fadeMsg(1)", MSGTIMER);
if (!autohide) {
autohide = MSGHIDE;
}
window.setTimeout("hideMsg()", (autohide * 1000));
// hide the form alert //
this.hideMsg(msg) = function (){
var msg = document.getElementById('msg');
if (!msg.timer) {
msg.timer = setInterval("fadeMsg(0)", MSGTIMER);
}
};
// face the message box //
this.fadeMsg(flag) = function() {
if (flag == null) {
flag = 1;
}
var msg = document.getElementById('msg');
var value;
if (flag == 1) {
value = msg.alpha + MSGSPEED;
}
else {
value = msg.alpha - MSGSPEED;
}
msg.alpha = value;
msg.style.opacity = (value / 100);
msg.style.filter = 'alpha(opacity=' + value + ')';
if (value >= 99) {
clearInterval(msg.timer);
msg.timer = null;
}
else
if (value <= 1) {
msg.style.display = "none";
clearInterval(msg.timer);
}
};
// calculate the position of the element in relation to the left of the browser //
this.leftPosition(target) = function() {
var left = 0;
if (target.offsetParent) {
while (1) {
left += target.offsetLeft;
if (!target.offsetParent) {
break;
}
target = target.offsetParent;
}
}
else
if (target.x) {
left += target.x;
}
return left;
};
// calculate the position of the element in relation to the top of the browser window //
this.topPosition(target) = function() {
var top = 0;
if (target.offsetParent) {
while (1) {
top += target.offsetTop;
if (!target.offsetParent) {
break;
}
target = target.offsetParent;
}
}
else
if (target.y) {
top += target.y;
}
return top;
};
// preload the arrow //
if (document.images) {
arrow = new Image(7, 80);
arrow.src = "images/msg_arrow.gif";
}
};
$.fn.errorbox = function(options)
{
this.each(function()
{
var element = $(this);
// Return early if this element already has a plugin instance
if (element.data('errorbox')) return;
// pass options to plugin constructor
var errorbox = new errorBox(this, options);
// Store plugin object in this element's data
element.data('errorbox', errorbox);
});
};
})(jQuery);
How Im calling it
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>jQuery Plugin - Error ToolTip</title>
<script type="text/javascript" src="js/jquery.js">
</script>
<script type="text/javascript" src="js/jquery.errorbox.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
var name = document.getElementById('name');
if(name == "") {
$('#name','You must enter your name.',2).errorbox();
alert("Blank");
}
});
</script>
<link rel="stylesheet" type="text/css" href="css/errorbox.css" />
</head>
<body>
<div>
Name: <input type="text" id="name" width="30"></input>
</div>
</body>
Any help on my first plugin would be great, thanks in advance.
--Phill
The var errorBox = function(... needs to change to:
$.errorBox = function(...
then you can call it on the jquery object.
Secondly, for clarity you may want to use $('#eboxcontent') instead of document.getElementById('eboxcontent') . It wont be any faster, but it is "clearer" to other jquery developers.
Lastly, jQuery has many built in functions for fading things over a specified time period, and it appears that you have built your own. I know that jQuery's fading is cross-browser compatible. just use:
$('#someDivId').fadeOut(timeInMilliseconds);
var name = document.getElementById('name');
if(name == "") {
//...
}
should be
var name = document.getElementById('name');
if(name.value == "") {
//...
}
or
var name = $('#name').val();
if(name == "") {
//...
}