can't call jquery custom function in separate js file - javascript

I'm trying to move my slideshow function runShow() into a seperate .js file named panzoomslideshow.js
This is simply to separate my script into another file that is then used by all my pages.
I can get the resize trigger to fire an alert, but it won't call the runShow () function - what am I doing wrong? I got it to run before, but now I can't!
The script to call panzoomslideshow.js in the head of my web page and this is where on each resize, the runShow() function in the panzoomslideshow.js file function is called:
<script type="text/javascript"> //*** This will reload the player upon resizing! ***\\
var resizeTimer;
$(window).resize(function() {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(runShow(), 100);
});
</script>
I should note I also tried putting the $(function(){ }) around it, but then all the variables can't be accessed from the runShow() function which won't run...
panzoomslideshow.js ->
var dur = 2000;
var pDur = 4500;
var vp_width = window.innerWidth;
var vp_height = window.innerHeight;
var width_large = 880;
var height_large = 495;
var width_medium = 720;
var height_medium = 405;
var width_small = 480;
var height_small = 270;
var width_micro = 320;
var height_micro = 180;
var slide_width;
var slide_height;
var anim_width;
var anim_height;
var margin_top;
var margin_left;
alert("The Global variables are set, like vp_width and vp_height are "+vp_width+" and "+vp_height);
runShow();
function runShow() {
if(vp_width <= 320){ //SET Micro size
slide_width = width_micro;
slide_height = height_micro;
anim_width = (width_micro * 1.2);
anim_height = (height_micro * 1.2);
margin_top = -30;
margin_left = -60;
} else if(vp_width <= 480){ //SET small size
slide_width = width_small;
slide_height = height_small;
anim_width = (width_small * 1.2);
anim_height = (height_small * 1.2);
margin_top = -70;
margin_left = -150;
} else if(vp_width <= 1140){ //SET Medium size
slide_width = width_medium;
slide_height = height_medium;
anim_width = (width_medium * 1.2);
anim_height = (height_medium * 1.2);
margin_top = -80;
margin_left = -180;
} else if(vp_width <= 1400){ //SET Large size
slide_width = width_large;
slide_height = height_large;
anim_width = (width_large * 1.2);
anim_height = (height_large * 1.2);
margin_top = -100;
margin_left = -200;
} else {
//do nothing since the screen size is too small???
}
alert("runShow() is invoked! Slideshow Width and Height will be "+slide_width+" and "+slide_height+" The Global variables are set, like vp_width and vp_height are "+vp_width+" and "+vp_height);
$(".carousel").carouFredSel({
items: {
visible: 1,
width: slide_width,
height: slide_height
},
scroll: {
fx: "fade",
easing: "linear",
duration: dur,
timeoutDuration: pDur,
onBefore: function( data ) {
animate( data.items.visible, pDur + ( dur * 3 ) );
},
onAfter: function( data ) {
data.items.old.find( "img" ).stop().css({
width: slide_width,
height: slide_height,
marginTop: 0,
marginLeft: 0
});
}
},
onCreate: function( data ) {
animate( data.items, pDur + ( dur *2 ) );
}
});
function animate( item, dur ) {
var obj = {
width: anim_width,
height: anim_height
};
switch( Math.ceil( Math.random() * 2 ) ) {
case 1:
obj.marginTop = 0;
break;
case 2:
obj.marginTop = -80
break;
}
switch( Math.ceil( Math.random() * 2 ) ) {
case 1:
obj.marginLeft = 0;
break;
case 2:
obj.marginLeft = -170
break;
}
item.find( "img" ).animate(obj, dur, "linear" );
}
};

:)
Did you try this?
$(document).ready(function () {
//your javascript code
});

Related

Random movement of circles created by the script

