Javascript Image shrinking for specific users - javascript

I have a javascript function for shrinking images but I dont want the shrinking function to work if an administrator logs in.
Here is part of the code
function shrinkImages(){
var i=0, maxWidth;
//if (/^(?:artistnews|albums|news|exitnews|reviews)$/.test(arg(0))) maxWidth=236;
if(typeof homepage != 'undefined') maxWidth=530;
else maxWidth=236;
var first = getElementsByClassName('first');
if(first.length>1)
first = first[0].getElementsByTagName('img');
var imgs = document.getElementsByTagName('img');
while(imgs[i]) {
if(imgs[i].width > maxWidth && imgs[i].name!="shadow") {
if (has(imgs[i], first) && maxWidth==236) {
imgs[i].height = Math.round(521 * imgs[i].height / imgs[i].width);
imgs[i].width = 521;
i++;
continue;
}
imgs[i].height = Math.round(maxWidth * imgs[i].height / imgs[i].width);
imgs[i].width = maxWidth;
}
i++;
}
imgs = null;

Define a Javascript variable called isAdmin and set it to true when an administrator logs in, then stick this at the beginning of that function...
if(isAdmin) return;

switch(userType || undefined) #Small update
{
case 'admin':
//Nothing
break;
case 'user':
case undefined: /*user or unknown*/
var imgs = document.getElementsByTagName('img');
for(i=0;i<=imgs.lenght;i++)
{
if(imgs[i].width > maxWidth && imgs[i].name!="shadow")
{
//ETC, You know the rest
}
}
break;
}
then within your html head do
var userType = 'admin'; // or w.e
And if you only define it for admin and dont define it for anyone else they still will get shrunk down

Related

Phaser 2 determining which unit is active

I have 3 clickable objects. When one is clicked, this becomes the 'selected unit'.
I am trying to create some generic actions for the units such as moving to a point.
In my create function I initialize the units, when a unit is clicked on - this is supposed to become the 'selected unit' so that my movement and direction function applies to the this unit. However, the script is not able to recognize which unit intend for example I get this error:
Uncaught TypeError: Cannot read property 'velocity' of undefined.
Is there a way to use a variable to indicate selected users and pass that to the functions?
window.onload = function() {
var block_count = 0;
var block = '';
var selected_unit = '';
var unit_clicked = 0;
var tank1 = null;
var game = new Phaser.Game(800, 600, Phaser.AUTO, '', { preload: preload, create: create, update: update, render: render});
function preload () {
game.load.image('block', 'block.png');
game.load.image('tank1', 'tank.png');
game.load.image('baddie', 'tank.png');
game.load.image('mouse_btn', 'block.png');
game.input.mouse.capture = true;
}
function create () {
game.physics.startSystem(Phaser.Physics.ARCADE);
mouse_btn = game.add.sprite(30,30, 'mouse_btn');
mouse_btn.anchor.setTo(0.5, 0.5);
//T1
tank1 = game.add.sprite(30,30, 'tank1');
initialise_player(tank1);
game.physics.enable(tank1, Phaser.Physics.ARCADE);
//T2
tank2 = game.add.sprite(30,60, 'tank1');
initialise_player(tank2);
game.physics.enable(tank2, Phaser.Physics.ARCADE);
game.world.setBounds(0, 0, 2000, 2000);
game.camera.follow(tank1);
}
function update () {
if(selected_unit == '') {
mouse_btn.x = game.input.mousePointer.worldX
mouse_btn.y = game.input.mousePointer.worldY
}
if(game.input.activePointer.leftButton.isDown && block_count == 0 && unit_clicked == 0) {
game.input.activePointer.leftButton.stop(event);
block_count =1;
block = game.add.sprite(game.input.mousePointer.worldX, game.input.mousePointer.worldY, 'block');
game.physics.enable(block, Phaser.Physics.ARCADE);
block.anchor.setTo(0.5, 0.5)
lookAtObject(selected_unit, block, 0.005);
}
if(block.alive){
game.physics.arcade.moveToObject(selected_unit, block, 260, 0)
} else {
console.log(selected_unit)
selected_unit.body.velocity.x = 0;
selected_unit.body.velocity.y = 0;
}
if(game.physics.arcade.collide(selected_unit, block)) {
block_count--;
block.kill();
}
}
function render(){
//console.log(game.physics.arcade.collide(tank1, block))
}
function lookAtObject(obj, target, rotspeed){
var angle = Math.atan2(block.y - tank1.y, block.x - tank1.body.x);
tank1.rotation = angle + game.math.degToRad(90);
}
function initialise_player(tank1){
tank1.anchor.setTo(0.5, 0.5);
tank1.inputEnabled = true;
tank1.input.useHandCursor = true;
tank1.events.onInputDown.add(t1_clicked,this);
tank1.events.onInputOver.add(t1_over, this)
tank1.events.onInputOut.add(t1_out, this)
}
function t1_clicked() {
selected_unit = tank1;
}
function t1_over() {
unit_clicked = 1
}
function t1_out () {
unit_clicked = 0
}
};
The error you're getting on initial load is because in update you're making an assumption that selected_unit exists and has a body.
Update your third if to make sure selected_unit is defined.
if (selected_unit !== '') {
selected_unit.body.velocity.x = 0;
selected_unit.body.velocity.y = 0;
}
However, a better option would be to put this a few lines down, where you kill the block instead.
if(game.physics.arcade.collide(selected_unit, block)) {
selected_unit.body.velocity.x = 0;
selected_unit.body.velocity.y = 0;
block_count--;
block.kill();
}
if (block.alive); moveToObject is also expecting selected_unit to exist and have a body, which may not be the case; wrap it with a check.
if (selected_unit !== '') {
game.physics.arcade.moveToObject(selected_unit, block, 260, 0)
}
That now allows tank1 to rotate to look at the item you just placed, but it doesn't move it until it or tank2 have been clicked on.
This also points out that there are a number of tweaks you'll want to make to your code in general, since you're ignoring arguments that are being passed in. For example, t1_clicked isn't using the sprite that's been clicked on, but is instead just hard-coding tank1. lookAtObject isn't using obj or target, but again has values hard-coded in.
One other thing you may want to change is the following:
if(selected_unit == '') {
mouse_btn.x = game.input.mousePointer.worldX
mouse_btn.y = game.input.mousePointer.worldY
}
If you make that the following, you won't end up with an extra sprite hanging about on the screen.
if (block_count === 0) {
mouse_btn.x = game.input.mousePointer.worldX;
mouse_btn.y = game.input.mousePointer.worldY;
}

How to use Adobe Illustrator Scripting for Artboard?

I'm trying to load my SVG-images as layers folder onto a current document. Somehow I'm able to manage it for new document by using the script below but what I need is that I want to import all my images to current opened document. Can someone suggest how I can change the script below for doing this task?
Script source code is:
function getFolder() {
return Folder.selectDialog('Please select the folder to be imported:', Folder('~'));
}
function importFolderAsLayers(selectedFolder) {
// if a folder was selected continue with action, otherwise quit
var document;
var mm = 2.83464567; // Metric MM converter…
// Set the script to work with artboard rulers
app.coordinateSystem = CoordinateSystem.ARTBOARDCOORDINATESYSTEM;
if (selectedFolder) {
document = app.documents.add(
DocumentColorSpace.RGB,
width = 720*mm,
height = 720*mm,
);
document = app.activeDocument;
var firstImageLayer = true;
var newLayer;
var thisPlacedItem;
var posX=10;
var posY=30;
var count=0;
// create document list from files in selected folder
var imageList = selectedFolder.getFiles();
for (var i = 0; i < imageList.length; i++) {
if (imageList[i] instanceof File) {
var fileName = imageList[i].name.toLowerCase();
if( (fileName.indexOf(".svg") == -1) ) {
continue;
} else {
if( firstImageLayer ) {
newLayer = document.layers[0];
firstImageLayer = false;
} else {
newLayer = document.layers.add();
}
// Give the layer the name of the image file
newLayer.name = fileName.substring(0, fileName.indexOf(".") );
// Place the image on the artboard
newGroup = newLayer.groupItems.createFromFile( imageList[i] );
newGroup.position = [ posX , posY ];
}
}
posX += newGroup.width;
if(posX > (newGroup.width*16)) {
posX = 0;
posY -= newGroup.height;
}
}
if( firstImageLayer ) {
// alert("The action has been cancelled.");
// display error message if no supported documents were found in the designated folder
alert("Sorry, but the designated folder does not contain any recognized image formats.\n\nPlease choose another folder.");
document.close();
importFolderAsLayers(getFolder());
}
} else {
// alert("The action has been cancelled.");
// display error message if no supported documents were found in the designated folder
alert("Rerun the script and choose a folder with images.");
//importFolderAsLayers(getFolder());
}
}
// Start the script off
importFolderAsLayers( getFolder() );
Simply remove these lines from your script:
document = app.documents.add(
DocumentColorSpace.RGB,
width = 720*mm,
height = 720*mm,
);

I'm trying to stop snow script and clear the page after x seconds

How can I make the snow clear after a certain time. I've tried using variables and the calling a timeout which switches on to false and stops the makesnow() function but that doesn't seem to clear the page at all.
<script language="javascript">
ns6 = document.getElementById;
ns = document.layers;
ie = document.all;
/*******************[AccessCSS]***********************************/
function accessCSS(layerID) { //
if(ns6){ return document.getElementById(layerID).style;} //
else if(ie){ return document.all[layerID].style; } //
else if(ns){ return document.layers[layerID]; } //
}/***********************************************************/
/**************************[move Layer]*************************************/
function move(layer,x,y) { accessCSS(layer).left=x; accessCSS(layer).top = y; }
function browserBredde() {
if (window.innerWidth) return window.innerWidth;
else if (document.body.clientWidth) return document.body.clientWidth;
else return 1024;
}
function browserHoyde() {
if (window.innerHeight) return window.innerHeight;
else if (document.body.clientHeight) return document.body.clientHeight;
else return 800;
}
function makeDiv(objName,parentDiv,w,h,content,x,y,overfl,positionType)
{
// positionType could be 'absolute' or 'relative'
if (parentDiv==null) parentDiv='body';
var oDiv = document.createElement ("DIV");
oDiv.id = objName;
if (w) oDiv.style.width = w;
if (h) oDiv.style.height= h;
if (content) oDiv.innerHTML=content;
if (positionType==null) positionType="absolute";
oDiv.style.position = positionType;
if (x) oDiv.style.left=x; else oDiv.style.left=-2000;
if (y) oDiv.style.top=y; else oDiv.style.top=-2000;
if (overfl) oDiv.style.overflow=overfl; else oDiv.style.overflow="hidden";
eval(' document.'+parentDiv+'.appendChild (oDiv); ');
delete oDiv;
}
var snowC=0;
var x = new Array();
var y = new Array();
var speed = new Array();
var t=0;
var cC = new Array();
var ra = new Array();
function makeSnow() {
x[snowC] = Math.round(Math.random()*(browserBredde()-60));
y[snowC] = 10;
makeDiv("snow"+snowC,"body",32,32,'<img src="http://i693.photobucket.com/albums/vv296/KIBBLESGRAMMY/CAT/Orange-tabby-cat-icon.gif">');
speed[snowC] = Math.round(Math.random()*8)+1;
cC[snowC]=Math.random()*10;
ra[snowC] = Math.random()*7;
snowC++;
}
function moveSnow() {
var r = Math.round(Math.random()*100);
if (r>70 && snowC<20) makeSnow();
for (t=0;t<snowC;t++) {
y[t]+=speed[t];move("snow"+t,x[t],y[t]);
if (y[t]>browserHoyde()-50) {y[t] = 10;x[t] = Math.round(Math.random()*(browserBredde()-60));}
cC[t]+=0.01;
x[t]+=Math.cos(cC[t]*ra[t]);
}
setTimeout('moveSnow()',20);
}
moveSnow();
</script>
makeSnow just adds the snowflakes. Stopping that, as you say, does not clear anything. moveSnow handles the animation, and calls itself at a timeout. If instead of setting a timeout for the next moveSnow each time, you set it up to run in an interval just once, you would have an easier time stopping it.
window.snowAnimation = window.setInterval(moveSnow, 20);
If you add a css class to your snow flakes, it would be easier to target them for deletion.
oDiv.className = 'snowflake';
Then your clear function could look something like:
function clearSnow() {
window.clearTimeout(window.snowAnimation);
var flakes = document.getElementsByTagName('snowflake');
for(var i = 0, l = flakes.length; i < l; i++) {
document.body.removeChild(flakes[i]);
}
}
Timeout doesnt help, it helps you only to stop creating new snowdivs, however if you see makeDiv is the one which creates new divs on to the body, if you clear / display:none the divs which got created on makeDiv i hope it will clear all the divs on the screen.
You need to remove the divs that were created. It might be easier if you give them all some sort of class, like ".snowflake" as you create them (in makeDiv), then start removing them from the dom.
You will have to clear the elements created after the time you wanna stop snow falling.
Following code snippet will help you to clear the elements
if(count < 500){
setTimeout('moveSnow()',20);
}else{
var i = 0;
var elem = document.getElementById('snow'+i);
do{
elem.parentNode.removeChild(elem);
elem = document.getElementById('snow'+ ++i);
}while(elem != null)
}
count++;
you have to create a global variable count.

jquery / javascript - storing reference to array - not array values

I'm trying to combine a few similar functions into a single functions, which need to make calls to different arrays / variables, but I'm not quite getting it right. Here's my code:
var initialPreloadArray = ['scenes/icons_orange.png','scenes/icons_blue.png','scenes/icons_green.png','site/pedestal_h.png']; //These must be loaded before we advance from the intro screen
var initialPreloadCounter = 0;
var secondaryPreloadArray = ['site/restart-black.png','site/back_black.png','interludes/city.png','interludes/town.png','interludes/country.png']; //These must be loaded before we can advance from the initial decision scene
var secondaryPreloadCounter = 0;
var vehiclesPreloadArray = ['vehicles/vehicles.png','site/close.png']; //These must be loaded before we can display the vehicles
var vehiclesPreloadCounter = 0;
var arrName; //Store the variable name of the array for the stage of preloading we're in
var arrCounter; //Stores the variable name of the counter for the stage of preloading we're in
function setPreloadStage(preloadStage){
if (preloadStage == initial){
arrName = initialPreloadArray;
arrCounter = initialPreloadCounter;
} else if (preloadStage == 'secondary'){
arrName = secondaryPreloadArray;
arrCounter = secondaryPreloadCounter;
} else if (preloadStage == 'vehicles'){
arrName = vehiclesPreloadArray;
arrCounter = vehiclesPreloadCounter;
}
preloadImages(preloadStage);
}
//Recurse through scene xml and populate scene array
function preloadImages(preloadStage) {
console.log(arrName[arrCounter]);
var img = new Image();
img.src = 'images/' + arrName[arrCounter];
if(!img.complete){
jQuery(img).bind('error load onreadystatechange', imageComplete(preloadStage));
} else {
imageComplete(preloadStage);
}
//$j.preloadCssImages({statusTextEl: '#textStatus', statusBarEl: '#status'});
}
function imageComplete(preloadStage){
arrCounter++;
var preloadLength = arrName.length-1;
if (arrName && preloadLength && arrName[arrCounter]) {
if (preloadLength == arrCounter){
if (preloadStage == 'initial'){
initialImagesLoaded();
} else if (preloadStage == 'secondary'){
secondaryImagesLoaded();
} else if (preloadStage == 'vehicles'){
vehiclesLoaded();
}
}
preloadImages(preloadStage);
}
}
Anybody have an idea what I'm doing wrong?
Actually, here’s an even more obvious problem:
jQuery(img).bind('error load onreadystatechange', imageComplete(preloadStage));
You would have to do this:
jQuery(img).bind('error load onreadystatechange', function () {
imageComplete(preloadStage)
});
I suggest that you should use an array to manage state.
define an array holding your stages, like this:
var stages = [
{
label : 'initial',
imgs : [ 'img/whoobee.png', ...more here...],
doneSoFar: 0,
allDone: function(){}
},
{ label : 'secondary', imgs : .....},
{ label : 'whatever', imgs : ....}
];
NB: You will need to set the "allDone" fn for each stage appropriately.
Then a fn that kicks off one stage:
function kickoffPreloadOneStage(stage) {
console.log ("preloading stage " + stage.label);
preloadNextImage(stage);
}
function preloadNextImage(stage) {
var img = new Image();
img.src = 'images/' + stage.imgs[stage.doneSoFar];
if(!img.complete){
jQuery(img).bind('error load onreadystatechange', function() {
imageComplete(preloadStage);
});
}
else {
imageComplete(preloadStage);
}
}
function imageComplete(stage){
stage.doneSoFar++;
var preloadLength = stage.imgs.length-1;
if (stage.doneSoFar == preloadLength) {
stage.allDone(); // call the allDone function. may want to pass stage back
}
else {
preloadNextImage(stage);
}
}
To do all stages, use code like this:
var i;
for(i=0; i < stages.length; i++) {
kickoffPreloadOneStage(stages[i]);
}
You can also go OO, defining those functions as members of a Stage() class, but ....what I suggested is a reasonable simplification without getting too complicated.

Javascript to increase/decrease font size (external css)

I managed to pull together a script that will increase the font sizes of parts of a web page using buttons or links. It works in Moz/Chrome, but sticks on IE, tho theoretically it shouldn't have a issue in these major browsers. But I'm stuck on whether or not it's possible to use currentStyle to get the fontSize from a variable populated by getElementsByName; certainly IE is drawing blanks.
Here's my script:
function changeFontSize(element,step)
{
var styleProp = 'font-size';
step = parseInt(step,10);
var x = document.getElementsByName(element);
for(i=0;i<x.length;i++) {
if (x[i].currentStyle) {
var y = parseInt(x[i].currentStyle[styleProp],10);
} else if (window.getComputedStyle) {
var y = parseInt(document.defaultView.getComputedStyle(x[i],null).getPropertyValue(styleProp),10);
}
x[i].style.fontSize = (y+step) + 'px';
}
}
The 3 sites I've used to pull this together are:
www.vijayjoshi.org
www.quirksmode.org
and (this isn't spam, this is actually important) //http://www.white-hat-web-design.co.uk/blog/controlling-font-size-with-javascript/
Can anyone point out a solution please? Thanks in advance!
what about updating your code with the following :
function changeFontSize(element,step)
{
function computeFontSizeUpdate(oE)
{
//- init fSize with proper null value
var fSize = null;
//- retrieve fSize from style
if (oE.currentStyle) {
fSize = parseInt(oE.currentStyle[styleProp], 10);
}
else if (window.getComputedStyle) {
var s = document.defaultView.getComputedStyle(oE,null);
fSize = (s) ? parseInt(s.getPropertyValue(styleProp),10) : NaN;
}
//- check fSize value based on return of parseInt function
if( isNaN(fSize) == false && fSize != null)
{
fSize += nStep + 'px';
if(oE.currentStyle)
oE.currentStyle.fontSize = fSize;
else
oE.style.fontSize = fSize;
}
};
var styleProp = 'font-size';
var nStep = parseInt(step, 10);
//- ensure step value
if( isNaN(nStep) ) nStep = 0;
//- get target elements
var oElems = document.getElementsByName(element);
if ( oElems && oElems.length == 0)
{
var oE = document.getElementById(element);
if(oE) computeFontSizeUpdate(oE);
}
else
{
for(oE in oElems)
{
computeFontSizeUpdate(oE);
}
}
}
I have updated script with fix and few better naming for some variables.
Also, I am sorry cause I am on Mac right now, I wasn't able to test the provided script in IE ... but from what I remember it should do the trick.
Using some JS console you can directly execute directly on this page
changeFontSize("nav-tags", 50);
and you will notice that the Tags element in the menu bar would get affected :)
Hope this helps

Categories

Resources