Finishing Rock Paper Scissors Game - actionscript-3

The code doesn't work although it won't display any errors. I'm trying to build a rock paper scissors game with 3 buttons and a score counter. I press the buttons but nothing changes on the screen.
Player 1 is the textbox for the user's score and Player 2 is the textbox for the computer's score.
var options: Array = [
"rock",
"paper",
"scissors"
];
var cp: String;
var res: String;
var score1: uint = 0;
var score2: uint = 0;
rockbtn.addEventListener(MouseEvent.CLICK, function (ev) {
computerturn("rock");
});
paperbtn.addEventListener(MouseEvent.CLICK, function (ev) {
computerturn("paper");
});
scissorsbtn.addEventListener(MouseEvent.CLICK, function (ev) {
computerturn("scissors");
});
function computerturn(player: String) {
cp = options[Math.floor(Math.random() * 3)];
computer.text = "Computer played " + cp;
if (cp == player) {
res = "TIE";
result.text = "TIE";
}
if ((cp == "rock") && (player == "paper")) {
res = "Player wins: paper covers rock.";
result.text = res;
score1 += 1;
Player1.text = score1.toString();
}
if ((cp == "rock") && (player == "scissors")) {
res = "Computer wins: rock breaks scissors";
result.text = res;
score2 += 1;
Player2.text = score2.toString();
}
if ((cp == "paper") && (player == "scissors")) {
res = "Player wins: scissors cuts paper.";
result.text = res;
score1 += 1;
Player1.text = score1.toString();
}
if ((cp == "paper") && (player == "rock")) {
res = "Computer wins: paper covers rock.";
result.text = res;
score2 += 1;
Player2.text = score2.toString();
}
if ((cp == "scissors") && (player == "rock")) {
res = "Player wins: rock breaks scissors.";
result.text = res;
score1 += 1;
Player1.text = score1.toString();
}
if ((cp == "scissors") && (player == "paper")) {
res = "Computer wins: scissors cuts paper.";
result.text = res;
score2 += 1;
Player2.text = score2.toString();
}
}
result.text = res;
computer.text = "Computer played " + cp;
This is the code I based it on:
var options:Array= [
"rock",
"paper",
"scissors"
];
var cp:String;
var res:String;
function computerturn(player:String) {
//trace("player played "+player);
cp = options[Math.floor(Math.random()*3)];
//trace("computer played "+cp);
computer.text = "Computer played "+cp;
if (cp==player) {
res = "TIE";
result.text = "TIE";
}
if ((cp=="rock")&&(player=="paper")) {
res="Player wins: paper covers rock.";
result.text = res;
}
if ((cp=="rock")&&(player=="scissors")) {
res="Computer wins: rock breaks scissors";
result.text = res;
gotoAndPlay("rockbreaks");
}
if ((cp=="paper")&&(player=="scissors")) {
res="Player wins: scissors cuts paper.";
result.text = res;
}
if ((cp=="paper")&&(player=="rock")) {
res="Computer wins: paper covers rock.";
result.text = res;
}
if ((cp=="scissors")&&(player=="rock")) {
res="Player wins: rock breaks scissors.";
result.text = res;
gotoAndPlay("rockbreaks");
}
if ((cp=="scissors")&&(player=="paper")) {
res="Computer wins: scissors cuts paper.";
result.text = res;
}
}
rockbtn.addEventListener(MouseEvent.CLICK, function (ev) {
computerturn("rock");} );
paperbtn.addEventListener(MouseEvent.CLICK, function (ev) {
computerturn("paper");} );
scissorsbtn.addEventListener(MouseEvent.CLICK, function (ev) {
computerturn("scissors");} );
stop();

Related

How to find the latitude and longitude of the beginning and the end of a street?

