Archive

Posts Tagged ‘javascript’

“Sad little piece of software”

June 5, 2011 2 comments

What do you think this code will do?

<html>
<body>
<a name="one">an anchor</a> <hr />
<div id="one">a div</div> <hr />
</body>

<script>
document.writeln("Element with id 'one' is '" + document.getElementById("one").innerHTML + "'");
</script>

</html>

You would think that it will print that element with id one is a div. Yep, and Firefox, Chrome and Safari will agree with you. But not IE :). For IE getElementById is synonym with getElementByName. No matter the version – 7, 8 or the mighty IE 9. I don’t know if you would guess, but if you put the div first, it has the expected behavior.
So, getElementById, in IE, returns the first element that has the id or name attribute, equal to the given value. Good to know. But sad.

Advertisements
Categories: Web Tags:

Back To Top – user script

November 11, 2010 Leave a comment

I previously explained how you can include a back to top button in your page. Pretty simple technique.
But Cosmin had the idea to automatically include this in all the pages using user scripts, so you can improve your browsing experience. For you and for the others.
So a little bit of tweaking for the original script and I got a working user script. And it works in Firefox, IE and Chrome.
I tested it with FF 3.6, IE 8 and Chrome 7. It seems that user scripts are also supported by a Safari for Mac plugin, but I have no knowledge about Safari for Windows. And for Opera … I don’t care too much about Opera and their less than 1 percent market share.

For Firefox you have to install Greasemonkey add-on, for IE you have to install the IE7Pro plugin and Chrome has native support for user scripts.
And now to install the user script – just click here for Firefox and Chrome, and here for IE. The only difference between the two is just the name, in IE, the user scripts must end with .ieuser.js as opposed to .user.js in other browsers. Otherwise the content is the same – I like cross-browser, non-intrusive JavaScript code ;).

Enjoy!

Categories: Web Tags:

Always back to top

November 4, 2010 1 comment

Do you want a button in your web page to go back to top? Visible only when you need it? If yes, just include the following lines in your head tag.

<link type="text/css" rel="stylesheet" href="http://beradrian.users.sourceforge.net/articles/btt/btt.css" />
<script src="http://beradrian.users.sourceforge.net/articles/btt/btt.js"></script>

That was the really short version. If you want to know how it is done or how to customize it, I will explain it in detail.
First, the idea. We will automatically insert a button (DIV tag with A inside) and we will show it only when it is needed – when we already scrolled one page down. And it will stay in the same place no matter how much we scroll.

Let’s go first into the JavaScript.

function goToTop() {
	var body = (document.body ? document.body : document.documentElement);
	body.scrollTop = 0;
	body.scrollLeft = 0;
	return false;
}

function showBTT() {
	var body = (document.documentElement &amp;&amp; document.documentElement.scrollTop ? document.documentElement : document.body);
	document.getElementById("btt").style.display = (body.scrollTop &gt; body.clientHeight * 1.1 ? "block" : "none");
}

function initBTT() {
	var body = (document.body ? document.body : document.documentElement);
	var btt = document.createElement("DIV");
	body.appendChild(btt);
	btt.appendChild(document.createElement("A"));
	btt.id = "btt";
	btt.firstChild.href = "#";
	//btt.firstChild.innerHTML = "Back to top";
	btt.firstChild.style.display = "block";
	btt.firstChild.style.width = "100%";
	btt.firstChild.style.height = "100%";
	btt.firstChild.onclick = goToTop;
	
	showBTT();

	if (window.addEventListener) {
		window.addEventListener("scroll", showBTT, false);
	} else {
		window.attachEvent("onscroll", showBTT);
	}
}

if (window.addEventListener) {
	window.addEventListener("load", initBTT, false);
} else {
	window.attachEvent("onload", initBTT);
}

Now let me explain. Function goToTop simply scrolls to the top of the page. This is the handler called everytime the button is pressed by the user.

In showBTT (BTT stands for BackToTop button) we decide when to show the back to top button. The condition is body.scrollTop > body.clientHeight * 1.1, which means that we will show the button when we scrolled more than one screen with 10%. You can change the factor to whatever you like and you can even have some static values in there like:

  • body.scrollTop > body.clientHeight + 100 when we scrolled more than one screen with 100 pixels
  • body.scrollTop > 200 when we scrolled 200 pixels from the top

