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.

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 2 comments

“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 29 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: , ,

Behavior helping cross browser transparency

February 16, 2009 1 comment

One of the things that I hate the most when developing DHTML applications is that I have to write code for at least 3 browsers. And nowadays the differences between them are not so big, but 5 years ago …
If you write some DHTML code you have to consider at least Firefox (>=2), Internet Explorer (>=6) and Safari. These are the most common web browsers. Google Chrome is gaining lately some popularity, but you can assimilate it with Firefox. Opera and other browsers have such a low percentage usage that you can safely ignore them.
Every time you will see some JavaScript code that shows you how to do some tricks, you will probably see a notice that is cross-browser. And if you dig deep inside the code, you will probably see lots of code that does nothing else but testing for the browser and then applying specific code for it.
It would be so nice if all the browsers will implement the standard(W3C) and only the standard. Then you will have an environment by default cross-browser.
A compromise are the existing cross-browser frameworks. But … you have to learn a new framework and you’re stuck with that framework, as your code will not work without it. And, if in the future browsers will become more and more compliant (it’s not a joke, IE8 seems to make small steps in that direction), you are still stuck with that framework.
Nice will be a framework that will ensure the cross-browser thingy in a transparent way.
Let’s be more practical. Some time ago I wrote an article about how you can make HTML elements transparent in a cross-browser way. But you actually had to write code for three browsers. Safari follows the standards here, Firefox >= 1.x as well (we can ignore FF 0.x – nobody is probably using it anymore). So I will focus on a workaround to help you write

element.style.opacity = 0.7;

and to have the desired result even in IE. Let’s admit, IE has always been the “rebel kid”, but also the most used.
The idea is simple. Every time I modify the “opacity” property of an element style in IE, I will run some code to do the necessary translation and ensure the cross-browser in a transparent way.
Now, for this we will use behaviors, an IE specific feature. Which in this case is good, as the code will be ignored by other browsers.
First of all attach a behavior, described in cb-opacity.htc, to all the elements, through CSS code (put it in a STYLE tag or a separate .css file):

* { behavior: url(cb-opacity.htc);}

.
And now the most interesting part – cb-opacity.htc

<PUBLIC:COMPONENT lightWeight="true"> 

<PUBLIC:ATTACH event="onpropertychange" handler="doOnPropertyChange"/>
<PUBLIC:ATTACH event="oncontentready" handler="doOnContentReady"/>

<SCRIPT>
function doOnContentReady() {
    // when this behavior is attached to an element, then check if the opacity was not already set
    // most likely through CSS code
    if (element.currentStyle.opacity != null) {
        element.style.filter = 'alpha(opacity=' + (element.currentStyle.opacity * 100) + ')';
    } else if (element.style.opacity != null) {
        element.style.filter = 'alpha(opacity=' + (element.style.opacity * 100) + ')';
    }    
}

function doOnPropertyChange() {
    // every time the style opacity is changed through JavaScript, then modify the CSS filter too
    if (window.event.propertyName == "style.opacity") {
        element.style.filter = 'alpha(opacity=' + (element.style.opacity * 100) + ')';
    }
}
</SCRIPT>
</PUBLIC:COMPONENT>

And now IE has support for style.opacity. Pretty nice, isn’t it?

Later edit: The same can be applied to cssFloat and styleFloat.

Categories: Web Tags: , ,

!u@#!^$ “Invalid character” IE error

January 28, 2009 16 comments

Internet Explorer is probably the worst browser for web development. Or maybe I’m too used to Firefox.
Let me give you just a simple example, that can drive you mad.
Have you ever encountered the below error?

Line: 2
Char: 1
Error: Invalid character
Code: 0
URL: ... 

I did. So I googled a little bit to see what could be the problem and I come over this article. Of course, that wasn’t the problem. Finally, I realized myself: one of the referenced JavaScript files was missing.

I know that this is my mistake, but I’m totally amazed about the usefulness of the IE error messages. It is a missing file, not an invalid character.
Not to mention, that the URL is always the main one, even though the error occurred in one of the referenced JavaScript files and the line reported is not the actual line where the error occurred, but increased by 1. But this is already common knowledge.

That’s one of the reasons I always use Firefox for web development, try to stick to the standards and only in the end, test the solution on Internet Explorer too. And there is no decent JavaScript debugger for IE. And …

I also wrote a small HTML, for you to see what I’m talking about.

Later update: This was tested on IE6. In IE8 works as expected.

Categories: Web Tags: , ,

Whoami in SharePoint

September 23, 2008 Leave a comment

One of the nicest things in SharePoint is that you can access it not only through the web interface, but through its web services as well. Combining this with AJAX, you can build pretty good user interfaces with a SharePoint backend.
When doing this you’ll definitely be interested in knowing who is currently logged in.
So if you are modifying a SharePoint generated page (like NewForm.aspx, EditForm.aspx or a page associated with a view) and add (D)HTML code to it, you can easily access the _spUserId variable which holds the current logged in user ID in SharePoint.
From this point on if you’re interested in more details you just simply run a query against the user list using SharePoint web services.
If you want to have these information in a page of your own, you can simply run that query using the CAML tag UserID.

<Query>
  <Where>
    <Eq>
      <FieldRef Name="ID"/>
      <Value Type="Integer"><UserID Type="Integer"/></Value>
    </Eq>
  </Where>
</Query<

Just as a note, don’t forget to put Type="Integer" in there.

If you wonder how I got over this, you should read my other article.

Categories: Web Tags: , , ,