Posts Tagged ‘Javascript’

Transit – CSS transformations plug-in for jQuery

Posted in Web Development on September 15th, 2014 by Jarred – Comments Off on Transit – CSS transformations plug-in for jQuery

I came across a little jquery plug-in that I found quite nifty and thought it deserved a shout out. The plug-in is called Transit and can be found here: http://ricostacruz.com/jquery.transit/ The plug-in not only makes css transformations a breeze the end animations produced are incredibly smooth. It is very simple and straightforward to use. Anybody already familiar with jquery .animate() will be able to pick it up with little or no effort. As of version 0.9.12 the minified file is only about 8kb. I built a little game using the plug-in (game to be released publicly in a post to come) and was very pleased with the outcome. I really couldn’t be more happy with the the whole thing with the and figured I would little post it here so A: I can remember it personally and also B: give the project a bit of love so hopefully development will continue.

Jquery click not binding to checkbox (or any other element)

Posted in Geekdom, Programing, Web Development on January 24th, 2014 by Jarred – Comments Off on Jquery click not binding to checkbox (or any other element)

I am just writing this down for the sake of my own personal sanity. I just spent way too much time trying to trouble shoot why I could not bind a click event to a checkboxes in jquery. This post here gave me a clue what I was doing wrong. If by chance you are having a similar issue make sure that the element you are trying to bind to is already created and part of the DOM or it will not work and you will be left befuddled why exactly nothing is happening (at least I was).

How not to set Backbone model properties

Posted in Geekdom, Programing on November 29th, 2012 by Jarred – Comments Off on How not to set Backbone model properties

So here is another backbone.js tidbit that took me a while to figure out/understand. This may be fairly straight forward to seasoned programmers, but it really through me for a loop. If you try and set initial model (or view) properties outside of the “defaults” method you can not retrieve them using model.get(‘propertyName’). This was a point of confusion because sometimes it was working like i though it should and sometimes it did not. To further complicate things I was trying to set properties by passing them when I was instantiating the object. It took me a while to figure out what I was doing wrong.

So this is incorrect even though you can still access the object properties.


ExampleModel = Backbone.Model.extend({
propertyName: 'Some Value',
})
exampleModel = new ExampleModel ({propertyName: 'Updated Value'});
exampleModel.propertyName// 'Some Value' not 'Updated Value'

From what I understand this is the correct way to do it


ExampleModel = Backbone.Model.extend({
defaults: {
propertyName: 'Some Value',
},
})
exampleModel = new ExampleModel ({propertyName: 'Updated Value'});
exampleModel.get('propertyName') //'Updated Value'

Now that I understand the concept the documentation makes this very clear to correctly set default model properties using the defaults method.

Problems with binding events on subview in backbone.js

Posted in Programing on November 23rd, 2012 by Jarred – Comments Off on Problems with binding events on subview in backbone.js

I am working on learning backbone.js and well it has been a bumpy road. Along the way I have come across several hiccups, but this one was a doozy and caused me all sorts of frustration. I was trying to to bind a change event to a select menu in one of my subviews. For the life of me I could not get the event to fire correctly. If I copied the exact same event to the parent view it worked just fine. This lead me to believe that I was experience a scope issue. There is lots of information on the web about breaking the scope of “this” in backbone.js which further lead me to believe this was the problem. But turns out that was not the problem at all. After a whole lot of confusion I lucky stumbled upon this post on stackoverflow

Unfortunately it looks like it was not the answer to the original posters problem, but it solved my issue.

According to the post, events in backbone.js are not actually bound to the changing element but rather the root element of the view and then delegated to the children from there. This is important if you are not actually inserting your the root element of your subview into the DOM, because then your events will not fire (which is exactly what I was doing).

So, this render function simply inserts the rendered template html into the DOM which fails to actually insert the views el into the DOM.

render: function() {
$('#anchorDiv').append( this.template(this) );
},

Something like this however will actually insert the view’s root element into the DOM which will (at least in my case) solved all my event issues.
render: function() {
$(this.el).html( this.template(this) );
$('#anchorDiv').append( this.template(this) );
},

I am really liking backbone.js as I think it is helping me better structure my applications. That being said, it has been tough to really learn and grasp how everything is supposed to work. This issue was not straight forward to me at all and hopefully might help somebody out there figure out why their events are not working like they thing they should.

JavaScript to Calculate the angle between two points in degrees

Posted in Geekdom, Programing, Web Development on February 19th, 2012 by Jarred – Comments Off on JavaScript to Calculate the angle between two points in degrees

