input text box does not updated properly for click event button - javascript

I have the following code which the cancel button is not working. I cannot figure out why, when the cancel button is hit, it does not render properly. The expected behavior is when the user hit cancel it would just rollback and hide the admin window. See the jsfiddle below.
Thanks for all the help
https://jsfiddle.net/launeric/y188v9bg/#&togetherjs=HrxmjAojcq
<!DOCTYPE html>
<!--
Created using JS Bin
http://jsbin.com
Copyright (c) 2017 by AH0HA (http://jsbin.com/hoqerih/6/edit)
Released under the MIT license: http://jsbin.mit-license.org
-->
<meta name="robots" content="noindex">
<html lang="en">
<head>
<meta name="description" content="udacity_catclicker_ben_admin_mod">
<meta charset="UTF-8">
<title>Cat Clicker</title>
<style id="jsbin-css">
img {
max-width:256px;
max-height:256px;;
width:auto;
height:auto;
}
</style>
</head>
<body>
<ul id="cat-list"></ul>
<div id="cat">
<h2 id="cat-name"></h2>
<div id="cat-count"></div>
<img id="cat-img" src="" alt="cute cat">
<br><button id="cat-admin-button-init" type="button">admin</button></br>
</div>
<div id="CatAdminDiv" style="display:none;">
<br>catName<input type="text" id="adminCatName" value="XXXXXX"></br>
<br>catURL<input type="text" id="adminCatURL" value="zzzzzz"></br>
<br>catCnt<input type="text" id="adminCatCnt" value="999"></br>
<br><button id="cat-admin-button-save" type="button">save</button></br>
<br><button id="cat-admin-button-cancel" type="button">cancel</button></br>
</div>
<script src="js/app.js"></script>
<script id="jsbin-javascript">
/* ======= Model ======= */
var model = {
currentCat: null,
cats: [
{
clickCount : 0,
name : 'Tabby',
imgSrc : 'https://static.pexels.com/photos/33358/cat-fold-view-grey-fur.jpg'
},
{
clickCount : 0,
name : 'Tiger',
imgSrc : 'https://static.pexels.com/photos/54632/cat-animal-eyes-grey-54632.jpeg',
},
{
clickCount : 0,
name : 'Scaredy',
imgSrc : 'http://1.bp.blogspot.com/-zAWnDj_hEeE/UjWq6heqF-I/AAAAAAAAB_8/iThTIziz7VA/s1600/cat.jpg',
},
{
clickCount : 0,
name : 'Shadow',
imgSrc : 'http://ravenclan.yolasite.com/resources/Dawnfleck.jpg',
},
{
clickCount : 0,
name : 'Sleepy',
imgSrc : 'https://i.ytimg.com/vi/aBSzB6qxisQ/0.jpg',
//imgSrc : 'img/9648464288_2516b35537_z.jpg',
//imgAttribution : 'https://www.flickr.com/photos/onesharp/9648464288'
}
]
};
/* ======= Octopus ======= */
var octopus = {
init: function() {
// set our current cat to the first one in the list
model.currentCat = model.cats[0];
// tell our views to initialize
catListView.init();
catView.init();
},
adminInit: function() {
var x = document.getElementById('CatAdminDiv');
if (x.style.display === 'none') {
x.style.display = 'block';
} else {
x.style.display = 'none';
}
},
adminCancel: function(){
this.adminInit();
catView.render();
},
adminSave: function() {
var x = document.getElementById('cat-name');
var y = document.getElementById("adminCatName");
x.textContent = y.value;
},
getCurrentCat: function() {
return model.currentCat;
},
getCats: function() {
return model.cats;
},
// set the currently-selected cat to the object passed in
setCurrentCat: function(cat) {
model.currentCat = cat;
},
// increments the counter for the currently-selected cat
incrementCounter: function() {
model.currentCat.clickCount++;
catView.render();
}
};
/* ======= View ======= */
var catView = {
init: function() {
// store pointers to our DOM elements for easy access later
this.catElem = document.getElementById('cat');
this.catNameElem = document.getElementById('cat-name');
this.catImageElem = document.getElementById('cat-img');
this.countElem = document.getElementById('cat-count');
// on click, increment the current cat's counter
this.catImageElem.addEventListener('click', function(){
octopus.incrementCounter();
});
//admin begin
this.catAdminButtonInit = document.getElementById('cat-admin-button-init');
this.catAdminButtonCancel = document.getElementById('cat-admin-button-cancel');
this.catAdminButtonSave = document.getElementById('cat-admin-button-save');
this.AdminCatName = document.getElementById('AdminCatName');
this.AdminCatURL = document.getElementById('AdminCatURL');
this.AdminCatCnt = document.getElementById('AdminCatCnt');
this.AdminCatDiv = document.getElementById('CatAdminDiv');
this.catAdminButtonInit.addEventListener('click', function(){
octopus.adminInit();
});
this.catAdminButtonSave.addEventListener('click', function(){
octopus.adminSave();
});
this.catAdminButtonCancel.addEventListener('click', function(){
octopus.adminCancel();
});
//this.catAdminButtonCancel.addEventListener('click', function(){
// octopus.adminCancel();
//});
//admin end
// render this view (update the DOM elements with the right values)
this.render();
},
render: function() {
// update the DOM elements with values from the current cat
var currentCat = octopus.getCurrentCat();
this.countElem.textContent = currentCat.clickCount;
this.catNameElem.textContent = currentCat.name;
this.catImageElem.src = currentCat.imgSrc;
this.catNameElem.textContent = currentCat.name;
this.admincatName = document.getElementById("adminCatName");
this.admincatName.setAttribute("value", currentCat.name);
//document.getElementById("adminCatURL").setAttribute("value", currentCat.imgSrc);
//document.getElementById("adminCatCnt").setAttribute("value", currentCat.clickCount);
//var x = document.getElementById('AdminCatName');
// x.setAttribute("value",currentCat.name );
//x.value = 'xxx';//currentCat.name;
//var x2 = document.getElementById('adminCatName');
//x2.value=model.currentCat.name;
},
/*
renderAdmin: function(){
var currentCat = octopus.getCurrentCat();
//this.AdminCatName.value = currentCat.name;
var x = document.getElementById('AdminCatName')
x.setAttribute("value",currentCat.name );
}
*/
}
var catListView = {
init: function() {
// store the DOM element for easy access later
this.catListElem = document.getElementById('cat-list');
// render this view (update the DOM elements with the right values)
this.render();
},
render: function() {
var cat, elem, i;
// get the cats we'll be rendering from the octopus
var cats = octopus.getCats();
// empty the cat list
this.catListElem.innerHTML = '';
// loop over the cats
for (i = 0; i < cats.length; i++) {
// this is the cat we're currently looping over
cat = cats[i];
// make a new cat list item and set its text
elem = document.createElement('li');
elem.textContent = cat.name;
// on click, setCurrentCat and render the catView
// (this uses our closure-in-a-loop trick to connect the value
// of the cat variable to the click event function)
elem.addEventListener('click', (function(catCopy) {
return function() {
octopus.setCurrentCat(catCopy);
catView.render();
};
})(cat));
// finally, add the element to the list
this.catListElem.appendChild(elem);
}
}
};
// make it go!
octopus.init();
</script>
</body>
</html>

Related

Cannot access elements by id/name inside my HelloWorld.js from my HelloWorld.html file

I am using Adobe Animate to export a website and it gives me this folder:
My main file is this HelloWorld.html. The other HelloWorld.js gets generated by Animate and here is where all of my html objects get autogenerated (labels, buttons, etc).
Once I run it I get this
All I know is every time I make a design change to my website this HelloWorld.js file gets overwritten. Which is fine, I suppose. But, I do need access to these elements. All I am given to work with is the .html file:
<!DOCTYPE html>
<!--
NOTES:
1. All tokens are represented by '$' sign in the template.
2. You can write your code only wherever mentioned.
3. All occurrences of existing tokens will be replaced by their appropriate values.
4. Blank lines will be removed automatically.
5. Remove unnecessary comments before creating your template.
-->
<html>
<head>
<meta charset="UTF-8">
<meta name="authoring-tool" content="Adobe_Animate_CC">
<title>HelloWorld</title>
<!-- write your code here -->
<style>
#animation_container {
position:absolute;
margin:auto;
left:0;right:0;
top:0;bottom:0;
}
</style>
<script src="libs/1.0.0/createjs.min.js"></script>
<script src="HelloWorld.js"></script>
<script>
var canvas, stage, exportRoot, anim_container, dom_overlay_container, fnStartAnimation;
function init() {
canvas = document.getElementById("canvas");
anim_container = document.getElementById("animation_container");
dom_overlay_container = document.getElementById("dom_overlay_container");
var comp=AdobeAn.getComposition("8F022118589B1141A961E277C0AE693B");
var lib=comp.getLibrary();
var loader = new createjs.LoadQueue(false);
loader.addEventListener("fileload", function(evt){handleFileLoad(evt,comp)});
loader.addEventListener("complete", function(evt){handleComplete(evt,comp)});
var lib=comp.getLibrary();
loader.loadManifest(lib.properties.manifest);
}
function handleFileLoad(evt, comp) {
var images=comp.getImages();
if (evt && (evt.item.type == "image")) { images[evt.item.id] = evt.result; }
}
function handleComplete(evt,comp) {
//This function is always called, irrespective of the content. You can use the variable "stage" after it is created in token create_stage.
var lib=comp.getLibrary();
var ss=comp.getSpriteSheet();
var queue = evt.target;
var ssMetadata = lib.ssMetadata;
for(i=0; i<ssMetadata.length; i++) {
ss[ssMetadata[i].name] = new createjs.SpriteSheet( {"images": [queue.getResult(ssMetadata[i].name)], "frames": ssMetadata[i].frames} )
}
exportRoot = new lib.HelloWorld();
stage = new lib.Stage(canvas);
//Registers the "tick" event listener.
fnStartAnimation = function() {
stage.addChild(exportRoot);
createjs.Ticker.framerate = lib.properties.fps;
createjs.Ticker.addEventListener("tick", stage);
}
//Code to support hidpi screens and responsive scaling.
AdobeAn.makeResponsive(false,'both',false,1,[canvas,anim_container,dom_overlay_container]);
AdobeAn.compositionLoaded(lib.properties.id);
fnStartAnimation();
}
</script>
<!-- write your code here -->'
<script>
});
</script>
</head>
<body onload="init();" style="margin:0px;">
<div id="animation_container" style="background-color:rgba(0, 204, 153, 1.00); width:800px; height:600px">
<canvas id="canvas" width="800" height="600" style="position: absolute; display: block; background-color:rgba(0, 204, 153, 1.00);"></canvas>
<div id="dom_overlay_container" style="pointer-events:none; overflow:hidden; width:800px; height:600px; position: absolute; left: 0px; top: 0px; display: block;">
</div>
</div>
</body>
</html>
Inside the HelloWorld.js this is the function where my elements get created:
// stage content:
(lib.HelloWorld = function(mode,startPosition,loop,reversed) {
if (loop == null) { loop = true; }
if (reversed == null) { reversed = false; }
var props = new Object();
props.mode = mode;
props.startPosition = startPosition;
props.labels = {};
props.loop = loop;
props.reversed = reversed;
cjs.MovieClip.apply(this,[props]);
this.actionFrames = [0];
this.isSingleFrame = false;
// timeline functions:
this.frame_0 = function() {
if(this.isSingleFrame) {
return;
}
if(this.totalFrames == 1) {
this.isSingleFrame = true;
}
/* Button Click Event
Clicking on the specified button executes this function in which you can add your own custom code.
Instructions:
1. Add your custom code on a new line after the line that says "// Start your custom code" below.
*/
if(!this.SendInfoButton_click_cbk) {
function SendInfoButton_click(evt) {
// Start your custom code
console.log("Button clicked");
alert('Click')
// End your custom code
}
$("#dom_overlay_container").on("click", "#SendInfoButton", SendInfoButton_click.bind(this));
this.SendInfoButton_click_cbk = true;
}
}
// actions tween:
this.timeline.addTween(cjs.Tween.get(this).call(this.frame_0).wait(1));
// Animation
this.instance = new lib.circleAnimation();
this.instance.setTransform(36.25,34.05,0.1804,0.1804);
this.timeline.addTween(cjs.Tween.get(this.instance).wait(1));
// Buttons
this.GetInfoButton = new lib.an_Button({'id': 'GetInfoButton', 'label':'Get Info', 'disabled':false, 'visible':true, 'class':'ui-button'});
this.GetInfoButton.name = "GetInfoButton";
this.GetInfoButton.setTransform(102.05,156.85,1,1,0,0,0,50,11);
this.SendInfoButton = new lib.an_Button({'id': 'SendInfoButton', 'label':'Send Info', 'disabled':false, 'visible':true, 'class':'ui-button'});
this.SendInfoButton.name = "SendInfoButton";
this.SendInfoButton.setTransform(102.05,106.05,1,1,0,0,0,50,11);
this.timeline.addTween(cjs.Tween.get({}).to({state:[{t:this.SendInfoButton},{t:this.GetInfoButton}]}).wait(1));
// Lights_mc
this.Light_1 = new lib.Light_mc();
this.Light_1.name = "Light_1";
this.Light_1.setTransform(177.25,377.3,1,1,0,0,0,41.2,12.5);
this.Light_1_1 = new lib.Light_mc();
this.Light_1_1.name = "Light_1_1";
this.Light_1_1.setTransform(187.25,343.65,1,1,0,0,0,51.2,12.5);
this.timeline.addTween(cjs.Tween.get({}).to({state:[{t:this.Light_1_1},{t:this.Light_1}]}).wait(1));
// Textfields
this.instance_1 = new lib.CachedBmp_5();
this.instance_1.setTransform(351.25,329.8,0.5,0.5);
this.textfield_1 = new cjs.Text("Text 1", "20px 'Arial'", "#FFFFFF");
this.textfield_1.name = "textfield_1";
this.textfield_1.lineHeight = 24;
this.textfield_1.lineWidth = 321;
this.textfield_1.parent = this;
this.textfield_1.setTransform(416.5,260.85);
this.textfield_2 = new cjs.Text("Text 2", "20px 'Arial'", "#FFFFFF");
this.textfield_2.name = "textfield_2";
this.textfield_2.lineHeight = 24;
this.textfield_2.lineWidth = 321;
this.textfield_2.parent = this;
this.textfield_2.setTransform(416.5,215.85);
this.textfield_3 = new cjs.Text("Text 3", "20px 'Arial'", "#FFFFFF");
this.textfield_3.name = "textfield_4";
this.textfield_3.lineHeight = 24;
this.textfield_3.lineWidth = 321;
this.textfield_3.parent = this;
this.textfield_3.setTransform(54.05,260.85);
this.instance_4 = new lib.CachedBmp_1();
this.instance_4.setTransform(233,28.6,0.5,0.5);
this.instance_5 = new lib.CachedBmp_2();
this.instance_5.setTransform(6.5,6.5,0.5,0.5);
this.timeline.addTween(cjs.Tween.get({}).to({state:[{t:this.instance_5},{t:this.instance_4},{t:this.sendInfo_1_text},{t:this.sendInfo_2_text},{t:this.textfield_3},{t:this.textfield_4},{t:this.textfield_5},{t:this.textfield_6},{t:this.instance_3},{t:this.instance_2},{t:this.light_1_value},{t:this.light_2_value},{t:this.instance_1}]}).wait(1));
// outlines
this.shape = new cjs.Shape();
this.shape.graphics.f().s("#FFFFFF").ss(1,1,1).p("Eg4egH4MBw9AAAIAAPxMhw9AAAg");
this.shape.setTransform(401.475,134.55);
this.timeline.addTween(cjs.Tween.get(this.shape).wait(1));
// Background
this.shape_1 = new cjs.Shape();
this.shape_1.graphics.f("#0066CC").s().p("Eg+fAu4MAAAhdvMB8/AAAMAAABdvg");
this.shape_1.setTransform(400,300);
this.timeline.addTween(cjs.Tween.get(this.shape_1).wait(1));
this._renderFirstFrame();
}).prototype = p = new lib.AnMovieClip();
p.nominalBounds = new cjs.Rectangle(400,300,400,300);
// library properties:
lib.properties = {
id: '8F022118589B1141A961E277C0AE693B',
width: 800,
height: 600,
fps: 24,
color: "#000000",
opacity: 1.00,
manifest: [
{src:"images/HelloWorld_atlas_1.png", id:"HelloWorld_atlas_1"},
{src:"components/lib/jquery-3.4.1.min.js", id:"lib/jquery-3.4.1.min.js"},
{src:"components/sdk/anwidget.js", id:"sdk/anwidget.js"},
{src:"components/ui/src/button.js", id:"an.Button"}
],
preloads: []
};
I have tried to access the "Text 1" text field by writing the following inside the <script> tags :
<script>
const demoId = document.getElementById('#textfield_1');
console.log(demoId);
</script>
but all I get is null when I check the console window which brings the initial question around: Given my current set up, how can I access a text field and change its value?
You shouldn't give the '#' in the getElementById function:
const demoId = document.getElementById('textfield_1');

