Javascript Event Listeners

Hey guys,

You may be thinking, why I am talking about javascript. Well, to be honest, I have started my life as a developer with javascript. After having a little conversation with my friend Jay Moretti couple months ago, about html5, he cleared my mind about what was html5. He wisely said “Marcelo, html5 is javascript!”. Coming from this point, I would say that I can be classified as html developer. Just kidding :) .

Back in time

Five or six years ago I used to set up my event listeners as anonymous functions, as below.

myElement.onclick = function() {
	//my click handler
};

Note at the code above, that I have a specific function only for that element, which makes me write too much code and not reusing it in the future.

myElement.onclick = myFunction;
function myFunction(){
	//my click handler
}

At this example we can reuse the code into the method, but it’s pretty sketchy, isn’t it?

Okay, let’s go by the beginning, if you look at the first block of code, I’m using a semicolon after the curly braces. At the second block of code, I am not. Why?
At the first block, there was no function call, it was a statement where I’m just saying that the myElement.onclick assigns a function. So, without the semicolon it doesn’t work in some cases.

Nowadays, javascript has another and better way to create event listeners.

//adding event listener
myElement.addEventListener('click', methodName, false);
function methodName(){
	//my click handler
}

//removing event listener
myElement.removeEventListener('click', methodName, false);

Here, I have an organized way, but not safe yet, to create my event listeners. I can reuse the methodName() function in the future, which saves me time of development.
You may be asking yourself, -Why isn’t it safe to use?; Simple, our cool friend, internet explorer 8 and older versions don’t understand the addEventListener method.

OMG, Internet Explorer again cracking the web. Calm down, we have three solutions for this cross-browser issue. I’ll explain one by one.

Please, save the web

The internet has generated a lot of headaches for developers, most part of that is because of the Internet Explorer, the browser that doesn’t evolve as much as Chrome and Firefox.

To avoid problems with event handlers on IE, we have three ways to go:

First:
The simple and weak way.

//Internet Explorer 8 and previous versions
myElement.attachEvent('onclick', methodName);

On this way I just set up this other method called attachEvent(); which can be understood by IE8 and previous.

Second:
To create a cross-browse event listener identifier, hummm, looks fun!

function addCrossBrowseEventListener(myElement, myEvent, myFunction) {
	if(myElement.addEventListener){
		myElement.addEventListener(myEvent, myFunction, false);
		return true;
	} else {
		myElement.attachEvent('on'+myEvent, myFunction);
		return true;
}

This bad boy up there should help you with major cross-browse issues, it checks if the addEventListener function exists, if yes, use it, otherwise use attachEvent.

Looks awesome, but, we have a safer and better way to fix the cross-browse issues for these event listeners, the famous jQuery or another JS library.
Download the jQuery from here

jQuery takes care of the whole cross-browse issues that could happen and it’s always up to date. To set your listener up with jQuery is pretty simple and useful.

//adding event listener
$(myElement).live('click', methodName);
function methodName(){
	//do something
}

//removing event listener
$(myElement).die('click', methodName);

Thanks to Igor Costa for the jQuery help. Very appreciated, man.

For a complete list of events, check this out

Conclusion

There is still hope at the internet, I know javascript is not even close to a strong typed language, but we can do it better using the obvious and right methods.

I hope you guys have enjoyed, from now on I’ll be posting more about javascript and html5. Stay tunned.

Posted in Javascript | 2 Comments

Brazilian vacations!

Hey my dear readers, hope it finds all you well in this new year! Happy 2012!

I’ll tell you about my vacations in Brazil. After two years living in USA, I’ve faced a lot of contrast and I’ll share these stories with you.

São Paulo

First thing I’ve faced in Brazil was in São Paulo. The airport officials were on strike! Welcome back Marcelo. I spent, literally, 3 hours at the airport to pass through the immigration. We are about to have Olympic Games and World Cup in Brazil… how?

São Paulo was always an ugly city, the thing that makes São Paulo a good place are the people. I had the pleasure to meet Danilo Rodrigues which was my coworker in NYC and Rafael Rinaldi, both great friends that I care a lot. That was the best part of São Paulo, all the rest was shit to me (visa, document problems, noise, stress and money spent).

Ok, I went to the american consulate and guess what, couldn’t renew my visa, why? I didn’t make the proper appointment! I had to spend R$ 300 (around U$ 200), at the clandestine trade to get another appointment as soon as possible, once my life is in Los Angeles. Another great memory of São Paulo. #NOT

Note: I spent around R$ 1000 (U$ 800) with taxes in Brazil at this trip!

Passo Fundo

Finally I flew to my hometown, I don’t know what I was expecting, maybe I thought I was Frodo and I was going back to the shire! No, Passo Fundo, my hometown has increased the crime average, it was really dangerous to walk on the streets with different clothes, they could steal it from you or worst.

Overall, I met my family which, with no doubt, was the best fact of my trip!

After a kind time spent with my family and friends, I flew back to São Paulo, in a madness to try to get my visa approved. At this time, São Paulo was good to me, I have gotten the visa in record time, 1.5 hours! Now I have to wait until my visa arrive!

Curitiba

Time to go to the city that made my education as man, rainy Curitiba. I really love this place and after living in São Paulo, Rio de Janeiro and know all the south main cities, I could easily say that Curitiba is the best city I ever lived in Brazil. Also is where I found the girl that will spend her life at my side :)

