; Missing Error after Packing Prototype - javascript

After using Packer (http://dean.edwards.name/packer/) I end up throwing a
missing ; after (the long packer string). I have no idea of the what and why.
possible fix and explanation please?
jQuery.fn.extend({
ImageRotate:function(parameters)
{
if (this.Wilq32&&this.Wilq32.PhotoEffect) return;
return (new Wilq32.PhotoEffect(this.get(0),parameters))._temp;
},
rotate:function(parameters)
{
if (this.length===0) return;
if (typeof parameters=="undefined") return;
if (typeof parameters=="number") parameters={angle:parameters};
var returned=[];
for (var i=0,i0=this.length;i<i0;i++)
{
var element=this.get(i);
if (typeof element.Wilq32 == "undefined")
returned.push($($(element).ImageRotate(parameters)));
else
{
element.Wilq32.PhotoEffect._rotate(parameters.angle);
}
}
return returned;
},
rotateAnimation:function(parameters)
{
if (this.length===0) return;
if (typeof parameters=="undefined") return;
if (typeof parameters=="number") parameters={angle:parameters};
var returned=[];
for (var i=0,i0=this.length;i<i0;i++)
{
var element=this.get(i);
if (typeof element.Wilq32 == "undefined")
returned.push($($(element).ImageRotate(parameters)));
else
{
element.Wilq32.PhotoEffect._parameters.animateAngle = parameters.angle;
element.Wilq32.PhotoEffect._parameters.callback = parameters.callback ||
function()
{
};
element.Wilq32.PhotoEffect._animateStart();
}
}
return returned;
}
});
Wilq32={};
Wilq32.PhotoEffect=function(img,parameters)
{
this._IEfix=img;
this._parameters=parameters;
this._parameters.className=img.className;
this._parameters.id=img.getAttribute('id');
if (!parameters) this._parameters={};
this._angle=0;
if (!parameters.angle) this._parameters.angle=0;
this._temp=document.createElement('span');
this._temp.Wilq32 =
{
PhotoEffect: this
};
var image=img.src;
img.parentNode.insertBefore(this._temp,img);
this._img= new Image();
this._img.src=image;
this._img._ref=this;
jQuery(this._img).bind("load", function()
{
this._ref._Loader.call(this._ref);
});
if (jQuery.browser.msie) if (this._img.complete) this._Loader();
}
Wilq32.PhotoEffect.prototype._Loader=
(function()
{
if (jQuery.browser.msie)
return function()
{
var src=this._IEfix.src;
this._IEfix.parentNode.removeChild(this._IEfix);
this._temp.setAttribute('id',this._parameters.id);
this._temp.className=this._parameters.className;
var width=this._img.width;
var height=this._img.height;
this._img._widthMax=this._img._heightMax=Math.sqrt((height)*(height) + (width) * (width));
this._img._heightMax=Math.sqrt((height)*(height) + (width) * (width));
this._vimage = document.createElement('v:image');
this._vimage._ref=this;
this._vimage.style.height=height;
this._vimage.style.width=width;
this._vimage.style.position="relative";
this._temp.style.display="inline-block";
this._temp.style.width=this._temp.style.height=this._img._heightMax;
this._vimage.src=src;
this._vimage.rotate=0;
this._temp.appendChild(this._vimage);
var self = this;
this._parameters.animateAngle=0;
if (this._parameters.bind)
{
for (var a in this._parameters.bind) if (this._parameters.bind.hasOwnProperty(a))
for (var b in this._parameters.bind[a]) if (this._parameters.bind[a].hasOwnProperty(b))
jQuery(this._temp).bind(b,this._parameters.bind[a][b]);
}
this._rotate(this._parameters.angle);
}
else
return function ()
{
this._IEfix.parentNode.removeChild(this._IEfix);
this._temp.setAttribute('id',this._parameters.id);
this._temp.className=this._parameters.className;
var width=this._img.width;
var height=this._img.height;
this._img._widthMax=this._img._heightMax=Math.sqrt((height)*(height) + (width) * (width));
this._canvas=document.createElement('canvas');
this._canvas._ref=this;
this._canvas.height=height;
this._canvas.width=width;
this._canvas.setAttribute('width',width);
this._temp.appendChild(this._canvas);
var self = this;
this._parameters.animateAngle=0;
if (this._parameters.bind)
{
for (var a in this._parameters.bind) if (this._parameters.bind.hasOwnProperty(a))
for (var b in this._parameters.bind[a]) if (this._parameters.bind[a].hasOwnProperty(b))
jQuery(this._canvas).bind(b,this._parameters.bind[a][b]);
}
this._cnv=this._canvas.getContext('2d');
this._rotate(this._parameters.angle);
}
})();
Wilq32.PhotoEffect.prototype._animateStart=function()
{
if (this._timer) clearTimeout(this._timer);
this._animate();
}
Wilq32.PhotoEffect.prototype._animate=function()
{
var temp=this._angle;
if (typeof this._parameters.animateAngle!="undefined") this._angle-=(this._angle-this._parameters.animateAngle)*0.1;
if (typeof this._parameters.minAngle!="undefined") if (this._angle<this._parameters.minAngle) this._angle=this._parameters.minAngle;
if (typeof this._parameters.maxAngle!="undefined") if (this._angle>this._parameters.maxAngle) this._angle=this._parameters.maxAngle;
if (Math.round(this._angle * 100 - temp * 100) == 0 && this._timer)
{
clearTimeout(this._timer);
if (this._parameters.callback)
this._parameters.callback();
}
else
{
this._rotate(this._angle);
var self = this;
this._timer = setTimeout(function()
{
self._animate.call(self);
}, 10);
}
}
Wilq32.PhotoEffect.prototype._rotate = (function()
{
if (jQuery.browser.msie)
return function(angle)
{
this._vimage.style.rotation=angle;
var radians=angle*Math.PI/180;
this._vimage.style.top= (this._img._heightMax - this._img.height)/2- (this._vimage.offsetHeight-this._img.height)/2 +"px";
this._vimage.style.left= (this._img._widthMax - this._img.width)/2- (this._vimage.offsetWidth-this._img.width)/2 +"px";
}
else
return function(angle)
{
if (!this._img.width) return;
if (typeof angle!="number") return;
angle=(angle%360)* Math.PI / 180;
var width=this._img.width;
var height=this._img.height;
var widthAdd = this._img._widthMax - width;
var heightAdd = this._img._heightMax - height;
this._canvas.width = width+widthAdd;
this._canvas.height = height+heightAdd;
this._cnv.save();
this._cnv.translate(widthAdd/2,heightAdd/2);
this._cnv.translate(width/2,height/2);
this._cnv.rotate(angle);
this._cnv.translate(-width/2,-height/2);
this._cnv.drawImage(this._img, 0, 0);
this._cnv.restore();
}
})();

Packer jams everything onto one line if I'm not mistaken so that any missing semicolons that would have been originally parsed OK turn into hard errors.
There are a few missing semicolons in your js for example
return function(angle)
{
this._vimage.style.rotation=angle;
var radians=angle*Math.PI/180;
this._vimage.style.top= (this._img._heightMax - this._img.height)/2- (this._vimage.offsetHeight-this._img.height)/2 +"px";
this._vimage.style.left= (this._img._widthMax - this._img.width)/2- (this._vimage.offsetWidth-this._img.width)/2 +"px";
}
is missing a semicolon. there are more.

Here's a nice site which will tell you what is wrong with your javascript: http://jslint.com/
So paste your code there, click on the JSLint button and observe the errors and warnings you get. Once you fix them you may be confident that when packed your javascript will work.

Related

How to get my function to increase variable "_time"

// videogame.js
// don't forget to validate at jslint.com
/*jslint devel: true, browser: true */
/*global $*/
$(function () {
"use strict";
// global functions
function boundaryCheck(element_selector) {
var element = $(element_selector);
var universe = $("#universe");
var p = element.position();
if (p.left < 0) {
element.css("left", "0px");
}
if (p.top < 0) {
element.css("top", "0px");
}
if (p.left + element.width() > universe.width()) {
element.css("left", (universe.width() - element.width()) + "px");
}
if (p.top + element.height() > universe.height()) {
element.css("top", (universe.height() - element.height()) + "px");
}
}
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
// Constructor for Player Ship object
function PlayerShip() {
var my = {};
$("#universe").append($("<div>").attr("id", "player"));
my.navigate = function (keys) {
var RIGHTARROW_KEYCODE = 39;
var LEFTARROW_KEYCODE = 37;
var UPARROW_KEYCODE = 38;
var DOWNARROW_KEYCODE = 40;
if (keys === RIGHTARROW_KEYCODE) {
$("#player").css("left", "+=10px");
}
if (keys === LEFTARROW_KEYCODE) {
$("#player").css("left", "-=10px");
}
if (keys === UPARROW_KEYCODE) {
$("#player").css("top", "-=10px");
}
if (keys === DOWNARROW_KEYCODE) {
$("#player").css("top", "+=10px");
}
boundaryCheck("#player");
};
return my;
}
// Constructor for Enemy Ship object
function EnemyShip() {
var my = {};
$("#universe").append($("<div>").attr("id", "enemy"));
my.move = function (paused) {
if (!paused) {
var left = Boolean(getRandomInt(0, 2));
var top = Boolean(getRandomInt(0, 2));
if (left) {
$("#enemy").css("left", "-=" + getRandomInt(1, 10) + "px");
} else {
$("#enemy").css("left", "+=" + getRandomInt(1, 10) + "px");
}
if (top) {
$("#enemy").css("top", "-=" + getRandomInt(1, 10) + "px");
} else {
$("#enemy").css("top", "+=" + getRandomInt(1, 10) + "px");
}
boundaryCheck("#enemy");
}
};
return my;
}
// this might make an asteroid happen, maybe. I don't know if it will work.
function Asteroid() {
var my = {};
$("#universe").append($("<div>").attr("id", "asteroid"));
my.move = function (paused) {
if (!paused) {
var left = Boolean(getRandomInt(0, 2));
var top = Boolean(getRandomInt(0, 2));
if (left) {
$("#asteroid").css("left", "-=" + getRandomInt(1, 10) + "px");
} else {
$("#asteroid").css("left", "+=" + getRandomInt(1, 10) + "px");
}
if (top) {
$("#asteroid").css("top", "-=" + getRandomInt(1, 10) + "px");
} else {
$("#asteroid").css("top", "+=" + getRandomInt(1, 10) + "px");
}
boundaryCheck("#asteroid");
}
};
return my;
}
// Constructor for Game object
function Game() {
// total points
var _health = 1000;
var _time = 0;
// is the game paused?
var _game_paused = false;
// speed of background animation in ms (larger = slower)
var _background_speed = 100;
// player ship
var _player_ship = new PlayerShip();
// enemy ship
var _enemy_ship = new EnemyShip();
var _asteroid = new Asteroid(); //make this an actual thing
var my = {
health: _health,
time: _time,
game_paused: _game_paused,
background_speed: _background_speed,
player_ship: _player_ship,
enemy_ship: _enemy_ship,
asteroid: _asteroid
};
$("#universe").append($("<div>").attr("id", "results"));
$("#results").append($("<h1>"));
$("#universe").append($("<div>").attr("id", "results2"));
$("#results2").append($("<h1>"));
my.health = function (value) {
if (value === undefined) {
return _health;
}
_health = value;
return my;
};
my.time = function (value) {
if (value === undefined) {
return _time;
}
_time = value;
return my;
};
my.game_paused = function (value) {
if (value === undefined) {
return _game_paused;
}
_game_paused = value;
return my;
};
my.background_speed = function (value) {
if (value === undefined) {
return _background_speed;
}
_background_speed = value;
return my;
};
my.player_ship = function (value) {
if (value === undefined) {
return _player_ship;
}
_player_ship = value;
return my;
};
function runtimer() {
_time++;
};
my.enemy_ship = function (value) {
if (value === undefined) {
return _enemy_ship;
}
_enemy_ship = value;
return my;
};
my.asteroid = function (value) {
if (value === undefined) {
return _asteroid;
}
_asteroid = value;
return my;
};
// METHODS
// display total points
my.displayHealth = function () {
$("#results h1").html("Health: " + _health);
};
my.increaseTime = function () {
setInterval(function(){ runTimer() }, 1000)
}
my.displayTimer = function () {
$("#results2 h1").html("Time: "+ _time);
};
my.moveBackground = function () {
if (!_game_paused) {
var background_position = $("#universe")
.css("backgroundPosition")
.split(" ");
var current_x = parseInt(background_position[0], 10);
var current_y = parseInt(background_position[1], 10);
var new_x = current_x - 1;
var new_y = current_y;
$("#universe").css({
"background-position": new_x + "px " + new_y + "px"
});
}
};
my.checkKeys = function () {
var ESCAPE_KEYCODE = 27;
$(document).keydown(function (key_event) {
if (key_event.which === ESCAPE_KEYCODE) {
if (_game_paused) {
_game_paused = false;
$("#pause").remove();
} else {
_game_paused = true;
var pause = $("<div>", {id: "pause"});
$("body").prepend(pause);
}
} else {
_player_ship.navigate(key_event.which);
}
});
};
my.checkCollisions = function (paused) {
var p = $("#player");
var e = $("#enemy");
var ppos = p.position();
var epos = e.position();
if (!paused) {
if (
(
(ppos.left + p.width() < epos.left) ||
(ppos.left > epos.left + e.width())
) ||
(
(ppos.top + p.height() < epos.top) ||
(ppos.top > epos.top + e.height())
)
) {
return false;
} else {
return true;
}
}
};
my.checkAsteroid = function (paused) {
var p = $("#player");
var a = $("#asteroid");
var ppos = p.position();
var apos = a.position();
if (!paused) {
if (
(
(ppos.left + p.width() < apos.left) ||
(ppos.left > apos.left + a.width())
) ||
(
(ppos.top + p.height() < apos.top) ||
(ppos.top > apos.top + a.height())
)
) {
return false;
} else {
return true;
}
}
};
my.play = function () {
_enemy_ship.move(_game_paused);
_asteroid.move(_game_paused);
if (my.checkCollisions(_game_paused)) {
_health --;
my.displayHealth();
} else if (
my.checkAsteroid(_game_paused)) {
_health --;
my.displayHealth();
}
};
return my;
}
var game = new Game();
game.checkKeys();
game.displayHealth();
game.displayTimer();
game.increaseTime();
setInterval(game.moveBackground, game.background_speed);
setInterval(game.play, game.background_speed);
});
I'm relatively new to programming. I took a class in high school, which was very mediocre. I'm now taking some starter courses in college, and my assignment is to improve a generic space game (which I have already started doing). I have a div for the timer, but for some reason, I can't get any functions to increase the _time variable. It's almost as though they're not allowed to access it. I have a function called "runTimer", which is supposed to increase "_time" by one every time it is run. I have another function called "increaseTime", which is supposed to run "runTimer" every 1000 milliseconds. The variable never seems to increase though. This hasn't been my first spaghetti code implementation of a timer, since I've tried various things over the past few hours. I just can't understand why the variable won't increase.
This is a big hunk of code. As RobG pointed out, try to work on paring back your question to the minimal, complete, and verifiable example you can.
That said, at a glance, it would appear that your timer probably is updating. At least _time is.
The problem is likely you are never re-drawing your div, so it isn't showing the updated value. You need to call game.displayTimer() every time _time updates.
Probably the easiest place to add it would be in your setInterval() in increaseTime():
my.increaseTime = function () {
setInterval(function(){
runTimer();
my.displayTime();
}, 1000)
}

Uncaught TypeError: $(...).find(...).once is not a function in bootstrap/js/bootstrap.js?

I have installed bootstrap theme for building responsive theme then I installed jquery_update module as documentation in theme project and everything seems ok expect below js error appears in inspect elements console:
Uncaught TypeError: $(...).find(...).once is not a function in
bootstrap/js/bootstrap.js?o5l669
Any one please can help me?
this is the bootstrap.js:
/**
* #file
* bootstrap.js
*
* Provides general enhancements and fixes to Bootstrap's JS files.
*/
var Drupal = Drupal || {};
(function($, Drupal){
"use strict";
Drupal.behaviors.bootstrap = {
attach: function(context) {
// Provide some Bootstrap tab/Drupal integration.
$(context).find('.tabbable').once('bootstrap-tabs', function () {
var $wrapper = $(this);
var $tabs = $wrapper.find('.nav-tabs');
var $content = $wrapper.find('.tab-content');
var borderRadius = parseInt($content.css('borderBottomRightRadius'), 10);
var bootstrapTabResize = function() {
if ($wrapper.hasClass('tabs-left') || $wrapper.hasClass('tabs-right')) {
$content.css('min-height', $tabs.outerHeight());
}
};
// Add min-height on content for left and right tabs.
bootstrapTabResize();
// Detect tab switch.
if ($wrapper.hasClass('tabs-left') || $wrapper.hasClass('tabs-right')) {
$tabs.on('shown.bs.tab', 'a[data-toggle="tab"]', function (e) {
bootstrapTabResize();
if ($wrapper.hasClass('tabs-left')) {
if ($(e.target).parent().is(':first-child')) {
$content.css('borderTopLeftRadius', '0');
}
else {
$content.css('borderTopLeftRadius', borderRadius + 'px');
}
}
else {
if ($(e.target).parent().is(':first-child')) {
$content.css('borderTopRightRadius', '0');
}
else {
$content.css('borderTopRightRadius', borderRadius + 'px');
}
}
});
}
});
}
};
/**
* Bootstrap Popovers.
*/
Drupal.behaviors.bootstrapPopovers = {
attach: function (context, settings) {
if (settings.bootstrap && settings.bootstrap.popoverEnabled) {
var elements = $(context).find('[data-toggle="popover"]').toArray();
for (var i = 0; i < elements.length; i++) {
var $element = $(elements[i]);
var options = $.extend(true, {}, settings.bootstrap.popoverOptions, $element.data());
$element.popover(options);
}
}
}
};
/**
* Bootstrap Tooltips.
*/
Drupal.behaviors.bootstrapTooltips = {
attach: function (context, settings) {
if (settings.bootstrap && settings.bootstrap.tooltipEnabled) {
var elements = $(context).find('[data-toggle="tooltip"]').toArray();
for (var i = 0; i < elements.length; i++) {
var $element = $(elements[i]);
var options = $.extend(true, {}, settings.bootstrap.tooltipOptions, $element.data());
$element.tooltip(options);
}
}
}
};
/**
* Anchor fixes.
*/
var $scrollableElement = $();
Drupal.behaviors.bootstrapAnchors = {
attach: function(context, settings) {
var i, elements = ['html', 'body'];
if (!$scrollableElement.length) {
for (i = 0; i < elements.length; i++) {
var $element = $(elements[i]);
if ($element.scrollTop() > 0) {
$scrollableElement = $element;
break;
}
else {
$element.scrollTop(1);
if ($element.scrollTop() > 0) {
$element.scrollTop(0);
$scrollableElement = $element;
break;
}
}
}
}
if (!settings.bootstrap || !settings.bootstrap.anchorsFix) {
return;
}
var anchors = $(context).find('a').toArray();
for (i = 0; i < anchors.length; i++) {
if (!anchors[i].scrollTo) {
this.bootstrapAnchor(anchors[i]);
}
}
$scrollableElement.once('bootstrap-anchors', function () {
$scrollableElement.on('click.bootstrap-anchors', 'a[href*="#"]:not([data-toggle],[data-target])', function(e) {
this.scrollTo(e);
});
});
},
bootstrapAnchor: function (element) {
element.validAnchor = element.nodeName === 'A' && (location.hostname === element.hostname || !element.hostname) && element.hash.replace(/#/,'').length;
element.scrollTo = function(event) {
var attr = 'id';
var $target = $(element.hash);
if (!$target.length) {
attr = 'name';
$target = $('[name="' + element.hash.replace('#', '') + '"');
}
var offset = $target.offset().top - parseInt($scrollableElement.css('paddingTop'), 10) - parseInt($scrollableElement.css('marginTop'), 10);
if (this.validAnchor && $target.length && offset > 0) {
if (event) {
event.preventDefault();
}
var $fakeAnchor = $('<div/>')
.addClass('element-invisible')
.attr(attr, $target.attr(attr))
.css({
position: 'absolute',
top: offset + 'px',
zIndex: -1000
})
.appendTo(document);
$target.removeAttr(attr);
var complete = function () {
location.hash = element.hash;
$fakeAnchor.remove();
$target.attr(attr, element.hash.replace('#', ''));
};
if (Drupal.settings.bootstrap.anchorsSmoothScrolling) {
$scrollableElement.animate({ scrollTop: offset, avoidTransforms: true }, 400, complete);
}
else {
$scrollableElement.scrollTop(offset);
complete();
}
}
};
}
};
})(jQuery, Drupal);
I have same issue and my solution is exclude bootstrap.js on my custom theme.
also you can alter bootstrap.js
Maybe The problem is because of two version ov jquery load on your page, inspect your javascript and if there is two version of jquery, let one exist and remove another.
In my case, there are 2 jquery files (core, theme). I removed it from theme. it works perfectly fine.

Combining two Javascript functions to one window.onload not working

I have two functions that I want to run on window.onload event but only the last function seems to work so far. One function is for an image slider and the other one retrieves data from a google spreadsheet cell.
function fun1() { //image slider
var ul;
var li_items;
var imageNumber;
var imageWidth;
var prev, next;
var currentPostion = 0;
var currentImage = 0;
function init() {
ul = document.getElementById('image_slider');
li_items = ul.children;
imageNumber = li_items.length;
imageWidth = li_items[0].children[0].clientWidth;
ul.style.width = parseInt(imageWidth * imageNumber) + 'px';
prev = document.getElementById("prev");
next = document.getElementById("next");
prev.onclick = function() {
onClickPrev();
};
next.onclick = function() {
onClickNext();
};
}
function animate(opts) {
var start = new Date;
var id = setInterval(function() {
var timePassed = new Date - start;
var progress = timePassed / opts.duration;
if (progress > 1) {
progress = 1;
}
var delta = opts.delta(progress);
opts.step(delta);
if (progress == 1) {
clearInterval(id);
opts.callback();
}
}, opts.delay || 17);
}
function slideTo(imageToGo) {
var direction;
var numOfImageToGo = Math.abs(imageToGo - currentImage);
direction = currentImage > imageToGo ? 1 : -1;
currentPostion = -1 * currentImage * imageWidth;
var opts = {
duration: 1000,
delta: function(p) {
return p;
},
step: function(delta) {
ul.style.left = parseInt(currentPostion + direction * delta * imageWidth * numOfImageToGo) + 'px';
},
callback: function() {
currentImage = imageToGo;
}
};
animate(opts);
}
function onClickPrev() {
if (currentImage == 0) {
slideTo(imageNumber - 1);
} else {
slideTo(currentImage - 1);
}
}
function onClickNext() {
if (currentImage == imageNumber - 1) {
slideTo(0);
} else {
slideTo(currentImage + 1);
}
}
}
function fun2() {
// Google spreadsheet js
google.load('visualization', '1', {
callback: function() {
var query = new google.visualization.Query('https://docs.google.com/spreadsheets/d/1sA7M5kG6Xo8YScD1Df38PIA_G0bvhGRdqoExXg0KJTs/gviz/tq?tqx=out:html&tq?gid=0&headers=0&range=A1:C');
query.send(displayData);
}
});
function displayData(response) {
numRows = response.getDataTable().getValue(0, 0);
document.getElementById('data').innerHTML = numRows;
}
}
var addFunctionOnWindowLoad = function(callback) {
if (window.addEventListener) {
window.addEventListener('load', callback, false);
} else {
window.attachEvent('onload', callback);
}
}
addFunctionOnWindowLoad(fun1);
addFunctionOnWindowLoad(fun2);
This is the answer I've tried link but I can't seem to figure out where I'm going wrong.
This is what I ended up doing, and now all the functions work.
var ul;
var li_items;
var imageNumber;
var imageWidth;
var prev, next;
var currentPostion = 0;
var currentImage = 0;
function init() {
ul = document.getElementById('image_slider');
li_items = ul.children;
imageNumber = li_items.length;
imageWidth = li_items[0].children[0].clientWidth;
ul.style.width = parseInt(imageWidth * imageNumber) + 'px';
prev = document.getElementById("prev");
next = document.getElementById("next");
prev.onclick = function() {
onClickPrev();
};
next.onclick = function() {
onClickNext();
};
}
function animate(opts) {
var start = (new Date());
var id = setInterval(function() {
var timePassed = (new Date()) - start;
var progress = timePassed / opts.duration;
if (progress > 1) {
progress = 1;
}
var delta = opts.delta(progress);
opts.step(delta);
if (progress == 1) {
clearInterval(id);
opts.callback();
}
}, opts.delay || 17);
//return id;
}
function slideTo(imageToGo) {
var direction;
var numOfImageToGo = Math.abs(imageToGo - currentImage);
// slide toward left
direction = currentImage > imageToGo ? 1 : -1;
currentPostion = -1 * currentImage * imageWidth;
var opts = {
duration: 1000,
delta: function(p) {
return p;
},
step: function(delta) {
ul.style.left = parseInt(currentPostion + direction * delta * imageWidth * numOfImageToGo) + 'px';
},
callback: function() {
currentImage = imageToGo;
}
};
animate(opts);
}
function onClickPrev() {
if (currentImage === 0) {
slideTo(imageNumber - 1);
} else {
slideTo(currentImage - 1);
}
}
function onClickNext() {
if (currentImage == imageNumber - 1) {
slideTo(0);
} else {
slideTo(currentImage + 1);
}
}
window.onload = init;
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
function fun2() {
// Google spreadsheet js
google.load('visualization', '1', {
callback: function() {
var query = new google.visualization.Query('https://docs.google.com/spreadsheets/d/1sA7M5kG6Xo8YScD1Df38PIA_G0bvhGRdqoExXg0KJTs/gviz/tq?tqx=out:html&tq?gid=0&headers=0&range=A1:C');
query.send(displayData);
}
});
function displayData(response) {
numRows = response.getDataTable().getValue(0, 0);
document.getElementById('data').innerHTML = numRows;
}
}
addLoadEvent(fun2);
addLoadEvent(function() {
});
I found this function a while ago and believe it or not, I still need to use it every so often. addEventLoad() Just call addEventLoad while passing the function to load.
"The way this works is relatively simple: if window.onload has not already been assigned a function, the function passed to addLoadEvent is simply assigned to window.onload. If window.onload has already been set, a brand new function is created which first calls the original onload handler, then calls the new handler afterwards."
This snippet will load 3 functions on window.onload
Snippet
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
function alert1() {
alert("First Function Loaded");
}
function alert2() {
alert("Second Function Loaded");
}
function alert3(str) {
alert("Third Function Loaded; Msg: " + str);
}
addLoadEvent(alert1);
addLoadEvent(alert2);
addLoadEvent(function() {
alert3("This works");
});
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>

Popup window Maximize button

How to enable the maximize and restore button of the popup window using Javascript?
You have to open a popup like this:
window.open('url', 'windowname', 'location=0, status=0, resizable=1, scrollbars=1, width=400, height=400');
The trick is to make the window resizable. Search for the window.open() function documentation.
Using the code I pasted on the bottom, you can emulate these buttons by creating them in your website interface.
To maximise: save the current position with Namespace.outerPositionGet() and size with Namespace.outerSizeGet(), then do Namespace.outerPositionSet({left:0,top:0}) and Namespace.outerSizeSet({width:window.screen.availWidth, height:window.screen.availHeight}).
To restore: just set position and size which were saved when maximising.
var Namespace = (function() {
var N, W, framePosition, frameChrome, setFramePosition, setFrameChrome;
N = {};
W = window;
setFramePosition = function() {
var tmp0;
if (typeof framePosition !== 'undefined') {
return;
}
tmp0 = {
top : W.screenTop,
left : W.screenLeft
};
W.moveTo(tmp0.left, tmp0.top);
framePosition = {
top : tmp0.top - W.screenTop,
left : tmp0.left - W.screenLeft
};
W.moveTo(tmp0.left + framePosition.left, tmp0.top + framePosition.top);
};
setFrameChrome = function() {
var tmp0, tmp1;
if (typeof frameChrome !== 'undefined') {
return;
}
tmp0 = N.innerSizeGet();
W.resizeTo(tmp0.width, tmp0.height);
tmp1 = N.innerSizeGet();
frameChrome = {
width : tmp0.width - tmp1.width,
height : tmp0.height - tmp1.height
};
W.resizeTo(tmp0.width + tmp1.width, tmp0.height + tmp1.height);
};
N.outerPositionSet = function(position) {
W.moveTo(position.left, position.top);
};
N.outerPositionGet = function() {
if (typeof W.screenTop !== 'undefined') {
setFramePosition();
N.outerPositionGet = function() {
return {
top : W.screenTop + framePosition.top,
left : W.screenLeft + framePosition.left
};
};
} else if (typeof W.screenY !== 'undefined') {
N.outerPositionGet = function() {
return {
top : W.screenY,
left : W.screenX
};
};
} else {
N.outerPositionGet = function() {
return {
top : 0,
left : 0
};
};
}
return N.outerPositionGet();
};
N.outerSizeSet = function(size) {
W.resizeTo(size.width, size.height);
};
N.outerSizeGet = function() {
if (W.outerWidth) {
N.outerSizeGet = function() {
return {
width : W.outerWidth,
height : W.outerHeight
};
};
} else {
setFrameChrome();
N.outerSizeGet = function() {
var size;
size = N.innerSizeGet();
size.width += frameChrome.width;
size.height += frameChrome.height;
return size;
};
}
return N.outerSizeGet();
};
N.innerSizeSet = function(size) {
setFrameChrome();
N.innerSizeSet = function(size) {
W.resizeTo(size.width + frameChrome.width, size.height + frameChrome.height);
};
N.innerSizeSet(size);
};
N.innerSizeGet = function() {
if (typeof W.innerHeight === 'number') {
N.innerSizeGet = function() {
return {
width : W.innerWidth,
height : W.innerHeight
};
};
return N.innerSizeGet();
}
var isDocumentElementHeightOff, node;
isDocumentElementHeightOff = function() {
var div, r;
div = W.document.createElement('div');
div.style.height = "2500px";
W.document.body.insertBefore(div, W.document.body.firstChild);
r = W.document.documentElement.clientHeight > 2400;
W.document.body.removeChild(div);
return r;
};
if (typeof W.document.clientWidth === 'number') {
node = W.document;
} else if ((W.document.documentElement && W.document.documentElement.clientWidth === 0) || isDocumentElementHeightOff()) {
node = W.document.body;
} else if (W.document.documentElement.clientHeight > 0) {
node = W.document.documentElement;
}
N.innerSizeGet = function() {
return {
width : node.clientWidth,
height : node.clientHeight
};
};
return N.innerSizeGet();
};
return N;
})();
I'm assuming you're talking about the alert popup? This can't be done with standard JavaScript.
You best solution would be to try using some of the many popup solutions that have been developed for the various JavaScript frameworks (e.g. jQuery), and seeing if you can tailor this to your particular use.
try this also. its working for me...
window.open('fileURL','status=1,directories=1,menubar=0,toolbar=0,
scrollbars=1,titlebar=0,dialog=1)
You can't, sorry - at least, not universally. The popup is implementation-dependent and there aren't any standard JavaScript methods for controlling it in the manner you describe.

can anybody help me how to deal this 2 javascript conflict

The First Script that allows me to create a moving clouds and loop after if reaches the end
// dvdp - volll - iphone alert
var agent=navigator.userAgent.toLowerCase();
var is_iphone = (agent.indexOf('iphone')!=-1);
// TJP - volll
var stispace=new Array();
var jumpspace=new Array();
var skyspace=new Array; skyspace['dir']=-1; skyspace['place']=0;
var smokespace=0;
var shipspace=0;
var cloudspace=new Array();
var stagespace=2000;
cloudspace[1]=new Array(); cloudspace[1]['w']=219; cloudspace[1]['p']=2000;
cloudspace[2]=new Array(); cloudspace[2]['w']=128; cloudspace[2]['p']=1050;
cloudspace[3]=new Array(); cloudspace[3]['w']=51; cloudspace[3]['p']=1200;
cloudspace[4]=new Array(); cloudspace[4]['w']=112; cloudspace[4]['p']=120;
cloudspace[5]=new Array(); cloudspace[5]['w']=219; cloudspace[5]['p']=130;
cloudspace[6]=new Array(); cloudspace[6]['w']=219; cloudspace[6]['p']=1020;
cloudspace[7]=new Array(); cloudspace[7]['w']=219; cloudspace[7]['p']=1400;
var movespace='';
var scrollspace=0;
function $(id) {
return document.getElementById(id);
}
function smoothto(whereto) {
wheretoreal=whereto;
if(scrollspace == 1) {return false;}
if(whereto == 'section_about_who') { whereto='section_about';}
if(whereto == 'section_about_contact') { whereto='section_about';}
scrollspace=1;
wheretoscroll=0;
wherefromscroll=topget();
for(smt=0;smt<pag_sections_name.length;smt++) {
if(smt>0) {wheretoscroll+=pag_sections_height[smt-1]}
if(pag_sections_name[smt] == whereto) {smt=pag_sections_name.length;}
}
if(wherefromscroll==wheretoscroll) {
scrollspace=0;
window.location='#'+wheretoreal;
return false;
}else{
window.paused=1;
clearInterval(int_TJPfloat);
clearInterval(int_TJProllsky);
}
$('vollltv').style.height='0';
tmp=new Array();
steps=20;
for(smt=1;smt<=steps;smt++) {
pt=smt/steps;
if(pt == .5) {
multi=1.5
} else {
multi=(Math.sqrt(Math.abs(2*pt-1))*(2*pt-1)/Math.abs(2*pt-1)+1)/2;
}
multi=Math.sqrt(smt/steps);
tmp[smt]='window.scroll(0,'+(wherefromscroll+(wheretoscroll-wherefromscroll)*multi)+');';
}
tmp[steps]+="window.location='#"+wheretoreal+"';$('vollltv').style.height='278px'; scrollspace=0;";
tmp[steps]+=" window.int_TJProllsky=undefined; window.int_TJProllsky=setInterval('TJProllsky();',200);";
tmp[steps]+="window.int_TJPfloat=undefined; window.int_TJPfloat=setInterval('TJPfloat();',50);";
tmp[steps]+="window.paused=0; ";
//alert(tmp.join("\n"));
ttt=Math.random();
stispace[ttt]=tmp;
setTI(ttt,10);
return false;
}
function volllresize() {
d=document.body.clientWidth;
if(d && d>1000) {
stagespace=d;
}
if($('inter4')) {
if (self.innerHeight) {
ch = self.innerHeight;
}
else if (document.documentElement && document.documentElement.clientHeight) {
ch = document.documentElement.clientHeight;
}
else if (document.body) {
ch = document.body.clientHeight;
}
if(ch>600) {
$('inter4').style.height=(ch-534)+'px';
}
}
}
function volllinit(section) {
if(section == 'inter0' && !is_iphone) {
volllresize();
window.onresize=volllresize;
for(i=1;i<cloudspace.length;i++) {
cloudspace[i]['p']*=d/1000;
}
//if(tmp.split('#')[1] == '' || tmp.split('#')[1] == 'section_main') {
// setTimeout('scroll(0,200);',100);
//}
}
else if(section == 'about') {
window.int_TJPfloat=setInterval("TJPfloat();",50);
tmp=location.href+'#';
}
}
window.paused=0;
function TJPmovecloud(cid,pos) {
if(pos > stagespace && window.paused>0 ) {
return;
}
if(pos+cloudspace[cid]['w']>stagespace) {
$('s_cloud'+cid).style.width=stagespace-pos+'px';
} else {
$('s_cloud'+cid).style.width=cloudspace[cid]['w']+'px';
}
$('s_cloud'+cid).style.left=pos+'px';
}
function TJPfloat() {
sy=Math.floor(Math.sin(smokespace)*20+20);
sy2=Math.floor(Math.sin(smokespace)*10+10);
sx=Math.floor(Math.cos(smokespace)*3+3);
//if(smokespace==0) {alert('about.css-be belerakni:'+sy+'px 0 0 '+sx+'px');}
$('g_wave1').style.margin=sy+'px 0 0 '+sy+'px';
$('g_wave2').style.margin=sy2+'px 0 0 '+sy2+'px';
smokespace+=.05; if(smokespace>2*Math.PI) {smokespace-=2*Math.PI;}
if($('inter1')) {
for(i=1;i<cloudspace.length;i++) {
if(cloudspace[i]['p'] >= stagespace) {cloudspace[i]['p']=-cloudspace[i]['w'];}
else if(cloudspace[i]['p'] <= -cloudspace[i]['w']) {cloudspace[i]['p']=stagespace;}
cloudspace[i]['p']-=1+cloudspace[i]['w']/200;
TJPmovecloud(i,cloudspace[i]['p']);
}
}
}
The Second script is the one that creates the bouncing effect like the one on tim van damme
<script type="text/javascript" charset="utf-8">
$('.navigation').each(function () {
var $links = $(this).find('a'),
panelIds = $links.map(function() { return this.hash; }).get().join(","),
$panels = $(panelIds),
$panelwrapper = $panels.filter(':first').parent(),
delay = 500,
heightOffset = 40; // we could add margin-top + margin-bottom + padding-top + padding-bottom of $panelwrapper
$panels.hide();
$links.click(function () {
var link = this,
$link = $(this);
// ignore if already visible
if ($link.is('.selected')) {
return false;
}
$links.removeClass('selected');
$link.addClass('selected');
document.title = 'jQuery look: Tim Van Damme - ' + $link.text();
if ($.support.opacity) {
$panels.stop().animate({opacity: 0 }, delay);
}
$panelwrapper.stop().animate({
height: 0
}, delay, function () {
var height = $panels.hide().filter(link.hash).css('opacity', 1).show().height() + heightOffset;
$panelwrapper.animate({
height: height
}, delay);
});
});
$links.filter(window.location.hash ? '[hash=' + window.location.hash + ']' : ':first').click();
});
</script>
This is the error I received
TypeError: Result of expression '$('.navigation')' [null] is not an object. Can anybody please explain to me why this error occur?
You receive this error because if the following function in the first code:
function $(id) {
return document.getElementById(id);
}
This overlaps with jQuery's $ function which is required by the second piece of code. rewrite the first piece of code to use jQuery's $() function or rename $() in the first piece of code and find/replace.
Do you have html elements with the class name "navigation" in your code?

Categories

Resources