Problems with changing color of gltf object

With this answer as a reference, I have succeeded in changing the color of the gltf model.
(Change the color of an object (.dae or gltf) in "AR.JS")
However, the model texture will disappear.
why?
<!-- A FRAME -->
<script src="https://aframe.io/releases/1.0.0/aframe.min.js"></script>
<script src="https://unpkg.com/aframe-orbit-controls#1.2.0/dist/aframe-orbit-controls.min.js"></script>
<script>
AFRAME.registerComponent('carman', {
init: function(){
let el = this.el;
let self = this;
self.cars = [];
el.addEventListener("model-loaded", e => {
let car3D = el.getObject3D('mesh');
if (!car3D){return;}
 //console.log('car', car3D);
car3D.traverse(function(node){
if (node.isMesh){
// console.log(node);
self.cars.push(node);
if(node.name == "meta02t"){
self.carMat = node.material;
}
node.material.map = null;
}
});
});
el.addEventListener('changecolor', e => {
let colorp = e.detail.color;
let colorHex = Number(colorp.replace('#', '0x'));
let color3D = new THREE.Color(colorHex);
self.carMat.color = color3D;
});
}
});
AFRAME.registerComponent('click-listener', {
init: function () {
// Listen for click event
let self = this;
let el = this.el;
this.el.addEventListener('click', function (evt) {
// Call the Octahedron and trigger it's scalewave animation
let car = document.querySelector('#car');
let color = el.getAttribute('material', 'color');
car.emit('changecolor', color);
});
}
});
</script>
My Glitch Project https://glitch.com/~0421
There is no texture, because once the model is loaded, you go through the nodes and remove it:
node.material.map = null; // removes the texture
Furthermore - the car seems black even with the color changed. The "metal" parts are rough and not metallic (roughness: 0.5, metalness: 0). If you change that, the car will change its color (visually speaking):
el.addEventListener('changecolor', e =>{  
// set the new color
let colorp = e.detail.color;
let colorHex = Number(colorp.replace('#', '0x'));
let color3D = new THREE.Color(colorHex);
// apply for the "metal" materials
for (var i = 0; i < self.cars.length; i++) {
if (!self.cars[i].material) return
if (self.cars[i].name.includes("meta")) {
self.cars[i].material.metalness = 0.7
self.cars[i].material.roughness = 0.2
self.cars[i].material.color = color3D;
}
}
});
Check it out in this glitch.