Though I was working remotely during the day, I had amazing dinners and happy hours with friends and my girlfriend’s family.

Michel Teló

Michel Teló isn’t a city or something that I like, he is a singer, a person that has my respect for being recognized in all country. How? I don’t know, I really don’t know, but it should be something that brazilians should ban FOREVER! Non sense lyric ever made. It doesn’t match our culture not even a bit. I really want to land in Brazil in December and not listening this song anymore.

Conclusion

It is clearly proved that Brazil doesn’t have structure to have a world recognize event yet. It needs couple years to improve and change some stereotype that people judge each other.

Brazil is a great place, though. It just need more love from the politicians. I won’t make a list with all the items we should change as brazilians, we know what has to be done, and I’m not a good example as well, once I live outside of the country!

Now I’m getting ready to flight back to Los Angeles, I want to see how my house is going, I really miss my life right now!

Basically it was the resume of my trip to Brazil, I know it is nothing about technology, but it’s good to share sometimes.

Have a great 2012, everyone!

Posted in Uncategorized | 2 Comments

Jzoo – Graphics

Couple days ago, I have started my Java toolkit, which is kinda useful in some occasions (static shapes, dynamic resizable shapes).

First of all, clone the project from GitHub.

https://github.com/marceloduende/JZoo

Use your desired software to do the work. I have used GitHub for Mac, which is simply amazing.

All right, once you have it cloned in your computer, you can set up your project and add the src folder as path. If you already have it, grab the “com” folder and throw inside your path folder.

I’ll start with a regular Rectangle without special settings.

Drawing Rectangle and Oval shapes

View linearLayout = findViewById(R.id.YOUR_LAYOUT_ID); // add the layout ID right here
ShapeFactoryParameters b = new ShapeFactoryParameters().x(50).y(50).w(300).h(100).color(0xffffffff).kind("RECT"); // explanation below
ShapeFactory sf = new ShapeFactory(YOUR_ACTIVITY, b); // add the Activity
((LinearLayout) linearLayout).addView(sf); // adding view

Explaining the second line.

What ShapeFactoryParameters does is to save all parameters and send it to the ShapeFactory.
You can use like above or like below.

ShapeFactoryParameters b = new ShapeFactoryParameters();
b.x(50);
b.y(50);
b.w(300);
b.h(100);
b.color(0xffffffff);
b.kind("RECT");

NOTE: You have to use it before setting the parameters to the ShapeFactory;

The result for this would be something like this:

rect

To use and Oval Shape is exactly the same thing. Just change the kind(“RECT”); to kind(“OVAL”);

rect

Drawing Stroke

You can, also, easily add a stroke in your shapes, adding only two parameters.

ShapeFactoryParameters b = new ShapeFactoryParameters();
b.x(50);
b.y(50);
b.w(300);
b.h(100);
b.color(0xffffffff);
b.kind("RECT_STROKE"); // changed the kind
b.stroke(5); // added the stroke size

And you can see something like this:

rect

Drawing Round Shapes

Another cool stuff is to add round shapes to your project. The round shape works different, you have to add a float value to determine the corners values. For this occasion I’ll use 20 pixels for all the corners.

float[] corner = new float[] {20, 20, 20, 20, 20, 20, 20, 20 }; // change it for a different corner;
ShapeFactoryParameters b = new ShapeFactoryParameters();
b.x(50);
b.y(50);
b.w(300);
b.h(100);
b.color(0xffffffff);
b.kind("ROUND");
b.corner(corner);

And you’ll have something like below:

rect

Drawing Round Strokes

