Applying function to a div by class - javascript

I thought I was doing this right but its not working. I think I'm being stupid...
function expand(){
var wide = $(this).css('width');
var high = $(this).css('height');
var newwide = wide * 10;
var newhigh = high * 10;
$(this).animate({'width':newwide,'height':newhigh}, 2000);
}
$('.object1').expand();
I just want to run this 'expand' function on the div with the class 'object1', what am I doing wrong?
Thanks

In jQuery, to add a custom function, you do it like this:
(function($){
$.fn.myFunction = function() {
//Custom Function
}
})(jQuery);
So, your code should look like this:
(function($){
$.fn.expand = function() {
var wide = $(this).css('width');
var high = $(this).css('height');
var newwide = wide * 10;
var newhigh = high * 10;
$(this).animate({'width':newwide,'height':newhigh}, 2000);
}
})(jQuery);
Learn More

Try to rewrite your code like this,
function expand($this){
var wide = $this.css('width');
var high = $this.css('height');
var newwide = wide * 10;
var newhigh = high * 10;
$this.animate({'width':newwide,'height':newhigh}, 2000);
}
expand($('.object1'));

How should the $ object know it has a expand() method now?
If you really want a jQuery plugin here (that's what they call it when you attach something to the jQuery object), you have to attach it to $.fn:
$.fn.expand = expand // as you defined it earlier
You almost surely don't want this. What creates what you were trying to achieve is giving the $('.object1') as a parameter to expand():
function expand($element){
var wide = $element.css('width');
var high = $element.css('height');
var newwide = wide * 10;
var newhigh = high * 10;
$element.animate({'width':newwide,'height':newhigh}, 2000);
}
expand($('.object1'));

Related

How to make this function do this in an interval

I'm trying to get the first function, to run repeatedly. Like it does in the second function. Where should I take a look?
(function printLetterByLetter() {
var i = 0;
var destination = "comment";
var RandomComment = [
"Did you choose that outfit?"
, "I like trains."];
var message = RandomComment[Math.floor(Math.random() * RandomComment.length)];
var typewriter = function () {
document.getElementById(destination).innerHTML += message.charAt(i);
i++;
if (i > message.length) {
clearInterval(typespeed);
}
}
var speed = 60;
var typespeed = setInterval(typewriter, speed)
}());
(function printLetterByLetter() {
var destination = "comment";
var frequency = 1000;
var RandomComment = [
"Did you choose that outfit?"
, "I like trains."];
var RandomCommentTimer = setInterval(function () {
var message = RandomComment[Math.floor(Math.random() * RandomComment.length)];
}, frequency)
}());
So what i'm trying to do is to make one function/module that types out a random comment at a set speed(first function). And after a set time the comment will disappear and a new comment will be typed out(second function). And like the second function this will go on.
So far I haven't made it work myself so I thought: let's see if anyone can help me on stackoverflow.
If anyone can give a tip on where to take a look, that is also most welcome.
You could set and alter the function parameters outside of the function then access them inside. Caveat is that you can't put var in front when setting them. Not putting var in front makes it accessible outside of the current scope.
destination = "comment";
frequency = 6000;
(function printLetterByLetter() {
//now you have access to destination and frequency as they are defined before the function is called
var RandomComment = [
"Did you choose that outfit?"
, "I like trains."];
var RandomCommentTimer = setInterval(function () {
var message = RandomComment[Math.floor(Math.random() * RandomComment.length)];
document.getElementById(destination).innerHTML = message;
}, frequency)
}());

Mapbox sidepanel and polygon interaction

I am attempting to make an interaction between images in a sidepanel and polygons on a map, so when the sidepanel is moved via mousescroll, the corresponding polygon with same name is brought into focus.
My current attempt is not responsive to mousescrolls as needed. Is there another approach than the one I have taken?
$('.sidebar').bind('mousewheel', function(e){
$("#help").html(' ');
var winTop = $(this).scrollTop();
var $imgs = $('.sidebar').find('img');
var $midElement;
var distance = null;
var currDistance = 0;
var minHeight = $(window).scrollTop();
var maxHeight = $(window).height();
var img_h=$('.sidebar').find('img');
var img_h1=img_h.height() / 2;
var middleHeightA = (maxHeight + minHeight) / 2;
var middleHeight = middleHeightA - img_h1;
$.each($imgs, function() {
currDistance = Math.abs(middleHeight - $(this).position().top);
if ( distance == null || currDistance < distance ) {
/*$midElement = $(element);*/
distance = currDistance;
for (j=0;j<polygons1.length;j++) {
polygons1[j].setStyle({color: '#fff',fillColor:'#000', weight:'1px'});
}
var scrid=$(this).attr('id');
for (j=0;j<help.length;j++) {
id=help[j];
if(id==scrid)
{
polygons1[j].openPopup(polygons1[j].getBounds().getCenter());
map.setView(polygons1[j].getBounds().getCenter(),10);
polygons1[j].setStyle({color: '#e72f2a',fillColor:'#e72f2a',weight:'7px'});
$('.thumbnail').removeClass('active');
$('.'+scrid).addClass('active');
}
}
}
var scrid=$(this).attr('id');
for (j=0;j<help.length;j++) {
id=help[j];
if(id==scrid)
{
polygons1[j].openPopup(polygons1[j].getBounds().getCenter());
map.setView(polygons1[j].getBounds().getCenter(),10);
polygons1[j].setStyle({color: '#e72f2a',fillColor:'#e72f2a',weight:'7px'});
}
}
}*/
I would recommend you to use a debounce function. Debounce function limits the rate at which a function can fire. The idea is to make polygons focus not every time a mouse-wheel event is triggered, but focus them with a kind of cooldown.
Debounce functions are already implemented in many libraries, for example in lodash. All you have to do is to wrap your mousewheel callback in it. Something like:
$('.sidebar').bind('mousewheel', _.debounce(function(e){
$("#help").html(' ');
...
), 100});
Pay attention to options param, in lodash implementation, most probably you would like to use one of them, for example maxWait.

EaselJs: Objects, Classes, and Making A Square Move

Although I have used Javascript extensively in the past, I have never used classes and objects in my programs. This is also the first for me using the HTML5 canvas element with an extra Javascript library. The library I'm using is EaselJS.
Short and sweet, I'm trying to make a square move with keyboard input, using object-oriented programming. I've already looked over sample game files, but I've never been able to properly get one to work.
The following is my classes script:
/*global createjs*/
// Shorthand createjs.Shape Variable
var Shape = createjs.Shape;
// Main Square Class
function square(name) {
this.name = name;
this.vX = 0;
this.vY = 0;
this.canMove = false;
this.vX = this.vY = 0;
this.canMove = false;
this.body = new Shape();
this.body.graphics.beginFill("#ff0000").drawRect(0, 0, 100, 100);
}
And below is my main script:
/*global createjs, document, window, square, alert*/
// Canvas and Stage Variables
var c = document.getElementById("c");
var stage = new createjs.Stage("c");
// Shorthand Create.js Variables
var Ticker = createjs.Ticker;
// Important Keycodes
var keycode_w = 87;
var keycode_a = 65;
var keycode_s = 83;
var keycode_d = 68;
var keycode_left = 37;
var keycode_right = 39;
var keycode_up = 38;
var keycode_down = 40;
var keycode_space = 32;
// Handle Key Down
window.onkeydown = handleKeyDown;
var lfHeld = false;
var rtHeld = false;
// Create Protagonist
var protagonist = new square("Mr. Blue");
// Set Up Ticker
Ticker.setFPS(60);
Ticker.addEventListener("tick", stage);
if (!Ticker.hasEventListener("tick")) {
Ticker.addEventListener("tick", tick);
}
// Init Function, Prepare Protagonist Placement
function init() {
protagonist.x = c.width / 2;
protagonist.y = c.height / 2;
stage.addChild(protagonist);
}
// Ticker Test
function tick() {
if (lfHeld) {
alert("test");
}
}
// Handle Key Down Function
function handleKeyDown(event) {
switch(event.keyCode) {
case keycode_a:
case keycode_left: lfHeld = true; return false;
case keycode_d:
case keycode_right: rtHeld = true; return false;
}
}
This is the error I get in the Developer Tools of Chrome:
Uncaught TypeError: undefined is not a function
easeljs-0.7.0.min.js:13
In case you're wondering, the order of my script tags is the EaselJS CDN, followed by my class, followed by the main script file.
I would really like closure on this question. Thank you in advance.
I figured it out. I was adding the entire protagonist instance to the stage. I've fixed by adding the protagonist.body to the stage.

Animating canvas with a javascript constructor

Hello stackoverflow community!
First I must say that I dont have much experience with constructors.
So. What I am trying to do, is to animate a parachutist to fly from top to bottom of the screen.
I thought I could use a constructor to set up a parachutist:
var parachute = function() {
this.height = 35;
this.width = 30;
this.speed = 50;
this.xPos = Math.round(Math.random() * (window.width - this.width));
this.animate = function() {
this.img = new Image();
this.yPos = 0;
this.img.onload = function() {
ctxPara.globalCompositeOperation = 'copy';
ctxPara.translate(0, this.yPos);
ctxPara.drawImage(this.img, this.xPos, 0);
};
this.img.src = 'para.png';
this.yPos++;
};
};
This constructor is used in a function called 'fly':
var fly = function() {
var newParachute = new parachute();
setInterval(newParachute.animate, newParachute.speed);
};
And this 'fly' function is triggered when the window loads:
window.onload = function() {
var canvasBg = document.getElementById('canvasBg');
// I splitt the Background and the parachutists in two canvas elements
// handling the problem (to erase content and draw new content) with
// the canvas animation.
var canvasPara = document.getElementById('canvasPara');
ctxPara = canvasPara.getContext('2d');
canvasPara.width = window.width;
canvasPara.height = window.height;
canvasBg.width = window.width;
canvasBg.height = window.height;
fly();
clouds(); // background is loading here
};
What you should see, is a Parachutist flying down the screen. But unfortunately you don't...
Now, after that Long text. (Iam very sorry that it is so long :-( ) My question is: Do you know what I am doing wrong? Is my constuctor correct? Is, what i am trying to do, supposed to be written like this? Any advices or suggestions for a succesfull opportunity? (I hope my english isn't that terrible I think it is :-) )
Oh i forgot to mention the error. It's a TypeMissMatchError.
That means 'this.img' is not an img element at this line:
ctxPara.drawImage(this.img, this.xPos, 0);
Now, I followed the example of markE.
Instead of showing me a parachutist. It shows me an error in this line: ctxPara.drawImage(this.img, this.xPos, this.yPos);
var fly = function () {
var newParachute = new parachute();
newParachute.img.load.call(newParachute);
setInterval(newParachute.animate.call(newParachute), newParachute.speed);
};
var parachute = function () {
this.height = 35;
this.width = 30;
this.speed = 25;
this.xPos = Math.round(Math.random() * (window.innerWidth - this.width));
this.img = new Image();
this.yPos = 0;
this.img.isLoaded = false;
this.img.load = function () {
this.img.isLoaded = true;
};
this.img.src = 'parachute.png';
this.animate = function () {
if (this.img.isLoaded) {
ctxPara.clearRect(0, 0, canvasPara.width, canvasPara.height);
ctxPara.drawImage(this.img, this.xPos, this.yPos); // ERROR: 'Unknown Error'.
this.yPos++;
console.log('animating');
}
};
};
I am stuck again. But now i don't even know the reason... Please help!?
Demo: http://jsfiddle.net/m1erickson/ym55y/
A couple of issues:
(1) To get the window width you can use:
window.innerWidth
(2) setInterval calls newParachute.animate.
setInterval(newParachute.animate, newParachute.speed);
But this inside animate the window object--not the Parachute object.
To give the correct this to animate you can use the call method like this:
var newParachute = new parachute();
setInterval(function(){newParachute.animate.call(newParachute);}, newParachute.speed);
(3) You need to deal with clearing previously drawn images or they will still show on your canvas.

Javascript & jQuery: how to make function infinite through animate callback?

have an object of a class Abon and then i want this object to move around the page.
a = new Abon();
a.init();
a.move();
the method move() contains:
function abon_move () {
var x = this.x;
var y = this.y;
var direction_x = Math.random()*5 - 5;
var direction_y = Math.random()*5 - 5;
var x_new = x + direction_x * this.movement_rate;
var y_new = y + direction_y * this.movement_rate;
console.log(x_new+" "+y_new)
$(".abonent."+this.id).animate( {
left:+x_new,
top:+y_new
}, 'slow', "linear", function() { this.move() });
}
All i want is that the method move (represented as function abon_move()) repeated again and again, after the animate stops. But the problem is that this.move() shown in callback has no connection to my object, because this in that place points to the HTML element, selected by jQuery.
UPD:
function Abon(id) {
...
this.move = abon_move;
...
}
Abon.prototype.move = abon_move;
And the actual method is the same, but with no callback in animate
then i try doing the following:
setInterval( a[0].move , 300); //doesn't work - says `this` members are undefined
setInterval( a[0].move() , 300); //works only one time and stops
Thank you for any help!
Try this :
function abon_move () {
var x = this.x;
var y = this.y;
var class = this;
...
}
Then, inside your jQuery animate, your can refer to your class using the variable class
Wrap the function abon_move() in a setTimeout call, as such: setTimeout(abon_move, 300); so it will run every 300 ms.

Categories

Resources