Chart is not defined

i'm new to this pie chart. i tried all possibile solution available in the
internet. i have seperate .js file and html file in the same webapp folder.
i don't know where am i missing. Please help me to resolve this
issue. Thanks in advance.
i'm getting the error for creating new Chart in the console
piechart.js:48 Uncaught ReferenceError: Chart is not defined
at drawPieChart (piechart.js:48)
at validation (piechart.js:35)
Here is my html code
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Insert title here</title>
<script type="text/javascript" src="piechart.js"></script>
</head>
<body>
<div>
<button onclick="makePieChart()">view to piechart</button>
</div>
<div>
<canvas id="chartContainer" style="height: 300px; width: 100%;margin-left: -313px;"></canvas>
</div>
</body>
</html>
Here is my pieChart.js code
if (typeof jQuery === "undefined") {
var script = document.createElement('script');
script.src = 'http://code.jquery.com/jquery-latest.min.js';
script.type = 'text/javascript';
script.srcOne="https://canvasjs.com/assets/script/canvasjs.min.js";
script.srcTwo="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.bundle.min.js";
document.getElementsByTagName('head')[0].appendChild(script);
}
var details;
function makePieChart() {
console.log("in");
$.ajax({
url : 'http://localhost:8085/restcall/rest/details',
type : 'GET',
cache : false,
success : function(data) {
console.log(data);
details = data;
validation(details);
}
});
}
function validation(details) {
let pending = 0;
let completed = 0;
for (var i = 0; i < details.length; i++) {
if (details[i].flag == 0) {
pending++;
} else {
completed++;
}
}
drawPieChart(pending, completed);
}
function drawPieChart(count1, count2) {
var canvas = document.getElementById("chartContainer");
var ctx = canvas.getContext("2d");
var data = {
datasets : [ {
data : [ count1, count2 ],
backgroundColor : [ "#F7464A", "#46BFBD" ]
} ],
labels : [ "Completed", "Pending" ]
};
var myNewChart = new Chart(ctx, {
animationEnabled : true,
title : {
text : "status"
},
type : 'pie',
data : data
});
canvas.onclick = function(evt) {
var activePoints = myNewChart.getElementsAtEvent(evt);
if (activePoints[0]) {
var chartData = activePoints[0]['_chart'].config.data;
var idx = activePoints[0]['_index'];
var label = chartData.labels[idx];
var value = chartData.datasets[0].data[idx];
if (label === "Pending") {
pendingList(sample);
}
}
}
}
function pendingList(details) {
var pList = [];
var list = details;
console.log(list);
for (var i = 0; i < details.length; i++) {
if (details[i].flag == "0") {
pList.push(details[i].name);
} else {
//console.log(sample[i].name);
}
}
console.log(pList);
}

jquery html(array) doesn't insert all items in array

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.

jQuery Plugin development help

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 == "") {
//...
}

Categories