float[] corner = new float[] {20, 20, 20, 20, 20, 20, 20, 20 }; // change it for a different corner;
ShapeFactoryParameters b = new ShapeFactoryParameters();
b.x(50);
b.y(50);
b.w(300);
b.h(100);
b.color(0xffffffff);
b.kind("ROUND_STROKE");
b.corner(corner);
b.stroke(5);

rect

Drawing Gradient Shapes

ShapeFactoryParameters b = new ShapeFactoryParameters();
b.x(50);
b.y(50);
b.w(300);
b.h(100);
b.color(0xffffffff);
b.kind("RECT");
b.gradientKind("CLAMP"); // "CLAMP", "REPEAT" "MIRROR"
b.gradientColor1(Color.WHITE); // initial color
b.gradientColor2(0xffff0000); // ending color
b.gradientStartX(50); // initial x
b.gradientStartY(50); // initial y
b.gradientEndX(200); // ending x
b.gradientEndY(100); // ending y

rect

Drawing Shapes with dynamic width and height

View linearLayout = findViewById(R.id.YOUR_LAYOUT_ID); // add the layout ID right here
        ShapeFactoryParameters b = new ShapeFactoryParameters()
         			.x(0)
         			.y(0)
         			.w(WindowBoundaries.getWidth(YOUR_ACTIVITY)) // dynamic width
         			.h(WindowBoundaries.getHeight(YOUR_ACTIVITY)) // dynamic height
         			.color(0xffffffff)
         			.kind("RECT")
         			.gradientKind("CLAMP")
         			.gradientColor1(Color.WHITE)
         			.gradientColor2(0xffff0000)
         			.gradientStartX(0)
         			.gradientStartY(0)
         			.gradientEndX(WindowBoundaries.getWidth(YOUR_ACTIVITY)) // dynamic width
         			.gradientEndY(WindowBoundaries.getHeight(YOUR_ACTIVITY)); // dynamic height
        ShapeFactory sf = new ShapeFactory(this, b); // add the Activity
        ((LinearLayout) linearLayout).addView(sf);

rect

App built with JZoo

This app is about to be released next month. I’ll make a special post about it soon.

rect

Parameters

// MANDATORY
x();
y();
h();
w();
color();
kind();

// RELATIVE
corner();
stroke();
alpha();
gradientKind(); // "CLAMP", "REPEAT" "MIRROR"
gradientColor1(); // int
gradientColor2(); // int
gradientStartX(); // int
gradientStartY(); // int
gradientEndX(); // int
gradientEndY(); // int
Posted in Uncategorized | Leave a comment

What happened?

Seriously, what the hell happened?

Where are the cool web sites experiences? Where are the projects which we loved to do? Where is the Coke Zero Game website?

What the hell they’re doing with html5? ONLY STUPID EXPERIMENTS which nobody can use, because these bullshits only work on the last super cool Chrome version. RETARDED!

What a egocentric person called Steve Jobs did to the world wide internet experience? I’m talking about internet, it encompasses mobile, desktops and whatever device that can run internet. He has simply killed a generation! Generation with amazing people that love to create crazy things.

I was part of this generation. I said, WAS!

What is cool now? I meant, cool, not useful! There’s a ton of useful apps at the Apple Store, which is great, but where’s the cool stuff?

I had to move on with the market. Doing petty things, because the client doesn’t want something that doesn’t run at iPad, iPhone, iSuck! At the end, the client is right. They’re lost in this war, they only want their brand at any device possible. How to do it? Stupid 1999 html projects which there’s NO excitement, none!

I have to say that I became a better developer with all this mess. I’ve learned couple new languages and ways to develop. I could be wrong, and I wanted to be wrong, but, to be honest, I’m pretty right and unhappy.

I really hope that html5 does become a real cool thing, because I like to do cool things. For now, it looks like crap for me, and commercially speaking, it is a huge crap.

I still can’t understand how Cannes could have named a Chrome experiment as the best choice for Cyber. What was the popularity of that thing? Who has launched that website? Only cool dudes with the new Chrome version? Cannes for hipsters, maybe? Should I grab my lion and throw out in the fog?

I don’t want to be old saying that, but I’d like to delivery something which all users could interact without restrictions, regardless the browser, the ONLY tool, that can provide this nowadays is the Flash.

Is it getting old? A’ight, so, can you show me something new that can do at least 50% that Flash does?

Again, I’m NOT a Flash defender, I don’t care about which technology will be used and I’m not biased with different technologies, don’t get me wrong, I JUST WANT TO DO COOL THINGS!

Posted in Flash, HTML5, Internet | Tagged , , | 9 Comments