I'm trying to find the coordinates (LAT LONG) of a street from the beginning to the end of the street with the GOOGLE MAPS API. I can not find some simillaria on the net
Thanks
I use this code :
function findEndAddr(addr) {
for (var i = 500;;) {
var Http = new XMLHttpRequest();
var url = 'https://maps.googleapis.com/maps/api/geocode/json?address=' + i.toString().split('.')[0] + addr.replace(/\s/g, '') + '&key=KEY_API';
console.log(url);
Http.open("GET", url, false);
Http.send(null);
if (Http.status == 200 && Http.readyState == 4) {
var resp = JSON.parse(Http.responseText);
if (resp['results'][0]['address_components'][0]['types'][0] != 'street_number') {
i = i / 2;
}
else {
return findEndAddrNext(addr, i, i, 2);
}
}
}
}
And I use this function :
function findEndAddrNext(addr, i, nb, div) {
var Http = new XMLHttpRequest();
var url;
url = 'https://maps.googleapis.com/maps/api/geocode/json?address=' + nb.toString().split('.')[0] + addr.replace(/\s/g, '') + '&key=KEY-API';
console.log(url);
Http.open("GET", url, false);
Http.send(null);
if (Http.status == 200 && Http.readyState == 4) {
var resp = JSON.parse(Http.responseText);
var index = 0;
for (let cpt = 0; cpt < resp['results'].length; cpt++) {
console.log(getThing(resp['results'][cpt]['address_components'], 'postal_code'));
console.log(addr.split(',')[2]);
if (getThing(resp['results'][cpt]['address_components'], 'locality') == addr.split(',')[1]) {
index = cpt;
break;
}
}
if (resp['results'][index]['address_components'][0]['types'][0] == 'street_number') {
i = nb;
if ((nb / div) <= 2) {
if (getThing(resp['results'][index]['address_components'], 'locality') != addr.split(',')[1]) {
oui = searchFinal(getThing(resp['results'][index]['address_components'], 'street_number'), addr);
return;
}
oui = [resp['results'][index]['geometry']['location'].lat, resp['results'][0]['geometry']['location'].lng];
console.log(resp);
return;
}
nb = nb + (nb / div);
findEndAddrNext(addr, i, nb, div);
}
if (resp['results'][index]['address_components'][0]['types'][0] != 'street_number') {
div *= 2;
nb = i + (i / div);
findEndAddrNext(addr, i, nb, div);
}
}
}

How to call a custom directive from angular controller