Quick little snippet here for later reference (Yeah this one took me a bit to figure out).  The below function will return the angle between two points and return it in degrees from 0-360.

 

 

		function calcAngle(x1, x2, y1, y2)
		{
		calcAngle = Math.atan2(x1-x2,y1-y2)*(180/Math.PI);	
		if(calcAngle < 0)	
		calcAngle = Math.abs(calcAngle);
		else
		calcAngle = 360 - calcAngle;		
		return calcAngle;
		}

 

 

Sources http://board.flashkit.com/board/showthread.php?t=778094

 

Universal AJAX function

Posted in Geekdom, Programing, Web Development on February 13th, 2012 by Jarred – 1 Comment

Here is my universal AJAX function. I am posting it here for reference. Over the months I have adapted/revised this function and now have finally gotten it to do pretty much what I want it. I did not write all of this myself I pulled most of it off of somewhere, but I can not remember so I can not give proper credit. Let me know if you have any suggestions on how to improve it.

 

// ******************************************************
// Universal Ajax Function
// Useage Example:  universalAJAX('http://url.com', "var1=true&var2=false", functionWhenDone, functionWhenWaiting, functionWhenFail);
// ******************************************************

function universalAJAX(URL, DataToSend, doneFunction, waitingFunction, errorFunction)
{

var json_http;
if (window.XMLHttpRequest)
{json_http=new XMLHttpRequest();}
else
{json_http=new ActiveXObject("Microsoft.XMLHTTP");}

json_http.onreadystatechange=function()
 {
   if (json_http.readyState==1)
    {waitingFunction();}
  if (json_http.readyState==4 && json_http.status==200)
    {
	if (json_http.status==200)
		{
		doneFunction(json_http.responseText);
		clearTimeout(timeOutVarCancel);
		}
	else
		{
		errorFunction();
		clearTimeout(timeOutVarCancel);
		}
	}
}

  json_http.open("POST",URL,true);
  json_http.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
  json_http.send(DataToSend);

  var timeOutVarCancel=setTimeout(errorFunction,10000);
}

Iterating through properties of a JavaScript Object with the “For In” loop

Posted in Geekdom, Programing, Web Development on January 16th, 2012 by Jarred – Comments Off on Iterating through properties of a JavaScript Object with the “For In” loop

As I have mentioned before I am a novice self taught programmer and I often come across little problems that take me quite a while to figure them out. I like to post them here so I can come back and remember how I solved the problem and also so hopefully others can benefit from my struggles. I came access one of these said problems this weekend trying to iterate through a object in JavaScript using a “for in” loop. I understood the looping mechanism quite well, however getting the syntax to work for me through me for a loop.

 

Incorrect (This is how I would assume it would work)

 for (var x in someObject.someProperty)

{
newVar = someObject.someProperty.x.anotherProperty;
}

This is how I got it to work

 for (var x in someObject.someProperty)

{
newVar = someObject.someProperty[x].anotherProperty;
}

You will notice you cant use .x to access the property the loop is currently processing,  you must use the [x] In truth I do not understand why this is so if anybody out there cares to enlighten me that would be appreciated. Either way hopefully this might save some frustration.

HTML5 Audio Is Here (Sorta)

Posted in Programing, Web Development on September 8th, 2011 by Jarred – Comments Off on HTML5 Audio Is Here (Sorta)

Figuring out how to implement a pure HTML5 Audio solution for my game was quite a chore. I found countless threads and post complaining that audio support is just not there yet and that the best thing to do is use flash based solutions (like the SoundManager 2 script). However, I found other information which lead me to believe it could be done. After much searching and trial and error I figured out something that would work and that would preload the sounds before the game would start. My ultimate solution was pure HMTL5 without the use of a script and used a variety of techniques I gleaned from reading others posts and blogs(mostly stackoverflow).

Here is how I did it:

First I load all the game sounds using HTML audio elements in the body of my page. You have to provide at least a .mp3 file and a .ogg file to be compatible with most browsers. Also, If you plan on doing multi-shot sounds (sounds that can be played overlapping themselves such as a rapid fire gun sound in a game) you will have to load multiple instance of them into separate audio elements (Many of my sounds have 5 or 6 instances of themselves)