MouseWheel – Javascript

Hey ya’ll

Last days I have the necessity to develop some work in html, using javascript and css and a lot more stuff. It’s been funny to be honest, I’m feeling pumped doing this kind of stuff, looks like I am 5 years in the past :) .

One thing that I never did before was to create a mouse wheel functionality in JS, thing that I was used to do in Actionscript.

Well, it is pretty straight forward, also I could easily save this code for future reuse, after some implementation, obviously.

I have tested this code in a couple browsers, looks like it is working pretty smooth.

/**
* @author Marcelo Duende
*
* This is a MouseWheel utility which allows you to scroll your content in any browser
*
* The license is FREE it does mean FREEEEEEE!
*
* Contact
* marceloduende.com
* marceloduende.com/blog
* marcelo.duende@gmail.com
*
*/

/**
* Adding event listener
*/
if (window.addEventListener)
	window.addEventListener('DOMMouseScroll', wheelHandle, false); /** Mozilla. */
	window.onmousewheel = document.onmousewheel = wheelHandle; /** IE - Opera. */

/**
* Handling div
*/
function handlingDelta(delta){
	/** kill default actions.*/
	if (event.preventDefault)
		event.preventDefault();
		event.returnValue = false;

	document.getElementById("your_elemet_here").scrollTop += -delta*2; /**throw your element there to start the mouse wheeling*/
}

/**
* Handling Delta value
*/
function wheelHandle(event){
	var deltaValue = 0;

	if (!event) /** For IE. */
		event = window.event;

	if(event.wheelDelta){ /** IE - Opera. */
		deltaValue = event.wheelDelta/120;

		if(window.opera) /** Opera 9. */
			deltaValue = -deltaValue;

	} else if(event.detail){/** Mozilla. In Mozilla delta is multiple of 3 */
		deltaValue = -event.detail/3;
	}

	if (deltaValue)
		handlingDelta(deltaValue);

}

Also, you need a html for this, I’ll copy and paste my code quickly, as the focus of this post, is to teach only the JS.



	

        
    

    
  • marcelo
  • duende
  • marcelo
  • duende
  • marcelo
  • duende
  • marcelo
  • duende
  • marcelo
  • duende

And the CSS.

@charset "UTF-8";
/* CSS Document */

.center_div{
	width:50%;
	height:100px;
	margin:auto;
	position:relative;
	overflow-y:hidden;
	overflow-x:auto;
}
#scroll_window ul{
	list-style-type:none;
	height:50px;
	width:200px;
	margin:auto;
}
#scroll_window li{
	float:left;
	padding:20px;
}

#test ul{
	list-style-type:none;
	height:50px;
	width:200px;
	margin:auto;
}

#test li{
	float:left;
	padding:20px;
}
#test ul a:hover {
	color: #000000;
}

#test ul a{
	text-decoration:none;
	color:#FF0000;
}
Posted in Javascript | Tagged , , , , | Leave a comment

Handling screen orientation change Android – Java

Sup guys,

Last days I’ve faced a tiny problem with orientations inside my app. When you change the orientation while it is sending, downloading or even with saved data in your screen, it does restart the Activity alone, creating another View for this new orientation. It is good in some cases, but sometimes it is a pain in the ass, crashing your app.

To block it, is pretty simple, you can block the new View and still fit your screen in both orientations (vertical and horizontal).

So just add this to your activity in AndroidManifest.xml


android:configChanges="orientation"

And you are good to go.

Posted in Android, Java | Tagged , , , , | Leave a comment

Google Analytics for Android/Java

I know there’s some people out there with tricky problems with this thing.

Well, the Google Analytics for android is under development, yet. It isn’t a done stuff, for this reason there’s some tricks to do. I gonna show in only one class how to do it

/**
 *
 * @author Marcelo Duende
 *
 * How to use it
 *
 * 1 - Download the Google Analytics JAR - http://code.google.com/mobile/analytics/download.html
 *
 * 2 - Change your AndroidManifest.xml, add this:
 * 
 * 
 *		
 *	    	
 *	    
 * 
 *
 * PS: Put it inside this node:
 * 
 * *******************************************************
 * *********************HERE*****************************
 * *******************************************************
 * 
 *
 * 3 - Don't forget to allow the internet connection in your AndroidManifest.xml
 * 
 *
 * 4 - Call this class passing some string to save in your records
 * GA ga = new GA();
 * ga.init(this);
 * ga.trackPageView("/MyPage");
 *
 * 5 - DON'T FORGET TO CREATE YOUR ACCOUNT AND CHANGE THE CONSTANT CALLED "GOOGLE_ANALYTICS_ID" down there
 *
 * 6 - Have fun
 *
 */