I have a function that craeates divs with a circle.
Now they are all created and appear at the beginning of the page and go further in order.
Next, I need each circle to appear in a random place. I did this.
Now I need all of them to move randomly across the entire page, I have difficulties with this.
Here is an example of how everything works for one element that is already on the page.
https://jsfiddle.net/quej8wko/
But when I add this code, all my created circles don't move.
I get an error:
"message": "Uncaught TypeError: Cannot set properties of null (setting 'willChange')",
This is probably due to the fact that initially there are no circles on the page. How can I connect the code so that all created circles move?
//creating circles
var widthHeight = 40; // <-- circle width
var margin = 20; // <-- margin - is it necessary ?
var delta = widthHeight + margin;
function createDiv(id, color) {
let div = document.createElement('div');
var currentTop = 0;
var documentHeight = document.documentElement.clientHeight;
var documentWidth = document.documentElement.clientWidth;
div.setAttribute('class', id);
if (color === undefined) {
let colors = ['#35def2', '#35f242', '#b2f235', '#f2ad35', '#f24735', '#3554f2', '#8535f2', '#eb35f2', '#f2359b', '#f23547'];
div.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
}
else {
div.style.backgroundColor = color;
}
div.classList.add("circle");
div.classList.add("animation");
// Get the random positions minus the delta
currentTop = Math.floor(Math.random() * documentHeight) - delta;
currentLeft = Math.floor(Math.random() * documentWidth) - delta;
// Keep the positions between -20px and the current positions
var limitedTop = Math.max(margin * -1, currentTop);
var limitedLeft = Math.max(margin * -1, currentLeft);
div.style.top = limitedTop + "px";
div.style.left = limitedLeft + "px";
document.body.appendChild(div);
}
let i = 0;
const oneSecond = 1000;
setInterval(() => {
i += 1;
createDiv(`circle${i}`)
}, oneSecond);
//move circles
function RandomObjectMover(obj, container) {
this.$object = obj;
this.$container = container;
this.container_is_window = container === window;
this.pixels_per_second = 250;
this.current_position = { x: 0, y: 0 };
this.is_running = false;
}
// Set the speed of movement in Pixels per Second.
RandomObjectMover.prototype.setSpeed = function(pxPerSec) {
this.pixels_per_second = pxPerSec;
}
RandomObjectMover.prototype._getContainerDimensions = function() {
if (this.$container === window) {
return { 'height' : this.$container.innerHeight, 'width' : this.$container.innerWidth };
} else {
return { 'height' : this.$container.clientHeight, 'width' : this.$container.clientWidth };
}
}
RandomObjectMover.prototype._generateNewPosition = function() {
// Get container dimensions minus div size
var containerSize = this._getContainerDimensions();
var availableHeight = containerSize.height - this.$object.clientHeight;
var availableWidth = containerSize.width - this.$object.clientHeight;
// Pick a random place in the space
var y = Math.floor(Math.random() * availableHeight);
var x = Math.floor(Math.random() * availableWidth);
return { x: x, y: y };
}
RandomObjectMover.prototype._calcDelta = function(a, b) {
var dx = a.x - b.x;
var dy = a.y - b.y;
var dist = Math.sqrt( dx*dx + dy*dy );
return dist;
}
RandomObjectMover.prototype._moveOnce = function() {
// Pick a new spot on the page
var next = this._generateNewPosition();
// How far do we have to move?
var delta = this._calcDelta(this.current_position, next);
// Speed of this transition, rounded to 2DP
var speed = Math.round((delta / this.pixels_per_second) * 100) / 100;
//console.log(this.current_position, next, delta, speed);
this.$object.style.transition='transform '+speed+'s linear';
this.$object.style.transform='translate3d('+next.x+'px, '+next.y+'px, 0)';
// Save this new position ready for the next call.
this.current_position = next;
};
RandomObjectMover.prototype.start = function() {
if (this.is_running) {
return;
}
// Make sure our object has the right css set
this.$object.willChange = 'transform';
this.$object.pointerEvents = 'auto';
this.boundEvent = this._moveOnce.bind(this)
// Bind callback to keep things moving
this.$object.addEventListener('transitionend', this.boundEvent);
// Start it moving
this._moveOnce();
this.is_running = true;
}
RandomObjectMover.prototype.stop = function() {
if (!this.is_running) {
return;
}
this.$object.removeEventListener('transitionend', this.boundEvent);
this.is_running = false;
}
// Init it
var x = new RandomObjectMover(document.querySelector(".circle"), window);
// Start it off
x.start();
.circle {
clip-path: circle(50%);
height: 40px;
width: 40px;
margin: 20px;
position: absolute;
}
I have modified the snippet which works as you expected.
There was a mistake where you were initializing and creating the object instance only once and none of the div elements that you created inside the setInterval function never got Instantiated.
I think you are just starting out with JavaScript with this sample project.
Below are few suggestions:
Learn to debug the code. You should be using dev tools by making use of debugger statement where it takes you to the source code to analyze the variable scope and stack during the runtime. console.log also helps in few situations.
I could see a lot of confusing naming convention (You have named the create div parameter as id but creating a div class using that id)
Try using ES6 features (class syntax is really good when writing OOP in JS although it's just a syntactic sugar for prototype)
//creating circles
var widthHeight = 40; // <-- circle width
var margin = 20; // <-- margin - is it necessary ?
var delta = widthHeight + margin;
function createAndInitializeDivObject(id, color) {
let div = document.createElement('div');
var currentTop = 0;
var documentHeight = document.documentElement.clientHeight;
var documentWidth = document.documentElement.clientWidth;
div.setAttribute('class', id);
if (color === undefined) {
let colors = ['#35def2', '#35f242', '#b2f235', '#f2ad35', '#f24735', '#3554f2', '#8535f2', '#eb35f2', '#f2359b', '#f23547'];
div.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
}
else {
div.style.backgroundColor = color;
}
div.classList.add("circle");
div.classList.add("animation");
// Get the random positions minus the delta
currentTop = Math.floor(Math.random() * documentHeight) - delta;
currentLeft = Math.floor(Math.random() * documentWidth) - delta;
// Keep the positions between -20px and the current positions
var limitedTop = Math.max(margin * -1, currentTop);
var limitedLeft = Math.max(margin * -1, currentLeft);
div.style.top = limitedTop + "px";
div.style.left = limitedLeft + "px";
document.body.appendChild(div);
var x = new RandomObjectMover(document.querySelector(`.${id}`), window);
x.start();
}
let i = 0;
const oneSecond = 1000;
setInterval(() => {
i += 1;
createAndInitializeDivObject(`circle${i}`)
}, oneSecond);
//move circles
function RandomObjectMover(obj, container) {
this.$object = obj;
this.$container = container;
this.container_is_window = container === window;
this.pixels_per_second = 250;
this.current_position = { x: 0, y: 0 };
this.is_running = false;
}
// Set the speed of movement in Pixels per Second.
RandomObjectMover.prototype.setSpeed = function(pxPerSec) {
this.pixels_per_second = pxPerSec;
}
RandomObjectMover.prototype._getContainerDimensions = function() {
if (this.$container === window) {
return { 'height' : this.$container.innerHeight, 'width' : this.$container.innerWidth };
} else {
return { 'height' : this.$container.clientHeight, 'width' : this.$container.clientWidth };
}
}
RandomObjectMover.prototype._generateNewPosition = function() {
// Get container dimensions minus div size
var containerSize = this._getContainerDimensions();
var availableHeight = containerSize.height - this.$object.clientHeight;
var availableWidth = containerSize.width - this.$object.clientHeight;
// Pick a random place in the space
var y = Math.floor(Math.random() * availableHeight);
var x = Math.floor(Math.random() * availableWidth);
return { x: x, y: y };
}
RandomObjectMover.prototype._calcDelta = function(a, b) {
var dx = a.x - b.x;
var dy = a.y - b.y;
var dist = Math.sqrt( dx*dx + dy*dy );
return dist;
}
RandomObjectMover.prototype._moveOnce = function() {
// Pick a new spot on the page
var next = this._generateNewPosition();
// How far do we have to move?
var delta = this._calcDelta(this.current_position, next);
// Speed of this transition, rounded to 2DP
var speed = Math.round((delta / this.pixels_per_second) * 100) / 100;
//console.log(this.current_position, next, delta, speed);
this.$object.style.transition='transform '+speed+'s linear';
this.$object.style.transform='translate3d('+next.x+'px, '+next.y+'px, 0)';
// Save this new position ready for the next call.
this.current_position = next;
};
RandomObjectMover.prototype.start = function() {
if (this.is_running) {
return;
}
// Make sure our object has the right css set
this.$object.willChange = 'transform';
this.$object.pointerEvents = 'auto';
this.boundEvent = this._moveOnce.bind(this)
// Bind callback to keep things moving
this.$object.addEventListener('transitionend', this.boundEvent);
// Start it moving
this._moveOnce();
this.is_running = true;
}
RandomObjectMover.prototype.stop = function() {
if (!this.is_running) {
return;
}
this.$object.removeEventListener('transitionend', this.boundEvent);
this.is_running = false;
}
// Init it
var x = new RandomObjectMover(document.querySelector(".circle"), window);
// Start it off
x.start();
.circle {
width: 35px;
height: 35px;
border-radius: 35px;
background-color: #ffffff;
border: 3px solid purple;
position: absolute;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="circle"></div>
<script src="app.js"></script>
</body>
</html>

wookmark plugin including grid as javascript

I have a question about the topic.
I use stackover at the first time.
I use JS wookmark plugin. by the way I make web pages.
One of pages with sidebar with open and close.
When I close the left sidebar, It makes a space left of article.
Usually It resizes width on no space. The open sidebar size is 260px. The close size is 70.
I use these but no action.
$(document).ready(function() {
var article_list = $("#grid-container article").get();
var outer = $('<div class="grid-outer"></div>').get(0);
var nowbox = false;
for ( var i = 0; i < article_list.length; i++ ) {
if($(article_list[i]).hasClass('area')){
nowbox = false;
$(outer).append(article_list[i]);
}
if($(article_list[i]).hasClass('area-box')) {
if(!nowbox) {
nowbox = $('<div class="gridbox"></div>').get(0);
$(outer).append(nowbox);
}
$(nowbox).append(article_list[i]);
}
}
$("#grid-container").empty();
$("#grid-container").append(outer);
var options = {
offset: 20, // Optional, the distance between grid items
autoResize: true,
fillEmptySpace: true,
};
var resizeTimer = null;
var gridarr = [];
var gridboxlist = $('.gridbox').get();
for ( var i = 0; i < gridboxlist.length; i++ ) {
gridarr[i] = new Wookmark( gridboxlist[i], options);
}
resize();
resizeTimer = setTimeout(function() {
resize();
}, 0);
$(window).resize(function(){
clearTimeout(resizeTimer);
resize();
resizeTimer = setTimeout(function() {
resize();
}, 0);
})
function resize(){
var gridboxlist = $('.gridbox').get();
$(gridboxlist).each(function(){
var window_w = window.outerWidth;
var outer_w = $(this).width();
if( window_w < 1400) {
var w = Math.floor((( outer_w - ( 20 * 1 )) / 2));
$(this).find('.area-box').css({
'width': w+'px'
});
} else {
var w = Math.floor((( outer_w - ( 20 * 2 )) / 3));
$(this).find('.area-box').css({
'width': w+'px'
});
}
});
if( 0 < gridarr.length ){
refresh();
}
}
function refresh(){
for ( var i = 0; i < gridarr.length; i++ ) {
gridarr[i].layout(true);
}
}
});

Tinder like function, appcelerator

I tried to re create a Tinder like function.
I found this code :
var win = Titanium.UI.createWindow({
backgroundColor: "#ffffff",
title: "win"
});
// animations
var animateLeft = Ti.UI.createAnimation({
left: -520,
transform: Ti.UI.create2DMatrix({rotate: 60}),
opacity: 0,
duration: 300
});
var animateRight = Ti.UI.createAnimation({
left: 520,
transform: Ti.UI.create2DMatrix({rotate: -60}),
opacity: 0,
duration: 300
});
var curX = 0;
win.addEventListener('touchstart', function (e) {
curX = parseInt(e.x, 10);
});
win.addEventListener('touchmove', function (e) {
if (!e.source.id || e.source.id !== 'oferta') {
return;
}
// Subtracting current position to starting horizontal position
var coordinates = parseInt(e.x, 10) - curX;
// Defining coordinates as the final left position
var matrix = Ti.UI.create2DMatrix({rotate: -(coordinates / 10)});
var animate = Ti.UI.createAnimation({
left: coordinates,
transform: matrix,
duration: 20
});
e.source.animate(animate);
e.source.left = coordinates;
});
win.addEventListener('touchend', function (e) {
if (!e.source.id || e.source.id !== 'oferta') {
return;
}
// No longer moving the window
if (e.source.left >= 75) {
e.source.animate(animateRight);
} else if (e.source.left <= -75) {
e.source.animate(animateLeft);
} else {
// Repositioning the window to the left
e.source.animate({
left: 0,
transform: Ti.UI.create2DMatrix({rotate: 0}),
duration: 300
});
}
});
for (var i = 0; i < 10; i++) {
var wrap = Ti.UI.createView({
"id": 'oferta',
"width": 320,
"height": 400,
"backgroundColor": (i % 2 == 0 ? "red" : "blue")
});
var text = Ti.UI.createLabel({
text: "row: " + i,
color: "black"
});
wrap.add(text);
win.add(wrap);
}
win.open();
But there's a weird behaviour.
Indeed, When I took the wrap view from the top, everythnig is OK but if I put my finger on the bottom on the wrap view, the image becomes crazy..
Try the code and You will see strange behaviour.
I use Titanium SDK 5.2.2
and iOS 9.3.1 on an iPhone 6.
Here s a video showing the weird thing: http://tinypic.com/player.php?v=x37d5u%3E&s=9#.Vx_zDaOLQb0
(Sorry for the video size)
Thanks for your help
Use this code to convert pxToDp and vice versa:
Put following code in your lib folder and include it
with require("measurement")
instead of require("alloy/measurement")
var dpi = Ti.Platform.displayCaps.dpi, density = Ti.Platform.displayCaps.density;
exports.dpToPX = function(val) {
switch (density) {
case "xxxhigh":
return 5 * val;
case "xxhigh":
return 4 * val;
case "xhigh":
return 3 * val;
case "high":
return 2 * val;
default:
return val;
}
};
exports.pxToDP = function(val) {
switch (density) {
case "xxxhigh":
return 5 / val;
case "xxhigh":
return 4 / val;
case "xhigh":
return val / 3;
case "high":
return val / 2;
default:
return val;
}
};
exports.pointPXToDP = function(pt) {
return {
x: exports.pxToDP(pt.x),
y: exports.pxToDP(pt.y)
};
};
Many thanks to all !!! It works using this code ::
var win = Titanium.UI.createWindow({
backgroundColor: "#ffffff",
title: "win"
});
// animations
var animateLeft = Ti.UI.createAnimation({
left: -520,
transform: Ti.UI.create2DMatrix({rotate: 60}),
opacity: 0,
duration: 300
});
var animateRight = Ti.UI.createAnimation({
left: 520,
transform: Ti.UI.create2DMatrix({rotate: -60}),
opacity: 0,
duration: 300
});
Ti.include('measurement.js');
var curX = 0;
var wrap = [];
var topWrap = 100; //(Titanium.Platform.displayCaps.platformHeight - 400) / 2;
var leftWrap = 50; //(Titanium.Platform.displayCaps.platformWidth - 320) / 2;
for (var i = 0; i < 10; i++) {
wrap[i] = Ti.UI.createView({
"id": 'oferta',
"width": Titanium.Platform.displayCaps.platformWidth - 100,
"height": Titanium.Platform.displayCaps.platformHeight - 300,
image:(i % 2 == 0 ? 'principale.png' : 'principale1.png'),
"backgroundColor": (i % 2 == 0 ? "red" : "blue"),
top:topWrap,
left:leftWrap,
});
wrap[i].addEventListener('touchstart', function (e) {
// curX = parseInt(e.x, 10);
curX = pxToDP(parseInt(e.x, 10));
// curY = pxToDP(parseInt(e.Y, 10));
});
wrap[i].addEventListener('touchmove', function (e) {
// Subtracting current position to starting horizontal position
// var coordinates = parseInt(e.x, 10) - curX;
// Defining coordinates as the final left position
var coordinatesX = pxToDP(parseInt(e.x, 10)) - curX;
//var coordinatesY = pxToDP(parseInt(e.y, 10)) - curY;
var matrix = Ti.UI.create2DMatrix({rotate: -(coordinatesX / 10)});
var animate = Ti.UI.createAnimation({
left: coordinatesX,
// top: coordinatesY,
transform: matrix,
duration: 10
});
e.source.animate(animate);
e.source.left = coordinatesX;
// e.source.top = coordinatesY;
});
wrap[i].addEventListener('touchend', function (e) {
// No longer moving the window
if (e.source.left >= 75) {
e.source.animate(animateRight);
} else if (e.source.left <= -75) {
e.source.animate(animateLeft);
} else {
// Repositioning the window to the left
e.source.animate({
left: leftWrap,
transform: Ti.UI.create2DMatrix({rotate: 0}),
duration: 300
});
}
});
win.add(wrap);
}
win.open();
And the measurement.js file is :
var dpi = Ti.Platform.displayCaps.dpi, density = Ti.Platform.displayCaps.density;
function dpToPX(val) {
switch (density) {
case "xxxhigh":
return 5 * val;
case "xxhigh":
return 4 * val;
case "xhigh":
return 3 * val;
case "high":
return 2 * val;
default:
return val;
}
};
function pxToDP(val) {
switch (density) {
case "xxxhigh":
return 5 / val;
case "xxhigh":
return 4 / val;
case "xhigh":
return val / 3;
case "high":
return val / 2;
default:
return val;
}
};
function pointPXToD(pt) {
return {
x: pxToDP(pt.x),
y: pxToDP(pt.y)
};
};
You have to convert px to dp.
var measurement = require('alloy/measurement');
win.addEventListener('touchstart', function (e) {
curX = measurement.pxToDP(parseInt(e.x, 10));
Ti.API.info("touchstart curX: " + curX);
});
...
win.addEventListener('touchmove', function (e) {
if (!e.source.id || e.source.id !== 'oferta') {
return;
}
// Subtracting current position to starting horizontal position
var coordinates = measurement.pxToDP(parseInt(e.x, 10)) - curX;
...

Creating a class of Crafty JS entity (class of a class?)

I am trying to create a class which creates a Crafty entity with specific properties. So far, the functions within the class do not run because 'this' refers to the window object
$(document).ready(function () {
Crafty.init(window.innerWidth, window.innerHeight);
var player = new controller(37,38,39,40);
player.d.color("red").attr({
w: 50,
h: 50,
x: 0,
y: 0
});
// Jump Height = velocity ^ 2 / gravity * 2
// Terminal Velocity = push * (1 / viscosity)
var gravity = 1;
var viscosity = 0.5;
var frame = (1 / 20);
var distanceMultiplier = 10; //pixels per meter
var timeMultiplier = 20; //relative to actual time
var keystart = [];
var keyboard = [];
function controller (controls) {
this.d = Crafty.e();
this.d.addComponent("2D, Canvas, Color, Collision");
this.d.collision();
this.d.mass = 1;
this.d.a = {
extradistance : 0,
velocity : 0,
acceleration : 0,
force : 0,
resistance : 0
};
this.d.a.push = 0;
this.d.v = {
extradistance : 0,
velocity : 0,
acceleration : 0,
force : 0
};
this.d.jumping = true;
this.d.onHit("Collision", function () {
var a = this.d.hit("Collision");
if (a) {
for (var b in a) {
this.d.x = this.d.x - a[b].normal.x * a[b].overlap;
this.d.y = this.d.y - a[b].normal.y * a[b].overlap;
if (a[b].normal.y < -0.5) {
this.d.jumping = false;
}
if (Math.abs(a[b].normal.x) < 0.2) {
this.d.v.velocity = this.d.v.velocity * a[b].normal.y * 0.2;
}
if (Math.abs(a[b].normal.y) < 0.2) {
this.d.a.velocity = this.d.a.velocity * a[b].normal.x * 0.2;
}
}
return;
}
});
this.d.physics = function () {
if (keyboard[arguments[1]] && !this.jumping) {
this.v.velocity = 5;
this.jumping = true;
}
if (keyboard[arguments[1]] && this.jumping) {
var now = new Date();
if (now.getTime() - keystart[arguments[1]].getTime() < 500) {
this.v.velocity = 5;
}
}
if (keyboard[arguments[0]] && keyboard[arguments[2]]) {
this.a.velocity = 0;
} else {
if (keyboard[arguments[0]]) {
this.a.velocity = -3;
}
if (keyboard[arguments[2]]) {
this.a.velocity = 3;
}
}
if (keyboard[arguments[3]]) {
this.v.velocity = -5;
}
this.a.force = this.a.push - this.a.resistance;
this.a.acceleration = this.a.force / this.mass;
this.a.velocity = this.a.velocity + (this.a.acceleration * frame);
this.a.extradistance = (this.a.velocity * frame);
this.a.resistance = this.a.velocity * viscosity;
this.attr({
x: (this.x + (this.a.extradistance * distanceMultiplier))
});
this.v.force = gravity * this.mass;
this.v.acceleration = this.v.force / this.mass;
this.v.velocity = this.v.velocity - (this.v.acceleration * frame);
this.v.extradistance = (this.v.velocity * frame);
this.attr({
y: (this.y - (this.v.extradistance * distanceMultiplier))
});
setTimeout(this.physics, (frame * 1000) / timeMultiplier);
};
this.d.listen = function(){ document.body.addEventListener("keydown", function (code) {
var then = new Date();
if (!keyboard[code.keyCode] && !this.jumping && code.keyCode == arguments[1]) { //only if not yet pressed it will ignore everything until keyup
keyboard[code.keyCode] = true; //start movement
keystart[code.keyCode] = then; //set time
}
if (!keyboard[code.keyCode] && code.keyCode != arguments[1]) { //only if not yet pressed it will ignore everything until keyup
keyboard[code.keyCode] = true; //start movement
keystart[code.keyCode] = then; //set time
}
});
};
}
player.d.physics();
player.d.listen();
document.body.addEventListener("keyup", function (code) {
keyboard[code.keyCode] = false;
});
});
In trying to put the functions as prototypes of the class, I run into a problem.
Crafty.init(500,500);
function block () {
block.d = Crafty.e("2D, Color, Canvas");
block.d.color("red");
block.d.attr({x:0,y:0,h:50,w:50});
}
block.d.prototype.green = function() {
this.color("green");
}
var block1 = new block();
block1.d.color();
If an object is defined in the constructor, I cannot use it to add a prototype to.
Generally in Crafty, we favor composition. That is, you extend an entity by adding more components to it. You can have kind of a hierarchy by having one component automatically add others during init.
I haven't looked through all of your example code, because there's a lot! But consider the second block:
function block () {
block.d = Crafty.e("2D, Color, Canvas");
block.d.color("red");
block.d.attr({x:0,y:0,h:50,w:50});
}
block.d.prototype.green = function() {
this.color("green");
}
var block1 = new block();
block1.d.color();
You're trying to combine Crafty's way of doing things (an entity component system) with classes in a way that's not very idiomatic. Better to do this:
// Define a new component with Crafty.c(), rather than creating a class
Crafty.c("Block", {
// On init, add the correct components and setup the color and dimensions
init: function() {
this.requires("2D, Color, Canvas")
.color("red")
.attr({x:0,y:0,h:50,w:50});
},
// method for changing color
green: function() {
this.color("green");
}
});
// Create an entity with Crafty.e()
block1 = Crafty.e("Block");
// It's not easy being green!
block1.green();

Javascript only displays in header, but want it to display on whole page

I am using a javascript for falling images. (1) I want the images to cover the whole page, but they are only displaying in the header area. I don't know what portion to change to make it cover the whole page. It's a wordpress site, so maybe that has something to do with it? I put the call to the script in the head section. This is the script:
var image="http://abyssinianguineapigtips.com/wp-content/uploads/2014/11/onepoop.png"; //Image path should be given here
var no = 15; // No of images should fall
var time = 0; // Configure whether image should disappear after x seconds (0=never):
var speed = 10; // Fix how fast the image should fall
var i, dwidth = 900, dheight =500;
var nht = dheight;
var toppos = 0;
if(document.all){
var ie4up = 1;
}else{
var ie4up = 0;
}
if(document.getElementById && !document.all){
var ns6up = 1;
}else{
var ns6up = 0;
}
function getScrollXY() {
var scrOfX = 10, scrOfY = 10;
if( typeof( window.pageYOffset ) == 'number' ) {
//Netscape compliant
scrOfY =window.pageYOffset;
scrOfX = window.pageXOffset;
} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
//DOM compliant
scrOfY = document.body.scrollTop;
scrOfX = document.body.scrollLeft;
} else if( document.documentElement &&
( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
//IE6 standards compliant mode
scrOfY = document.documentElement.scrollTop;
scrOfX = document.documentElement.scrollLeft;
}
return [ scrOfX, scrOfY ];
}
var timer;
function ranrot()
{
var a = getScrollXY()
if(timer)
{
clearTimeout(timer);
}
toppos = a[1];
dheight = nht+a[1];
//alert(dheight);
timer = setTimeout('ranrot()',2000);
}
ranrot();
function iecompattest()
{
if(document.compatMode && document.compatMode!="BackCompat")
{
return document.documentElement;
}else{
return document.body;
}
}
if (ns6up) {
dwidth = window.innerWidth;
dheight = window.innerHeight;
}
else if (ie4up) {
dwidth = iecompattest().clientWidth;
dheight = iecompattest().clientHeight;
}
nht = dheight;
var cv = new Array();
var px = new Array(); //position variables
var py = new Array(); //position variables
var am = new Array(); //amplitude variables
var sx = new Array(); //step variables
var sy = new Array(); //step variables
for (i = 0; i < no; ++ i) {
cv[i] = 0;
px[i] = Math.random()*(dwidth-100); // set position variables
py[i] = Math.random()*dheight; // set position variables
am[i] = Math.random()*20; // set amplitude variables
sx[i] = 0.02 + Math.random()/10; // set step variables
sy[i] = 0.7 + Math.random(); // set step variables
document.write("<div id=\"dot"+ i +"\" style=\"POSITION: absolute; Z-INDEX: "+ i +"; VISIBILITY: visible; TOP: 15px;LEFT: 15px;\"><img src='"+image+"' border=\"0\"><\/div>");
}
function animation() { // animation function
for (i = 0; i < no; ++ i) { // iterate for every dot
py[i] += sy[i];
if (py[i] > dheight-50) {
px[i] = Math.random()*(dwidth-am[i]-100);
py[i] = toppos;
sx[i] = 0.02 + Math.random()/10;
sy[i] = 0.7 + Math.random();
}
cv[i] += sx[i];
document.getElementById("dot"+i).style.top=py[i]+"px";
document.getElementById("dot"+i).style.left=px[i] + am[i]*Math.sin(cv[i])+"px";
}
atime=setTimeout("animation()", speed);
}
function hideimage(){
if (window.atime) clearTimeout(atime)
for (i=0; i<no; i++)
document.getElementById("dot"+i).style.visibility="hidden"
}
if (ie4up||ns6up){
animation();
if (time>0)
setTimeout("hideimage()", time*1000)
}
animation();
/* Free Script provided by HIOXINDIA */
/* visit us at http://www.hscripts.com */
/* This is a copyright product of hioxindia.com */
The page is here.
My second question is the best way to stop the script from executing when someone clicks on the stop sign image. I've read 10 different answers to similar questions here on stackoverflow. So my thought is to make it happen by using:
<img src="stop.png" onclick="myEventHandler(event);" />
and I add:
function myEventHandler(e)
{
if (!e)
e = window.event;
//IE9 & Other Browsers
if (e.stopPropagation) {
e.stopPropagation();
}
//IE8 and Lower
else {
e.cancelBubble = true;
}
}'
to the js file. (I got that from here)
Is that the best way to make it stop with an onclick?
This was a Z-index problem/ Changing
document.write("<div id=\"dot"+ i +"\" style=\"POSITION: absolute; Z-INDEX: "+ i +"; VISIBILITY: visible; TOP: 15px;LEFT: 15px;\"><img src='"+image+"' border=\"0\"><\/div>");
}
to
document.write("<div class=\"img-object\" id=\"dot"+ i +"\" style=\"POSITION: absolute; Z-INDEX: "+ (i + 1000) +"; VISIBILITY: visible; TOP: 15px;LEFT: 15px;\"><img src='"+image+"' border=\"0\"><\/div>");
}
made it cover the whole page.
And to stop the animation when clicking on an image, this function works:
(html):
<img src="stopsign.png" onclick="stopAnimation();" />
and the function:
function stopAnimation() {
if (window.atime) {clearTimeout(atime);}
jQuery('.img-object').hide();
}

Categories