I have a directive which is depending on some input. I want to call that directive from angular controller when ever that input changed. Here is my directive.
var app = angular.module('App', ['ui.bootstrap']);
app.controller('fcController', function($scope, fcService, $uibModal) {
$scope.formatType = '1';
});
app.directive('fcsaNumber', function($filter) {
var addCommasToInteger, controlKeys, hasMultipleDecimals, isNotControlKey, isNotDigit, isNumber, makeIsValid, makeMaxDecimals, makeMaxDigits, makeMaxNumber, makeMinNumber;
isNumber = function(val) {
return !isNaN(parseFloat(val)) && isFinite(val);
};
isNotDigit = function(which) {
return which < 45 || which > 57 || which === 47;
};
controlKeys = [0, 8, 13];
isNotControlKey = function(which) {
return controlKeys.indexOf(which) === -1;
};
hasMultipleDecimals = function(val) {
return (val != null) && val.toString().split('.').length > 2;
};
makeMaxDecimals = function(maxDecimals) {
var regexString, validRegex;
if (maxDecimals > 0) {
regexString = "^-?\\d*\\.?\\d{0," + maxDecimals + "}$";
} else {
regexString = "^-?\\d*$";
}
validRegex = new RegExp(regexString);
return function(val) {
return validRegex.test(val);
};
};
makeMaxNumber = function(maxNumber) {
return function(val, number) {
return number <= maxNumber;
};
};
makeMinNumber = function(minNumber) {
return function(val, number) {
return number >= minNumber;
};
};
makeMaxDigits = function(maxDigits) {
var validRegex;
validRegex = new RegExp("^-?\\d{0," + maxDigits + "}(\\.\\d*)?$");
return function(val) {
return validRegex.test(val);
};
};
makeIsValid = function(options) {
var validations;
validations = [];
if (options.maxDecimals != null) {
validations.push(makeMaxDecimals(options.maxDecimals));
}
if (options.max != null) {
validations.push(makeMaxNumber(options.max));
}
if (options.min != null) {
validations.push(makeMinNumber(options.min));
}
if (options.maxDigits != null) {
validations.push(makeMaxDigits(options.maxDigits));
}
return function(val) {
var i, number, _i, _ref;
if (!isNumber(val)) {
return false;
}
if (hasMultipleDecimals(val)) {
return false;
}
number = Number(val);
for (i = _i = 0, _ref = validations.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
if (!validations[i](val, number)) {
return false;
}
}
return true;
};
};
addCommasToInteger = function(val) {
var commas, decimals, wholeNumbers;
decimals = val.indexOf('.') == -1 ? '.00' : val.replace(/^\d+(?=\.)/, '');
wholeNumbers = val.replace(/(\.\d+)$/, '');
commas = wholeNumbers.replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,');
return "" + commas + decimals.substring(0, 3);
};
return {
restrict: 'A',
require: 'ngModel',
scope: {
options: '#fcsaNumber',
},
link: function(scope, elem, attrs, ngModelCtrl) {
var isValid, options;
options = {};
if (scope.options != null) {
options = scope.$eval(scope.options);
}
isValid = makeIsValid(options);
ngModelCtrl.$parsers.unshift(function(viewVal) {
var noCommasVal;
noCommasVal = viewVal.replace(/,/g, '');
if (isValid(noCommasVal) || !noCommasVal) {
ngModelCtrl.$setValidity('fcsaNumber', true);
return noCommasVal;
} else {
ngModelCtrl.$setValidity('fcsaNumber', false);
return void 0;
}
});
ngModelCtrl.$formatters.push(function(val) {
if ((options.nullDisplay != null) && (!val || val === '')) {
return options.nullDisplay;
}
if ((val == null) || !isValid(val)) {
return val;
}
ngModelCtrl.$setValidity('fcsaNumber', true);
val = addCommasToInteger(val.toString());
if (options.key == 1) {
options.prepend = 'S/.';
}
if (options.key == 2) {
options.prepend = '$';
}
if (options.prepend != null) {
val = "" + options.prepend + val;
}
if (options.append != null) {
val = "" + val + options.append;
}
return val;
});
elem.on('blur', function() {
var formatter, viewValue, _i, _len, _ref;
viewValue = ngModelCtrl.$modelValue;
if ((viewValue == null) || !isValid(viewValue)) {
return;
}
_ref = ngModelCtrl.$formatters;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
formatter = _ref[_i];
viewValue = formatter(viewValue);
}
ngModelCtrl.$viewValue = viewValue;
return ngModelCtrl.$render();
});
elem.on('focus', function() {
var val;
val = elem.val();
if (options.prepend != null) {
val = val.replace(options.prepend, '');
}
if (options.append != null) {
val = val.replace(options.append, '');
}
elem.val(val.replace(/,/g, ''));
return elem[0].select();
});
if (options.preventInvalidInput === true) {
return elem.on('keypress', function(e) {
if (isNotDigit(e.which && isNotControlKey(e.which))) {
return e.preventDefault();
}
});
}
}
};
});
HTML:
<input type ="text" ng-model ="currency" fcsa-number="{key : {{formatType}}}">
Here $scope.formatType = '1'; is the input. If this formatType changed then That directive need to call. One friend suggested me this
link: function(scope,elem,attr,ctrl){
scope.$watch('fcsaNumber', function(){
// do your stuff
});
but it is not calling my directive manually.
even I have tried with
.controller("ctrl", function($scope) {
$scope.$watch('formatType', function() {
$scope.$broadcast("call_dir")
})
})
return {
restrict: 'A',
require: 'ngModel',
scope: {
options: '#fcsaNumber',
},
link: function(scope, elem, attrs, ngModelCtrl) {
var isValid, options;
options = {};
scope.$on('call_dir', function(ev) {
//your code
})
};
You need to watch the value that is going to change in your controller. In your case it is formatType.
You should try to use this expression in your isolated scope:
scope: {
options: '=fcsaNumber',
}
And if you want the event broadcasting to work, i.e. the $scope.$bradcast approach, then make sure your directive is a child of the controller scope in the scope hierarchy. Else a easier way (but not always recommended) would be to broadcast your event from $rootScope.
So something like this should also work (with your event based solution):
.controller("ctrl", function($scope, $rootScope) {
$scope.$watch('formatType', function() {
$rootScope.$broadcast("call_dir")
})
})

Making invisible sprite with phaser

I need some help with my code. I want to make the str sprite invisible after 10 seconds.
I'm using this link for help: http://phaser.io/examples/v2/time/basic-timed-event
var game = new Phaser.Game(500, 550, Phaser.AUTO);
//var picture;
var Pacman = function (game) {
this.map = null;
this.layer = null;
this.pacman = null;
this.safetile = 14;
this.gridsize = 16;
this.speed = 100;
this.threshold = 3;
this.turnSpeed = 200;
this.marker = new Phaser.Point();
this.turnPoint = new Phaser.Point();
this.directions = [ null, null, null, null, null ];
this.opposites = [ Phaser.NONE, Phaser.RIGHT, Phaser.LEFT, Phaser.DOWN, Phaser.UP ];
this.current = Phaser.NONE;
this.turning = Phaser.NONE;
this.score=0;
this.scoreText='';
this.bonus=0;
this.bonusText='';
};
Pacman.prototype = {
init: function () {
this.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
this.scale.pageAlignHorizontally = true;
this.scale.pageAlignVertically = true;
Phaser.Canvas.setImageRenderingCrisp(this.game.canvas);
this.physics.startSystem(Phaser.Physics.ARCADE);
},
preload: function () {
// We need this because the assets are on github pages
// Remove the next 2 lines if running locally
this.load.baseURL = 'https://nikosdaskalos.github.io/pacman/';
this.load.crossOrigin = 'anonymous';
this.load.image('str', 'assets/str.png');
this.load.image('dot', 'assets/dot.jpg');
this.load.image('coin', 'assets/coin.jpg');
this.load.image('tiles', 'assets/pacman-tiles.png');
this.load.spritesheet('pacman', 'assets/pacman.png');
this.load.tilemap('map', 'assets/pacman-map.json', null, Phaser.Tilemap.TILED_JSON);
// Needless to say, graphics (C)opyright Namco
},
create: function () {
this.map = this.add.tilemap('map');
this.map.addTilesetImage('pacman-tiles', 'tiles');
this.layer = this.map.createLayer('Pacman');
//picture = game.add.sprite(game.world.centerX, game.world.centerY, 'str');
//picture.anchor.setTo(0.5, 0.5);
//game.time.events.add(Phaser.Timer.SECOND * 4, fadePicture, this);
this.dots = this.add.physicsGroup();
this.map.createFromTiles(36, this.safetile, 'str', this.layer, this.dots);
this.map.createFromTiles(7, this.safetile, 'dot', this.layer, this.dots);
this.map.createFromTiles(35, this.safetile, 'coin', this.layer, this.dots);
// The dots will need to be offset by 6px to put them back in the middle of the grid
this.dots.setAll('x', 6, false, false, 1);
this.dots.setAll('y', 6, false, false, 1);
// Pacman should collide with everything except the safe tile
this.map.setCollisionByExclusion([this.safetile], true, this.layer);
// Position Pacman at grid location 14x17 (the +8 accounts for his anchor)
this.pacman = this.add.sprite((14 * 16) + 8, (17 * 16) + 8, 'pacman', 0);
this.pacman.anchor.set(0.5);
//this.pacman.animations.add('munch', [0, 1, 2, 1], 20, true);
this.physics.arcade.enable(this.pacman);
this.pacman.body.setSize(16, 16, 0, 0);
this.cursors = this.input.keyboard.createCursorKeys();
//this.pacman.play('munch');
this.move(Phaser.LEFT);
this.scoreText = game.add.text(0, 500, 'Score: 0', { fontSize: '34px Arial', fill: 'white' });
lives = game.add.group();
game.add.text(game.world.width - 340, 500, 'Lives : ', { fontSize: '34px Arial', fill: 'white' });
this.bonusText = game.add.text(360, 500, 'Bonus: 0', { fontSize: '20px Arial', fill: 'white' });
for (var i = 0; i < 3; i++)
{
var pacman = lives.create(game.world.width - 235 + (30 * i), 517, 'pacman');
pacman.anchor.setTo(0.5, 0.5);
pacman.angle = 90;
pacman.alpha = 0.4;
}
},
//function fadePicture() {
//game.add.tween(picture).to( { alpha: 0 }, 2000, Phaser.Easing.Linear.None, true);
//},
checkKeys: function () {
if (this.cursors.left.isDown && this.current !== Phaser.LEFT)
{
this.checkDirection(Phaser.LEFT);
}
else if (this.cursors.right.isDown && this.current !== Phaser.RIGHT)
{
this.checkDirection(Phaser.RIGHT);
}
else if (this.cursors.up.isDown && this.current !== Phaser.UP)
{
this.checkDirection(Phaser.UP);
}
else if (this.cursors.down.isDown && this.current !== Phaser.DOWN)
{
this.checkDirection(Phaser.DOWN);
}
else
{
// This forces them to hold the key down to turn the corner
this.turning = Phaser.NONE;
}
},
checkDirection: function (turnTo) {
if (this.turning === turnTo || this.directions[turnTo] === null || this.directions[turnTo].index !== this.safetile)
{
// Invalid direction if they're already set to turn that way
// Or there is no tile there, or the tile isn't index 1 (a floor tile)
return;
}
// Check if they want to turn around and can
if (this.current === this.opposites[turnTo])
{
this.move(turnTo);
}
else
{
this.turning = turnTo;
this.turnPoint.x = (this.marker.x * this.gridsize) + (this.gridsize / 2);
this.turnPoint.y = (this.marker.y * this.gridsize) + (this.gridsize / 2);
}
},
turn: function () {
var cx = Math.floor(this.pacman.x);
var cy = Math.floor(this.pacman.y);
// This needs a threshold, because at high speeds you can't turn because the coordinates skip past
if (!this.math.fuzzyEqual(cx, this.turnPoint.x, this.threshold) || !this.math.fuzzyEqual(cy, this.turnPoint.y, this.threshold))
{
return false;
}
// Grid align before turning
this.pacman.x = this.turnPoint.x;
this.pacman.y = this.turnPoint.y;
this.pacman.body.reset(this.turnPoint.x, this.turnPoint.y);
this.move(this.turning);
this.turning = Phaser.NONE;
return true;
},
move: function (direction) {
var speed = this.speed;
if (direction === Phaser.LEFT || direction === Phaser.UP)
{
speed = -speed;
}
if (direction === Phaser.LEFT || direction === Phaser.RIGHT)
{
this.pacman.body.velocity.x = speed;
}
else
{
this.pacman.body.velocity.y = speed;
}
// Reset the scale and angle (Pacman is facing to the right in the sprite sheet)
/* this.pacman.scale.x = 1;
this.pacman.angle = 0;
if (direction === Phaser.LEFT)
{
this.pacman.scale.x = -1;
}
else if (direction === Phaser.UP)
{
this.pacman.angle = 270;
}
else if (direction === Phaser.DOWN)
{
this.pacman.angle = 90;
}
this.current = direction;
},*/
this.add.tween(this.pacman).to( { angle: this.getAngle(direction) }, this.turnSpeed, "Linear", true);
this.current = direction;
},
getAngle: function (to) {
// About-face?
if (this.current === this.opposites[to])
{
return "180";
}
if ((this.current === Phaser.UP && to === Phaser.LEFT) ||
(this.current === Phaser.DOWN && to === Phaser.RIGHT) ||
(this.current === Phaser.LEFT && to === Phaser.DOWN) ||
(this.current === Phaser.RIGHT && to === Phaser.UP))
{
return "-90";
}
return "90";
},
eatDot: function (pacman, dot) {
dot.kill();
var audio = new Audio('assets/pacman_chomp.wav');
audio.play()
this.score+=10;
this.scoreText.text= 'Score: ' + this.score;
//setTimeout(audio.play(),2000);
if (this.dots.total === 0)
{
this.dots.callAll('revive');
}
},
/*function muteAudio() {
var audio = document.getElementById('audioPlayer');
if (audio.mute = false) {
document.getElementById('audioPlayer').muted = true;
}
else {
audio.mute = true
document.getElementById('audioPlayer').muted = false;
}
}*/
eatCoin: function(pacman,coin){//pente
coin.kill();
this.score+=20;
this.scoreText.text= 'Score: ' + this.score;
var audio = new Audio('assets/pacman_eatfruit.wav');
audio.play()
if(this.coins.total===0)
{
this.coins.callAll('revive');
}
},
eatStr: function(pacman,str){//pente
str.kill();
this.bonus+=100;
this.bonusText.text= 'Bonus: ' + this.bonus;
var audio = new Audio('assets/pacman_eatfruit.wav');
audio.play()
if(this.strs.total===0)
{
this.strs.callAll('revive');
}
},
update: function () {
this.physics.arcade.collide(this.pacman, this.layer);
this.physics.arcade.overlap(this.pacman, this.dots, this.eatDot, null, this);
this.physics.arcade.overlap(this.pacman, this.dots, this.eatCoin, null, this);
this.physics.arcade.overlap(this.pacman, this.dots, this.eatStr, null, this);
this.marker.x = this.math.snapToFloor(Math.floor(this.pacman.x), this.gridsize) / this.gridsize;
this.marker.y = this.math.snapToFloor(Math.floor(this.pacman.y), this.gridsize) / this.gridsize;
// Update our grid sensors
this.directions[1] = this.map.getTileLeft(this.layer.index, this.marker.x, this.marker.y);
this.directions[2] = this.map.getTileRight(this.layer.index, this.marker.x, this.marker.y);
this.directions[3] = this.map.getTileAbove(this.layer.index, this.marker.x, this.marker.y);
this.directions[4] = this.map.getTileBelow(this.layer.index, this.marker.x, this.marker.y);
this.checkKeys();
if (this.turning !== Phaser.NONE)
{
this.turn();
}
}
};
game.state.add('Game', Pacman, true);
</script>
</body>
</html>
So, can anyone help me with making the str invisible after 10 seconds?
You were pretty close.
I'm going to use pacman as an example, since I'm not 100% sure how you were going to fade out the coins. When Pacman eats them?
First, you want the following fadePicture function:
fadePicture: function() {
game.add.tween(this.pacman).to( { alpha: 0 }, 2000, Phaser.Easing.Linear.None, true);
},
Note how that was changed from function fadePicture().
Next, in your create function you can refer to it:
this.game.time.events.add(Phaser.Timer.SECOND * 4, this.fadePicture, this);
That replaces the following:
//game.time.events.add(Phaser.Timer.SECOND * 4, fadePicture, this);
I've created a JSFiddle with the relevant changes.
If you do want your coins to fade then I would try updating fadePicture to accept a dot/str parameter and then game.add.tween on that.

How did they make this glitchable_container?

https://versionindustries.com/
Hover over the images they use for their portfolio. That glitch is really cool to me, and I can see tons of applications for it. Does anybody know how I can replicate that? I'm not great at coding, but I'd probably understand the lingo you throw at me.
Anybody?
Why not just inspect the code they're using and try to reverse-engineer?
(function($) {
window.GlitchableImages = function(selector) {
var base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
base64Map = base64Chars.split(""),
reverseBase64Map = false,
hover_img = false,
elSelector = selector;
function setupReverseBase64Map() {
reverseBase64Map = {};
base64Map.forEach(function(val, key) {
reverseBase64Map[val] = key
})
}
function detectJpegHeaderSize(data) {
var jpgHeaderLength = 417;
for (var i = 0, l = data.length; i < l; i++) {
if (data[i] == 255 && data[i + 1] == 218) {
jpgHeaderLength = i + 2;
return jpgHeaderLength
}
}
return jpgHeaderLength
}
function base64ToByteArray(str) {
var result = [],
digitNum, cur, prev;
for (var i = 23, l = str.length; i < l; i++) {
cur = reverseBase64Map[str.charAt(i)];
digitNum = (i - 23) % 4;
switch (digitNum) {
case 1:
result.push(prev << 2 | cur >> 4);
break;
case 2:
result.push((prev & 15) << 4 | cur >> 2);
break;
case 3:
result.push((prev & 3) << 6 | cur);
break
}
prev = cur
}
return result
}
function byteArrayToBase64(arr) {
var result = ["data:image/jpeg;base64,"],
byteNum, cur, prev;
for (var i = 0, l = arr.length; i < l; i++) {
cur = arr[i];
byteNum = i % 3;
switch (byteNum) {
case 0:
result.push(base64Map[cur >> 2]);
break;
case 1:
result.push(base64Map[(prev & 3) << 4 | cur >> 4]);
break;
case 2:
result.push(base64Map[(prev & 15) << 2 | cur >> 6]);
result.push(base64Map[cur & 63]);
break
}
prev = cur
}
if (byteNum === 0) {
result.push(base64Map[(prev & 3) << 4]);
result.push("==")
} else if (byteNum == 1) {
result.push(base64Map[(prev & 15) << 2]);
result.push("=")
}
return result.join("")
}
function glitchJpegBytes(strArr, jpgHeaderLength) {
var rnd = Math.floor(jpgHeaderLength + Math.random() * (strArr.length - jpgHeaderLength - 4));
strArr[rnd] = Math.floor(Math.random() * 256)
}
function glitchJpeg() {
try {
var glitchCopy = hover_img.dataArr.slice();
for (var i = 0; i < 10; i++) {
glitchJpegBytes(glitchCopy, hover_img.headerLength)
}
var new_img = new Image;
new_img.onload = function() {
if (typeof hover_img.ctx === "undefined") return;
hover_img.ctx.drawImage(new_img, 0, 0, hover_img.width, hover_img.height)
};
new_img.src = byteArrayToBase64(glitchCopy)
} catch (e) {}
}
function unglitch(this_img) {
try {
var new_img = new Image;
new_img.onload = function() {
this_img.ctx.drawImage(new_img, 0, 0, this_img.width, this_img.height)
};
new_img.src = byteArrayToBase64(this_img.dataArr)
} catch (e) {}
}
function setupGlitchableImage(event) {
var img = this.page_img;
var $img = $(img);
var $canvas = $('<canvas width="' + $img.width() + '" height="' + $img.height() + '">');
$img.wrap('<span class="glitchable_container"></span>');
$img.after($canvas);
try {
img.ctx = $canvas[0].getContext("2d");
img.ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, $img.width(), $img.height());
img.jpgImgData = $canvas[0].toDataURL("image/jpeg");
img.dataArr = base64ToByteArray(img.jpgImgData);
img.headerLength = detectJpegHeaderSize(img.dataArr)
} catch (e) {}
}
function onImageMouseOver(event) {
hover_img = $(event.target).prev("img")[0]
}
function onImageMouseMove(event) {
requestAnimationFrame(glitchJpeg)
}
function onImageMouseOut(event) {
unglitch(hover_img);
hover_img = false
}
function resize() {
$(".glitchable_container canvas").each(function() {
var $img = $(this).siblings("img");
$(this).attr("width", $img.width()).attr("height", $img.height())
})
}
function init() {
if (!reverseBase64Map) {
setupReverseBase64Map()
}
$(elSelector).each(function() {
if (this.ctx) {
return
}
this.load_img = new Image;
this.load_img.page_img = this;
$(this.load_img).load(setupGlitchableImage);
this.load_img.src = this.getAttribute("src")
});
$("body").on("mouseover", ".glitchable_container", onImageMouseOver).on("mousemove", ".glitchable_container", onImageMouseMove).on("mouseout", ".glitchable_container", onImageMouseOut)
}
return {
onResize: resize,
init: init
}
}
})(jQuery);

IE 8 - Invalid source HTML for this operation

What is wrong with
el.insertAdjacentHTML(hashVal[0], html);
where html is "<a title=\"\">1</a>" and hashVal[0] is "afterBegin".
This is related to a rating functionality. I think due to this error, the rating star is not displaying in ie 8. Other browsers are ok.
I have given the full flow of code below. I am using extjs.
var starLink = star.createChild({
tag: 'a',
html: this.values[i],
title: this.showTitles ? this.titles[i] : ''
});
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
createChild : function(config, insertBefore, returnDom) {
config = config || {tag:'div'};
if (insertBefore) {
return Ext.DomHelper.insertBefore(insertBefore, config, returnDom !== true);
}
else {
return Ext.DomHelper[!this.dom.firstChild ? 'insertFirst' : 'append'](this.dom, config, returnDom !== true);
}
},
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
insertFirst : function(el, o, returnElement){
return doInsert(el, o, returnElement, afterbegin, 'firstChild');
},
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function doInsert(el, o, returnElement, pos, sibling, append){
el = Ext.getDom(el);
var newNode;
if (pub.useDom) {
newNode = createDom(o, null);
if (append) {
el.appendChild(newNode);
} else {
(sibling == 'firstChild' ? el : el.parentNode).insertBefore(newNode, el[sibling] || el);
}
} else {
newNode = Ext.DomHelper.insertHtml(pos, el, Ext.DomHelper.createHtml(o));
}
return returnElement ? Ext.get(newNode, true) : newNode;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function createHtml(o){
var b = '',
attr,
val,
key,
cn,
i;
if(typeof o == "string"){
b = o;
} else if (Ext.isArray(o)) {
for (i=0; i < o.length; i++) {
if(o[i]) {
b += createHtml(o[i]);
}
}
} else {
b += '<' + (o.tag = o.tag || 'div');
for (attr in o) {
val = o[attr];
if(!confRe.test(attr)){
if (typeof val == "object") {
b += ' ' + attr + '="';
for (key in val) {
b += key + ':' + val[key] + ';';
}
b += '"';
}else{
b += ' ' + ({cls : 'class', htmlFor : 'for'}[attr] || attr) + '="' + val + '"';
}
}
}
if (emptyTags.test(o.tag)) {
b += '/>';
} else {
b += '>';
if ((cn = o.children || o.cn)) {
b += createHtml(cn);
} else if(o.html){
b += o.html;
}
b += '</' + o.tag + '>';
}
}
return b;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
insertHtml : function(where, el, html){
var hash = {},
hashVal,
range,
rangeEl,
setStart,
frag,
rs;
where = where.toLowerCase();
hash[beforebegin] = ['beforeBegin', 'previousSibling'];
hash[afterend] = ['afterEnd', 'nextSibling'];
if (el.insertAdjacentHTML) {
if(tableRe.test(el.tagName) && (rs = insertIntoTable(el.tagName.toLowerCase(), where, el, html))){
return rs;
}
hash[afterbegin] = ['afterBegin', 'firstChild'];
hash[beforeend] = ['beforeEnd', 'lastChild'];
if ((hashVal = hash[where])) {
el.insertAdjacentHTML(hashVal[0], html);
return el[hashVal[1]];
}
} else {