<audio id=”gun_sound_1″ preload=”auto”>
<source src=”sounds/gun.mp3″ type=”audio/mpeg” />
<source src=”sounds/gun.ogg” type=”audio/ogg” />
</audio>
<audio id=”gun_sound_2″ preload=”auto”>
<source src=”sounds/gun.mp3″ type=”audio/mpeg” />
<source src=”sounds/gun.ogg” type=”audio/ogg” />
</audio>
<audio id=”gun_sound_3″ preload=”auto”>
<source src=”sounds/gun.mp3″ type=”audio/mpeg” />
<source src=”sounds/gun.ogg” type=”audio/ogg” />
</audio>

Secondly the JavaScript

//Create a counter for the sound
gunSound_counter = 1

//Variable holding the number of audio elements that exist
gunSound_maxNumber = 3;

function playSound_html5(soundName)
{
//Add the counter suffix
soundToPlay = soundName+gunSound_counter;

//Play The Sound
audioElement = document.getElementById(soundToPlay);
audioElement.play();

// For Multi-Shot sounds Increment the counter. If counter is at the max reset to one
if (gunSound_counter >= gunSound_maxNumber)
gunSound_counter = 1;
else
gunSound_counter++;
}

Now when ever I want to play the sound I just call the playSound function and pass it a string with the name of the sound I want to play (without the number suffix).

playSound_html5(‘gun_sound_’);

I am pretty sure there is likely more eloquent ways to do this, but hopefully this can help you get a good start.

Update: Upon reading this it now looks like the SoundManager 2 now offers support (beta) for HTML5 audio. Looks like I will have to check this out on my next game cause sound really was just a pain.

 

Some of the sources I used:
http://stackoverflow.com/questions/1933969/sound-effects-in-javascript-html5
http://stackoverflow.com/questions/2741493/how-do-you-detect-html5-video-events
http://stackoverflow.com/questions/6312714/adding-event-listener-to-audio-html5-tag-in-javascript
http://stackoverflow.com/questions/3566967/how-to-stop-audio-played-by-audio-tag-of-html5
http://diveintohtml5.org/everything.html
http://www.webdeveloper.com/forum/showthread.php?t=194442
http://www.broken-links.com/2009/10/06/building-html5-video-controls-with-javascript/
http://bioinfornetics.blogspot.com/2011/02/how-to-resetrestart-position-of-html5.html

HTML5 Canvas performance for scaling sprites

Posted in All on August 1st, 2011 by Jarred – 1 Comment

Well…This is likely a nobrainer for most, but for some reason it took me quite a while to figure this one out.  In my latest game asteroidsInc I have been designing I was experiencing some pretty awful frame rates, and so I started to try and optimized the code for better performance.  I was using the JavaScript drawImage function to scale the images I was using as sprites in order to achieve a retro pixely effect.  While it did accomplish the effect I was looking for it turns out the frame rate took a big hit due to the scaling.  To improve the performance I simply used Photoshop to enlarge my images (in order to retain the retro effect) and then used the drawImage function using no scaling. The performance boost was quite significant. In hindsight it seems quite obvious that using the scaling was a bad idea on sprites and would require more resources to render, but hey…sometimes the obvious just takes a little longer.

 

In recap, if you are are trying to animate multiple objects on the canvas it appears that resizing the images themselves has performance advantages over using the drawImage to scale the images.

Safari not liking the HTML5 Audio

Posted in All, Programing, Web Development on July 30th, 2011 by Jarred – 1 Comment

 Well this one threw me for a loop….

 I never use Safari, but in an attempt to make my latest HTML5 Game compatible in all the major browsers I downloaded the PC version of Safari to do some testing and trouble shooting to see if it would work. The game worked well in Chrome, Firefox, and I.E. so I assumed it would just work in Safari. But no, to my surprise it started throwing the following error every time I tried playing one of the audio elements.

 TypeError: ‘undefined’ is not a function (evaluating ‘audioElement.play()’)

 After much frustration I came across a post which indicated that HTML5 audio and video tags will not work in Safari without QuickTime. So much for HTML5 not requiring any plug-ins. I installed QuickTime and to my dismay Safari was now giving me the following error when I tried to start it up.

This application has failed to start because QTCF.dll was not found. Re-installing the application may fix this problem.

After trying to reinstall the the browser (this did not work) I found the QTCF.dll file in the Program Files/QuickTime/QTsystem made a copy of it and put it in Windows/System32. This solve the problem and Safari now started up. I was able to load my game with no more errors playing the audio objects. Safari seemed to handle the canvas object fairly well (although the frame rate on seems to be fairly poor).

Source: http://happyworm.com

Source: http://answers.yahoo.com/question/index?qid=20090912133753AAM60Ur