package com.marceloduende.sickspot.ga;

import android.app.Activity;

import com.google.android.apps.analytics.GoogleAnalyticsTracker;

public class GA {

	/**
	 * Set tracker object
	 */
	public GoogleAnalyticsTracker tracker;

	/**
	 * Set Google Analytics ID
	 */
	// Change it to your Google Analytics ID
	public final String GOOGLE_ANALYTICS_ID = "UA-xxxx-x"; 

	/**
	 * Initiates the Google Analytics
	 * @param activity
	 */
	public void init(Activity activity){
		tracker = GoogleAnalyticsTracker.getInstance();
		tracker.start(GOOGLE_ANALYTICS_ID, activity);
		tracker.setCustomVar(1, "Medium", "Mobile App");
		tracker.dispatch();
	}

	/**
	 *
	 * Tracking Events
	 *
	 * @param arg0
	 * @param arg1
	 * @param arg2
	 * @param arg3
	 */
	public void trackEvent(String arg0, String arg1, String arg2, int arg3){
		tracker.trackEvent(arg0, arg1, arg2, arg3);
	}

	/**
	 *
	 * Tracking Page Views
	 *
	 * @param arg0
	 */
	public void trackPageView(String arg0){
		tracker.trackPageView(arg0);
	}

	/**
	 *
	 * Stopping tracker
	 *
	 */
	public void trackerStop(){
		tracker.stop();
	}
}

If you need more info than this, here goes a useful link. Developer’s guide

Enjoy :)

Posted in Android, Java | Tagged , , , , | Leave a comment

Checking if the Wi-fi is turned on/off – Android/Java

Sometimes you gotta have the Wi-fi connection turned on to execute some actions, as to get the location (LAT/LON). It can help you to get it more precisely.

So to do it, the first thing you have to do is to open your AndroidManifest.xml and add this


It gonna make you able to check your wifi state.

Then to check it, just do this

WifiManager wifimanager = (WifiManager)this.getSystemService(Context.WIFI_SERVICE);
if (wifimanager.isWifiEnabled()){
// enabled
} else {
// disabled
}

Pretty simple, hun?

Posted in Android | Tagged | Leave a comment

Uploading an image to a webserver – Android/Java

Last week, I faced a problem to send an image to the server, I have tried a lot of ways, but seemed that nothing would work.

After some research, I found the HTTPClient API , this API helped me to do the dirty work, and it did pretty well. I will show you now, how to upload images and/or strings to the web server.

It’s pretty simple, actually. I gonna do in only one function!

 

// create a bitmap variable before anything;

private Bitmap bitmap;

// variable to set a name to the image into SD card;
// this variable, you have to put the path for the File, It's up to you;

public static String exsistingFileName;

// sendData is the function name, to call it, you can use something like sendData(null);
// remember to wrap it into a try catch;

public void sendData(String[] args) throws Exception {
	try {

		HttpClient httpClient = new DefaultHttpClient();
		HttpContext localContext = new BasicHttpContext();

		// here, change it to your php;

		HttpPost httpPost = new HttpPost("http://www.myURL.com/myPHP.php");
		MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
		bitmap = BitmapFactory.decodeFile(exsistingFileName);

		// you can change the format of you image compressed for what do you want;
		//now it is set up to 640 x 480;

		Bitmap bmpCompressed = Bitmap.createScaledBitmap(bitmap, 640, 480, true);
		ByteArrayOutputStream bos = new ByteArrayOutputStream();

		// CompressFormat set up to JPG, you can change to PNG or whatever you want;

		bmpCompressed.compress(CompressFormat.JPEG, 100, bos);
		byte[] data = bos.toByteArray();

		// sending a String param;

		entity.addPart("myParam", new StringBody("my value"));

		// sending a Image;
		// note here, that you can send more than one image, just add another param, same rule to the String;

		entity.addPart("myImage", new ByteArrayBody(data, "temp.jpg"));

		httpPost.setEntity(entity);
		HttpResponse response = httpClient.execute(httpPost, localContext);
		BufferedReader reader = new BufferedReader(new InputStreamReader( response.getEntity().getContent(), "UTF-8"));
		String sResponse = reader.readLine();

	} catch (Exception e) {

		Log.v("myApp", "Some error came up");

	}

}

 

And you should be good to go :)

Posted in Android, Java | Tagged , , , , , , | 2 Comments