Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

Sunday, May 4, 2008

JavaScript Tip: Submit Form On Enter Key

A common practice with search forms is to have them submit when the enter key is pressed, instead of requiring the user to use their mouse to press the submit button (or using tab key to tab to the submit button).

Here is a simple way to do that in JavaScript:
First, define a input box:


<input name="txtsearchentries" id="txtsearchentries" type="text" size="13" value="" />


Second, create a function to be placed in the head area of the webpage:
//see if the user pressed the enter key while using a specific control

function submitSearchOnEnter(variable)
{
var keyCode;

//get whatever key was just pressed
//try to account for different methods of getting
//event keys depending on implementation
if(window.event)
{
keyCode = window.event.keyCode;
}
else if(variable)
{
keyCode = variable.which;
}

//if the key was the enter key, perform the necessary function
if(keyCode == 13) //13 = enter key
{
//here is where you process the form item or call a function to do that
searchEntries(); //call search
}
}


Third, you need to assign the function above to to be an event handler:

//assign an event handler to the search box so we can have it
//submit when user presses enter
document.getElementById('txtsearchentries').onkeyup = submitSearchOnEnter;

That's it. Should be able to assign it similarly to other fields on the page too, but then you would need to think of how to create separate functions to handle each.

Thursday, April 10, 2008

Objects in Javascript

Javascript does not use a standard class model. It uses objects that are like associative array structures of data, or so I have read. Regardless of how it works, you can make a class-ish type construct in Javascript.

I'll try to go over the basics here to help anyone who is interested.

Objects are defined by creating a new function. Inside the function you can define variables and methods that are attached to the primary function. The primary function is really like the constructor for the object as well.

For example:


function ObjectExample(constructorParameter1, constructorParameter2)
{
//define a variable and assign a constructor value to it
this.variable1 = constructorParameter1;
this.variable2 = constructorParameter2;

//you can also define variables with var, but they act differently
var variable3 = this; //assigns an instance pointer to a "constructor" variable

//defines a function that is attached to the object
//this function has one parameter
//pretend that this.variable1 is a reference to a div element
this.statusIndicator = function(statusText)
{
//make sure an element reference was returned before trying to set properties
if(this.variable1 != null)
{
document.getElementById(this.variable1).innerHTML = statusText;
}
}

//you can also have a function with zero parameters
this.aBoringFunction = function()
{
alert('YO!');
}

//you can call an instance function from inside the "constructor" (aka. primary function)
this.aBoringFunction(); //every time an instance is created we will get a pop-up
}



To use the object we just defined we would do something like this:

//create a new instance
var newObjectInstance = ObjectExample('7', divReference);

//execute a object function
newObjectInstance.statusIndicator('Hello...');




That's about it, let me know if I missed something, or there was an error. I typed the code out rather then copying something I know works for readability reasons.

Javascript Rant

I've been working on something recently where I decided to have most of the program run in a client's browser. It's basically a blog system that works with that asp- xml-to-access-db class I released on here as an LGPL piece of code. The clients browser sends/requests information in XML to the server script and everything turned out peachy. I'm overall extremely happy with it.

Now that I'm done writing the script. I learned quite a bit more about Javascript that I didn't know in the past. The initial few days of working with it were tragic. I'm not too fond of Javascript's "object" model and lack of a standard class model. While javascript works and provides a good deal of functionality, it feels "dirty." Maybe my fellow "old school" programmers can understand.

Besides the object model, the DOM in general is a pain to work with, and hard to find information about (that works in multiple browsers). Inconsistencies, things that logically should work don't, and, trying ~5 different suggested methods to do something, but finding out that only 1/ 5 seems to actually work.

If you don't agree with me, have you ever tried encapsulating XMLHttpRequest in a "class" object? There are a few gotchas that I stumbled on, which I hope to talk about in the future.

My tip of the day about Javascript: Objects are functions are objects can be variables with no data hiding what-so-ever...

Friday, February 2, 2007

Accessing page content from the front and back-end of a site

As I'm programming this database driven website, I've come into a few irritating little issues. Today I'll talk about a few methods to access page content (images) from the back-end.

I've created a way to create and edit page content with a browser based WYSIWYG editor. The problem is after the first time the data is submitted to the server, all images are set with a path that now only works from the root directory of the website. So when a user tries to edit some page content with images in the WYSIWYG editor they see broken images (aka. "The dreaded Red X").

I thought of a few ways to fix the problem. I'll also mention which method I actually used in the end.

1. Have the PHP script handle the path conversions. This would mean two functions or so with a few replacements using regular expressions. So when the fetched data is sent to the user all of the html image tags are modified. When or if the user sends the data back they are remodified (excluding any new images the user is submitting). This is probably the safest bet.

2. Create a synaptic link if the server is on Linux/Unix. For example if the site root is www/, the site editor is in www/editor, and the content is in www/images. You would create the synaptic link in the www/editor directory linking to www/images directory. Probably the easiest solution by far, but I want my site to work on both Windows and Linux/Unix servers if possible. I'm developing the site on Windows, so I did not try this, but I'm pretty sure it would work. I also know that windows has a way to create similar links, but it seems like a pain to use so I didn't bother.

