Archive for 'JavaScript'

jQuery : Error: $(document).ready is not a function — Sure!

This error message appears only if another framework is in conflict with the almighty jQuery. For example You try to use Prototype/Scriptaculous for Lightbox but you also need Thickbox for something else, which requires jQuery.

Since no framework is compatible with another framework, you have to find a workaround to get things working.

And here comes jQuery in your help. The jQuery team was smart enough to realize that there will be conflicts between frameworks, especially the $ will cause massive headaches since it’s the basic of each framework. $ is the shortcut for the word “jQuery”

So, they invented jQuery.noConflict();. This will let you to replace the $ with the word jQuery, in all your code. So, when you need to call this: $(document).ready(function(){ … You simply replace the $ as I said above: jQuery(document).ready(function(){ …, don’t forget to call jQuery.noConflict(); before this.

So, when you use the noConflict() function, your code should look something like this:

<head>
  
  
  
</head>

World saved again, now you can use 2 frameworks together.

XHTML Strict incompatible with target attribute: FALSE


Clients… I had to create a website… XHTML Strict… AND opening all links in a new tab/window.
No probs, there’s the target attribute of the anchor elements! But not in XHTML Strict!
W3 states clearly that target attributes should be forgotten and avoided. Why, I have no idea, but if you want to create XHTML Strict pages, you can forget about the target attribute.

So let’s hack with Javascript this rule! Rules are set to have something to brake, that’s what we’ll do now. This is very simple code, basically a single function which loops through the document and adds to all the anchor elements the “target=’_blank’” attribute. As it’s created with Javascript, the XHTML validators should not observe. I think they won’t observe, so first check it out somewhere.

So, the Javascript code to open links in new window/tab while maintaining the XHTML Strict compliance is:

function open_in_new_tab() {
if (!document.getElementsByTagName){
return;
/*If the browser doesn't support DOM, do nothing*/
}
var anchors = document.getElementsByTagName("a");
/*Select all the 'a' tags, anchors*/
for (var i=0; i<anchors.length; i++) {
var links = anchors[i];
if (links.getAttribute("href")){
/*every anchor with 'href' attribute will get a new attribute,
only those with 'href' attribute set because we don't want
to mess with the section anchors, for example*/
links.target = "_blank";
}
}
}
window.onload = open_in_new_tab;
/*finally load the function on page load*/

And the word is saved again.

Javascript pop-up windows and parent page refreshing

This subject is quite interesting and i was searching for examples for long. Then I managed to do something, true that only by combining many examples i’ve found.

Let’s see the code then I’ll try to explain everything.

function popUp(URL) {
window.open(URL, 'WindowName', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=0,width=300,height=400');
}
window.onload = popUp("http://example.com");

The above function will pop-up window which will contain the page you put as value in the popUp function. I’ve put http://example.com, you put whatever you like, but preferably from your own domain if you want to have access to the pop-up’s DOM. You can play with the toolbar,scrollbars,location variables till hurts, basically they define how the popped up window will look and act. I wrote the above script so to pop the window up when the page loads (window.onload) , if you don’t like that and the fact that this even is blocked by most pop-up blockers, you can put a HTML button or link somewhere in the page, like this:

Pop Up the window

As I said before, there’s a slight issue with the stuff if you use the window.onload, specifically that your pop-up much likely will be blocked by pop-up blockers. You don’t want that, and even if it succeeds to pop-up, it’s annoying for the visitor, so just don’t do it, please.

OK, now let’s see the the parent window refreshing. Prent window is the page which pop-up up the small window. The pop-up window is the child. Usually, we use the parent refresh if we want to transfer a variable from the pop-up to the parent. The script which has to be placed in the child, popped up window is the following script:

function Parent() {
  window.opener.location.href = window.opener.location.href;
  if (window.opener.progressWindow){
    window.opener.progressWindow.close()
  }
  window.close();
}

and the button or link which closes and refreshes the parent window is

Click here to close this window and refresh the parent

A working example is situated here. It’s a loop so if your pop-up blocker doesn’t block the first pop-up, most likely you’ll get annoyed in no time.

And I think that was all. You can also transfer variables from one window to other, but that’s for another day… so, the show is over… there’s nothing to see here, pass over please.

Getting the client’s IP address using JavaScript

This will be a serious disappointment: simply it’s not possible. Javascript is not designed to access this detail of the clients.
I find this thing very odd, because while it’s possible to get the CPU type, the screen height and width and many other details of the client, we can’t get the IP of the client.

So we need other way to do it. Here comes in help server side scripting, basically you define the javascript variable using a server side script, like this:

var clientip = <?php echo $_SERVER['REMOTE_ADDR']; ?>
/*OR*/
var clientip = <?= $_SERVER['REMOTE_ADDR'] ?>

Other server side code is also welcomed, it doesn’t matter whether you use PHP or ASP, the fact that you can’t use JS matters only…

So, world saved again… partially

Creating and manipulating IFrame with Javascript

Great day today for creating IFrames with JavaScript! Well, maybe there’s no good day to do that, we will try it anyway.

First, what are IFrames?

IFrame is abbreviation for “inline frame”. Basically, using an IFrame you bring another page’s content in your HTML page. The content can be on a remote domain or on your own domain too, it doesn’t matter where is the source, the IFrame will display the remote page’s content.
There are some attributes you can set when creating an IFrame, I won’t list them as it’s published in many places. For good reference go to W3Schools IFrame reference.

Problem with IFrame is that in XHTML Strict is not supported, so possibly in the next HTML (5) won’t be supported either. Developers should forget this tag in the far future, but as it’s still supported by all the browsers we may use it with courage.

IFrames and Javascript

There are times when you have to generate IFrames with Javascript. Creating an IFrame with Javascript is very easy, a few line, that is. The following Javascript code will generate you an IFrame

fr1 = document.createElement("IFRAME");
fr1.setAttribute("src", "http://yourdomain.com/page1.html"); /*Set the source of the IFrame*/
fr1.setAttribute("name", "iframe_name"); /*Set a name for the IFrame for easy access*/
fr1.style.width = 170+"px";
fr1.style.height = 600+"px"; /*Set height and width*/
document.body.appendChild(fr1); /*push it into the document*/

That was all. You have your IFrame which will be visible only for the users who have Javascript enabled.

Accessing IFrame with Javascript

There are two ways you can access an IFrame with Javascript: using the document object model (DOM from now on) and using every browser’s frames array.

From the frames array

When a page contains frames, in this case inline frames, the browser creates a special array for itself where it stores all the frames’ details separately.
So, let’s say there are 3 frames on a page. The browser will create an array (always) named “frames”. Parsing the code line by line, the first frame in the document will be indexed as 0, the second as 1, the third 2. So the frames array will look like this

frames(0=> "1st frame's details",
1=> "2nd frame's details",
2=> "3rd frame's details")

Or if the frame has a name set, you can access it via its name:
frames(frame1name=> “1st frame’s details”,
frame2name=> “2nd frame’s details”,
frame3name=> “3rd frame’s details”)

Generally, the browsers support both methods, i prefer the numbered version but using the named version might be easier to remember.

The objects which are existent in a normal page will be existent in the iframes too.
So, accessing the iframes via the frames array will look like this:

window.frames[0].document....;

For the matter of the example, let’s set the “body” element’s style to “background:#000000″

window.frames[0].document.getElementsByTagName('body').style.background="#000000";

If you know the ID of an element from the IFrame’s content, you can set only one specific element’s style by writing:

window.frames[0].document.getElementById(id_ofan_element').style.background="#000000";

The above code will set the element’s with id of “id_ofan_element” background color to black. Remember that this element is in the IFrame, not on the page which called the IFrame tag.

If the IFrame’s source is on a remote domain, for example you call the IFrame on http://example.com and the source of the IFrame is on http://other-example.com, even though the frames array will exist, there’s no way to access any of its details. That’s because it would be considered cross-site scripting (XSS from now on) and that’s a big nono, the browsers’ XSS protection will stop you doing anything with the IFrame’s content.

From the DOM

If you know the ID of the IFrame, you can access the IFrame via the DOM.
Accessing the IFrame via DOM looks like this:

document.getElementById("frame_id"). ...

That’s it.
Using the DOM to access the IFrame is a better solution. On slower PCs or on old browsers some time has to be passed before the frames array is created, thus your script will fail. The DOM on the other hand exist from the beginnings of the process.

Manipulating IFrames with Javascript

Remember that when the source of the IFrame is on a remote domain, you can’t access the IFrame’s any detail with Javascript. There’s no way you can do it… I’d be interested though if there’s a way so please let me know if you know how to do it. just drop in the comments.

So, you have an IFrame with ID “frameID” and name “frameName”. It’s source is on the domain as the script which called the IFrame.
Let’s change the IFrame’s source with Javascript:

/*using the DOM*/
document.getElementById('frameID').src = "new_page.html";
/*using the frames array*/
window.frames['frameName'].location.href = "new_page.html"

Setting the style of an IFrame, using Javascript.

/*using the DOM*/
document.getElementById('frameID').style.margin = "5px";
/*using the frames array*/
window.frames['frameName'].document.style.margin = "5px"

Some thoughts on the IFrame

The IFrames are great in bringing other page’s content to another document, but from the search engine optimizers’ point of view IFrames are equal with quick death. Why? If you know a page which has excessive IFrame, search it in Google. You won’t find anything related to the content of the IFrame. As of why, search engines are still young, they are a bit dumb (sorry). The content of an IFrame is inaccessible for them thus they will know nothing about the IFrame’s content. Of course, if you are in hiding content from search engines, it a cool way.
Other than the above, IFrames will be deprecated in the future. I think the reason is their great insecurity, vulnerability of XSS attacks. Other reason I can’t think of.

v8 Javascript Virtual Machine: Welcome in the new era of the web

First let’s see what is this mysterious thing which has been included in Google Chrome and , well, created a smaller storm amongst the developers. Well, maybe it was only a wind. Or whisper?

It’s a C++ engine which can be embedded in any other C++ application freely. It parses the Javascript (ECMA-262 standard), collects the memory garbage (small chunks of memory which are a result of closed processes) and handles memory allocation. It should speed up script execution a big time.

Google claims that Chrome, thanks to V8 is 10 times faster than Firefox 3.0 . As Darren Hobbs states on his blog, you can optimize a code for a benchmark, so maybe Google’s benchmarks are not as accurate as they state. Anyway, a quick test on a Javascript Benchmarking tool gave the following results:

  • Firefox 3.0 — 27535.2ms +/- 7.0%
  • Chrome — 5127.6ms +/- 3.7% (WOW!)
  • Safari (win) — 9317.6ms +/- 9.4%
  • IE 7.0 — 81825.4ms +/- 3.0%

That means that it’s not 10 times faster, but only 5. Not that it’s not enough!
By the way, see the IE result? Impressive, I have to admit, it’s the slowest browser when talking about Javascript.

I’m not a C developer, I know only basic stuff, but when I saw the V8 source code I was amazed! The assembly code is generated dynamically. I always knew this is possible, I even heard that it’s an extremely effective way to create high performance applications, I just never used it. For me it’s quite hard to understand though. But as for the applications, it’s a very effective way.

So, the verdict on V8: the test talks for itself, the Chrome engine thanks to V8 and WebKit is extremely fast Javascript executor, the code behind V8 is designed to be very fast, it follows the current standards.

If you develop some application which could use the V8 engine, I say try it. You can only win.

What do you think about the Gears Geolocation API

What you see on the top of the sidebar is not server side code. More than that, not even a bit of PHP has been used. In fact, even HTML is almost not present. It’s Gears and its GeoLocation API.

When you allow Devoracles to collect some data about you, more exactly your location on the Earth, Gears queries Google about your location. Again, not even a bit of server side code on Devoracles’s side.

This is the GeoLocation API of Gears. And What can be used for? Think about AdSense, for the matter of the example. It always knows where you are. OK, almost always.

Any thoughts on this API?