Function initBTT does the magic. When the document is loaded (see the last lines), this function is called and a DIV with A inside, the back to top button, is added to the document. If you want some text inside the button just uncomment the line

//btt.firstChild.innerHTML = "Back to top";

And now let’s see how we can cutomize the layout – btt.css.

#btt {
	background: #eeeeee url(btt.png) center center no-repeat;
	width: 66px;
	height: 54px;
	top: 200px;
	left: 80%;

	opacity: 0.9;
	filter: progid:DXImageTransform.Microsoft.Alpha(opacity=90);
		
	border:2px solid #eeeeee;
	border-radius: 5px;
	-moz-border-radius: 5px;
	-webkit-border-radius: 5px;
	box-shadow: 1px 2px 6px rgba(0, 0, 0, 0.5);
	-moz-box-shadow: 1px 2px 6px rgba(0, 0, 0, 0.5);
	-webkit-box-shadow: 1px 2px 6px rgba(0, 0, 0, 0.5);

	position: fixed;
	_position: absolute;
	_top: expression(((document.documentElement && document.documentElement.scrollTop 
		? document.documentElement.scrollTop :  document.body.scrollTop) + 200) + 'px' );
}

There are some hacks that you have to read first about CSS fixed position and opacity.
Besides the implementation details, with the CSS fixed position, we can configure here various aspects of the button: background, size, position on screen, opacity, border etc. If you want to configure the text on the button, if any, you should use #btt A as the CSS selector.

And finally, the demo.

Categories: Web Tags:

Patu Digua – JavaScript/HTML/CSS Obfuscator/Compressor

September 6, 2009 1 comment

I finally managed to get a first version done for a web obfuscator and compressor.
First of all, why to use such a program. Some may say to hide your HTML/JavaScript/CSS code. Right. This could be one option. And it is powerful enough to do so. But I would personally use it to reduce the size of the code. I tested on a few projects and the code gets reduced up to 60-70% from the initial size. It’s not like a zip but quite good if you take into account that you’re dealing only with scripts.
It is very good practice to comment and indent your code, but this doesn’t have any value at all for the end user, it only eats up his/her bandwidth.
The application has a very nice and intuitive interface (check out the screenshots), it is very customizable and it can be run on both UI and command line mode. A nice feature in the graphical interface is the drop zone, where you can drag and drop files or folders and they are automatically processed. Just switch first to the drop zone mode.
If you want to play with it you can download it from SourceForge or check out its home page.
I would gladly want to hear your opinion or how do you use it.

Categories: Software, Web Tags: , ,

MyUI – JavaScript library

May 11, 2009 Leave a comment

I worked with JavaScript for more than 10 years. In different companies, in different projects, doing various things. Many times I ended copy-pasting the code from here to there.
Finally, a few months ago I decided to put all the common JS code that I have into one big library: MyUI.
Why MyUI?
UI because the library is mostly oriented on creating web user interface components and my because the scope is to make it easy to use and highly configurable. That’s why I paid attention to documentation and augmented it with lots of examples. There is also small demos for the most important features. I will also come back with tutorials on this blog.
So far the library is at the beginning and, if you use it, I will definitely value your feedback.

Categories: Software, Web Tags: ,

Object Oriented Programming in JavaScript

May 8, 2009 1 comment

“JavaScript is one of the most misunderstood programming languages”.
Do you agree on this? Personally, I partially agree. And I outline PARTIALLY.
I agree that the language allows you to do a lot of stupid things and that’s the case with most of the weak typed languages. On the other side, strong typed programming languages like Java or C#, stops you from doing some of the mistakes at compile time and saves you from a lot of headaches later.
But why I said partially? Because if you instruct yourself to work in some structured way, even JavaScript can be less painful. In this article I will tell you how to do this and I will cover how to implement the major OOP(Object Oriented Programming) principles in JavaScript.

Today’s systems problem becomes more and more maintainability and not performance. More and more features are requested by users and the computing power becomes more and more cheaper and widely available. And then a good software system architecture is the key. Object Orientated Programming augmented with Design Patterns comes with good solutions to these problems.