3. Use JavaScript to handle the temporary conversion. This is the route I picked. I was just looking for something quick that worked and this was it. Well it wasn't exactly quick because I spent a few minutes researching what function I needed to use and exactly how it works. The tutorials I saw were lacking...

Here is an example of the code that will do the initial edit, so the user can see the images in the WYSIWYG editor:


function fixImagePaths(textAreaId)
{
var tempHtmlData = document.getElementById(textAreaId).value;
tempHtmlData = tempHtmlData.replace(/(<img\s.*src=")(images\/[^"]*"\s.*>)/gi, '$1/../$2');
document.getElementById(textAreaId).value = tempHtmlData;
}


The KEY problem that took me a few minutes to figure out was that the first parameter (the regular expression) in the replace function can't have any type of quotes around it. If you've never heard of regular expressions, I highly suggest that you read up on them. They are extremely useful in a multitude of applications. Anyways, what that function does is take data from a wysiwyg html textarea and search through the whole thing for img tags. When it finds one that has a src directory that starts with "images/" it replaces it with "/../images", this gets the browser to jump back a directory to find the right path to the image folder.

I have this function execute on the body onload event. I'll also have a second similar function execute on the form onsubmit event. This solution seemed a bit easer then the php one. Well that's it for now!

Saturday, December 9, 2006

No, but there is more...much more thanks to my new friend ajax.

As I mentioned in the previous post, I made a static website in html, css, javascript, and json. It works pretty good and that's great. The problem is my sister is the one who should be adding/editing content because it is her site. So the question is, how can I make an easily update-able site that is on a server without any server-side coding functionality?

I had figured out pretty much how I wanted it to work even before I finished coding the first version of the site. Sure, I could just write a client application that spits out html\css code and uploads it to the server, but no, that isn't cool enough.

I wanted to break up the site data and formatting. That way the client application would only need to create json files and upload them along with any new content.

That means the json data needs to be removed from the html files and the html page now needs to allow fetching of the data whenever the person using the site needs it. What does this mean? It means that I now have a site that is comprised of: index.htm, a css file, and a javascript file. This is pretty much the whole website (not including the json files)! How can this be possible? Thank our new friend ajax (Asynchronous JavaScript and XML). What that does is allow javascript code to fetch data from the server (in my case text files containing json data) when the user does some type of action.

Lets get on to a few examples, shall we!

The whole index page:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<link rel="stylesheet" type="text/css" href="sapphirearts.css" />
<script src="sapphirearts.js" type="text/javascript"></script>
</head>

<body onload="getJsonFromServer('links.json', 'init');">
<div id="divcontainer">
<div id="divbanner"></div>

<div id="divlinks"></div>

<div id="divbody">
<div id="divbodycontent"></div>
</div>

<div id="divfooter"></div>
</div>
</body>
</html>


What happens when this page is loaded on to a client computer? The javascript function getJsonFromServer() is called. This function downloads a block of json data that defines the main links for the site. Pretty cool, eh? When you click one of these main links, they call getJsonFromServer() again, but with different parameters and ends up filling the content area of the page.
function getJsonFromServer(filename, newstate)
{
xmlHttp = getXmlHttpObject();

if (xmlHttp != null){
currentState = newstate; // save the state so we can process it later
xmlHttp.onreadystatechange = stateChanged;
xmlHttp.open("GET", filename, true);
xmlHttp.send(null);
}
}


Which relies on the function:
function getXmlHttpObject(){
var objXMLHttp = null;

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

return objXMLHttp;
}


The getXmlHttpObject() function needs to execute different functions based on what bowser the user is using. Just one of the multitude of problems getting cross browser compatibility.

javascript and json together forever

I created a static website recently for my sister. It is hosted on our ISP's server, which means there is no way to do any server-side coding. The site is coding in html with a few pages using javascript and JSON (javascript object notation). Just what is JSON you ask? It is simply a way of structuring data like the more commonly known XML format, but it's easier to use with javascript.

Why not just code the site in straight html? Well, I wanted the website to be somewhat easily modifiable. Even if the JSON is embedded in the page, it still allows easier access to the content and also cuts down on the actual number of pages.
For example, there is a page that displays a list of graphic designs she has made. The JSON text is processed when the page loads. When one of the graphic design links are clicked, a javascript function modifies the html on the page to display the new picture/title/description.

An example of JSON and the eval() function:

var pageInformation = '{"collection":[
{"filename":"butterflyanimation.gif",
"title":"Butterfly GIF",
"description":"An animated butterfly made in ImageReady and Illustrator"},
{"filename":"butterflypana.jpg",
"title":"Express Colors",
"description":"Express Inspiration for Spring 2005 Colors."}]}';

// create an object from the JSON formatted data
var objItems = eval('(' + pageInformation ')');

If this code were in a script tag, what would happen? The variable objItems would store all of that data in pageInformation as a javascript object. That means we can now access the data like: objItems.collection[0].title, which would be "Butterfly GIF".

To change an element in a webpage, make sure it has its "id" property set. after that use the javascript: document.getElementById('id_name').innerHTML = 'whatever';