OK, but what this has to do with JavaScript? JavaScript is actually an OOP programming language, except that has a different paradigm then the other traditional programming languages. If C++, Java or C# are class-based OOP languages, JavaScript is prototype based.
Before diving deep into JavaScript OOP, let me give you a little bit of background about JavaScript itself. Even tough you know the language pretty well you should still read this, as it will help you in a deeper understanding.

Basically, everything in JavaScript is an object. And every object has a map of properties associated, from where you can get (object[propertyName]) or set (object[propertyName] = propertyValue) a property. If the property name can be only a string (if another type is passed the toString method is called first), the property value can be anything: objects, numbers, strings and even functions.
With that in mind let’s get back to OOP. Supposing that you are used with a class-based paradigm, I would make a parallel between the two.
Let’s see first how to define a class.

function MyClass() {
}

You haven’t defined only a function, but a class as well. You can create new objects using var obj = new MyClass();. So you also have the constructor. But this is the no-arg constructor. How can you define a constructor that accepts arguments. Just add some arguments to the function. If you don’t specify them, they will be passed as null. And you have the overloading too.

function MyClass(name) {
    this.name = (name != null ? name : "Default");
}

You already saw the this keyword. It is a reserved word and refers to the function scope, which in the case of creation of new objects is the object itself. And name is a class field. JavaScript class fields can be accessed only using this.propertyName, which is practically an equivalent form of this[propertyName]. The this prefix is not implied, but mandatory.
Now let’s define some class methods. When doing this you have a few options. I’ll present them to you and tell you the advantages and disadvantages and what is my recommendation.

  1. function MyClass(name) {
        this.name = (name != null ? name : "Default");
        this.doIt = function() {
            // do something
        };
    }
    
  2. function MyClass(name) {
        this.name = (name != null ? name : "Default");
        this.doIt = MyClass_doIt;
    }
    
    function MyClass_doIt {
        // do something
    }
    
  3. function MyClass(name) {
        this.name = (name != null ? name : "Default");
    }
    
    MyClass.prototype.doIt = function() {
        // do something
    };
    

In the first version doIt is defined as a method. When the constructor is called, a new function is created and the value of the doIt property is assigned to it. From a syntactical point of view this looks very much alike to Java or C# and you probably like it, but that’s far from optimal. Because the function will be defined for each and every object of the class.
The second version overcomes this problem. The function MyClass_doIt is defined only once and in the constructor is only referenced.
But there is even a better way(3), but we have to discuss first about prototype.

I was saying above that every object has a set of properties. If you try to access a property or a method that it is not defined for that particular object, then the next step taken by the JavaScript engine is to look in its prototype. If still not found, then the prototype of the prototype will be inspected and so on. The prototype hierarchy is similar to the class hierarchy from Java or C#. If you want you can look at the prototype as an object common to all the objects of the same type. If you modify a prototype property this will be reflected in all the objects with the same prototype. If you define a function as a type, all the object created with the new operator will have the same prototype, the function prototype itself.

In this light, the third version becomes self explanatory: define the class methods in the prototype directly, so all the existing and future objects can benefit of them.
If you add or modify a method to a prototype, not only that all the future objects will benefit of it, but also all the already created objects. This concept of dynamically modifying a type could be new if you come from the Java or C# world.

And now let’s discuss about inheritance, probably the hardest part of OOP in JavaScript. Inheritance in JavaScript is not implemented as easy as other traditional OO languages. This is not simply marking as being part of an hierarchy, but having the same prototype.

Let’s extend MyClass with MyExtendedClass.

function MyExtendedClass() {
}

MyExtendedClass.prototype = new MyClass();
MyExtendedClass.prototype.constructor = MyExtendedClass;

The line MyExtendedClass.prototype = new MyClass(); links the prototype of the prototype of MyExtendedClass to MyClass, simulating the inheritance. The line after just sets the correct constructor of MyExtendedClass objects, otherwise set to MyClass.

Along with inheritance comes the super concept and overriding. If you define a method in the extended class prototype you simply override from the base class prototype (it will be found there first). There is a way to call the super constructor and methods:

function MyExtendedClass() {
    MyClass.call(this); // call the super constructor
}

MyExtendedClass.prototype = new MyClass();
MyExtendedClass.prototype.constructor = MyExtendedClass;

MyExtendedClass.prototype.doIt = function() {
    MyClass.prototype.doIt.call(this); // call the super method
};

Actually this way you can call any method in the hierarchy.

If we touched inheritance, then polymorphism comes naturally on the way. And if we think that objects in JavaScript don’t have a reference type, but only the actual type, then this is automatically implied.

We have to do one more stop: encapsulation. The solution here is a little bit more tricky. I will show you how to define a private field an accessor methods for it.

function JustAClass() {
    var privateField = 10;

    this.getField = function() {
        return privateField;
    }

    this.setField = function(value) {
        privateField = value;
    }
}

So, the solution here is to define a local variable. The context (and the variable in this context) will be accessible in the methods (as they are in the same context), but not outside. Personally I don’t like this method as this relies on the first way of defining methods.

The major OOP principles are abstraction, encapsulation, inheritance and polymorphism. In this article I touched how you can implement all these principles. Abstraction comes with design and you have to use composition. You saw how to define fields and methods for a class. Encapsulation is basically about making the data private and I described how to implement it. Inheritance is about having a common prototype.

Just to make it easier, you should keep in mind that an object in JavaScript is a collection of properties (and even methods can be considered properties). And a property is first looked upon in the object and if not found in the object’s prototype, and then in the prototype’s prototype and so on.

I always said that if you want to take an interview to a JavaScript developer, the best way will be to ask him to create an hierarchy of two or more classes and discuss the pitfalls. Learning a framework, some method signatures, some object documentation, this comes with time and exercise, but knowing all these internals must be crystal clear from the beginning if you want to develop complex systems in JavaScript.

Categories: Web Tags: ,

Calculating the angle between two points on a circle

March 23, 2009 25 comments

I needed to calculate the angle between two points on the same circle. Don’t ask why, totally a new more complicated discussion.
So I had to remember a little trigonometry from the old days. Actually, this is done surprisingly easy, by simply using the atan2 method. Fortunately, this is available in JavaScript in the Math library.
In my problem, I had the center of the circle, one of the coordinates point(p1) and I had to find out the angle between the point (p0) at the 12-hour (imagine the circle as a clock) and the given one.

Angle between two points on a circle

Angle between two points on a circle


First of all the coordinates of the point at 12-hour is

p0(x,y) = (center.x, center.y - radius)

where radius is the circle radius and is calculated (according to Pythagorean theorem) as

radius = sqrt(|center.x - p1.x|<sup>2</sup> * |center.y - p1.y|<sup>2</sup>)

Now let’s calculate the angle:

angle = atan2(p1.y - p0.y, p1.x - p0.x)

This will return the angle in radians. If you want to translate it into the interval [0,2 π] then simply multiply by two. If you want to transform it to degrees use angle * 180 / π.
Below you have a JavaScript function that receives as arguments the coordinates of the center and second point and returns the angle in degrees in the interval (0°, 360°) between the 12-hour point and the second point

function angle(center, p1) {
    var p0 = {x: center.x, y: center.y - Math.sqrt(Math.abs(p1.x - center.x) * Math.abs(p1.x - center.x)
            + Math.abs(p1.y - center.y) * Math.abs(p1.y - center.y))};
    return (2 * Math.atan2(p1.y - p0.y, p1.x - p0.x)) * 180 / Math.PI;
}

I also wrote a small demo.

Later update:
As I had this question in the comments, in case you have the center coordinates, radius, angle and you want to calculate the second point coordinates, below is the JavaScript function. The first point is considered to be at 12’o clock.

function getPointAt(center, radius, angle) {
    // Please note that the angle is given in radians; 
    // if given in degrees uncomment the line below
    //angle *= Math.PI / 180;
    return {x: center.x + Math.sin(Math.PI - angle) * radius,
        y: center.y + Math.cos(Math.PI - angle) * radius};
}

All the coordinates are relative to the top left corner.

Categories: Software, Web Tags: , ,