Stephen Groom Music Producer? Poker Pro? Sports Bettor? Tune in next post to find out

6Jul/080

JAVASCRIPT: Load a page using AJAX

I just noticed that I use one little AJAX function to load all of my pages but haven't took the time to explain to my readers how I do it yet, so here goes :) .

To use this create a HTML file with the following code and upload it to your web server..

[i]ajax.html[/i]
[code]
<html>
<head>
<script type="text/javascript" src="ajax.js"></script>
</head>

<body>
<p>
<a href="nonjs.html" onclick="get('content.txt', 'content');return false;">Click here to load our content using ajax</a>
</p>

<div id="content">
<p>
Our content.txt file will be loaded here when the link above is pressed.
</p>
</div>

</body>
</html>
[/code]

Now, the html file shows us a page with the text [i]Click here to load our content using ajax[/i]. When this text is clicked it makes a call to the function get() which is defined in the next file.. ajax.js

[i]ajax.js[/i]
[code]
function createhandler(){
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
return xmlhttp;
}
function get(url, divid){ //Url to fetch + div ID to insert content into
var xmlhttp=createhandler();
xmlhttp.onreadystatechange=function (){
if(xmlhttp.readyState==4){
document.getElementById(divid).innerHTML=xmlhttp.responseText;
xmlhttp.onreadystatechange = null;
xmlhttp.abort();
}
};
xmlhttp.open('GET', url, true);
xmlhttp.send(null);
}
[/code]
This file defines the functions [i]get[/i] and [i]createhandler[/i]. The createhandler function is used to create our AJAX xmlhttp object used to send and receive data via ajax.

The [b]get()[/b] function takes the parameters [i]url[/i] and [i]divid[/i]. Then createhandler is called to make the xmlhttp object.

The code that begins [i]xmlhttp.onreadystatechange=function (){ [/i] is used to capture the onreadystatechange event and when readystate changes to 4 (READY) our divid is updated with the text taken from the url we specified.

The lines [i]xmlhttp.open('GET', url, true);xmlhttp.send(null);[/i] send a HTTP GET request to the url we specified. The true paramater means that data can be sent and received asynchronously and does not concern us here.. Just be sure it's true :) . We send null data to terminate the command.

Next all you need to do is create a content.txt file with some html code in it to be loaded. Here is an example:
[i]content.txt[/i]
[code]
<p>I have just been loaded with ajax using the function get(url, divID)</p>
[/code]

To use the example above, upload all of the files into the same directory on your webserver. I hope this gives you some insight on the basics of AJAX and how to load pages. If you have any questions please comment this blog :)

Love
Stephen

Share
Filed under: Tutorials No Comments
1Jun/080

JAVASCRIPT: Custom right-click menu

Many of you may have already noticed that there is no text link to my Admin panel. That is because it is cleverly hidden. If you right click anywhere on this page in most modern browsers, you will be greeted by my admin logon in your cursors location :) .

You could use this for whatever purpose you want, here I will just show you how I did it personally.

Firstly, the code for the "hidden" menu is always loaded with every page in this website. It sits inside a little div tag which is hidden with css.

Here is how this div should look when I remove all my content::

[code]
<div id="adminpop" style="display:none">
<div onclick="this.parentNode.style.display='none'">x</div>
</div>
[/code]

The declaration [i]style="display:none"[/i] ensures that everything inside the div is hidden from view when the page is rendered. The next div is shows an X in the hidden window which when clicked will hide it again.

[b]Now for the Javascript[/b]

[code]
document.oncontextmenu=function(ev)
{
var ev=ev || window.event;
var pop=document.getElementById('adminpop');
var x,y

if (document.all) //IE Workaround
{
if(ev.srcElement.tagName.toLowerCase()=="input" || ev.srcElement.tagName.toLowerCase()=="textarea")
return;
x=ev.clientX + document.body.scrollLeft;
y=ev.clientY + document.body.scrollTop;
}
else
{
if(ev.target.tagName.toLowerCase()=="input" || ev.target.tagName.toLowerCase()=="textarea")
return;
x=ev.pageX;
y=ev.pageY;
}
pop.style.left=x+"px";
pop.style.top=y+"px";
pop.style.display="block";
return false;
};
[/code]

This code should be pretty self-explanatory but I will now explain it bit by bit.

The first line defines our function to be called everytime the "context menu" is opened (This is the right-click menu). After this we define our variables, the one that concerns us most is [b]pop[/b] which must have the same ID set as your hidden div. [b]ev[/b] is used to capture the mouse location and [b]x + y[/b] will be used to store the information.

There is an if conditional which is used for cross-browser compatibility. They both contain code that gets and sets the X and Y coordinates of the mouse cursor when the right mouse button is clicked. They also both contain the following:
[code]
if(ev.srcElement.tagName.toLowerCase()=="input" || ev.srcElement.tagName.toLowerCase()=="textarea")
return;
[/code]
This is optional and allows the right-click menu to still appear as normal on form elements that require typing. I did this to allow selection and copy-pasting to occur as normal.

After this the last 4 lines set the coordinates, set the display CSS property to "block" and then [i]return:false[/i] to cancel the standard right click menu.

I hope this was a useful tutorial. Please ask away in the comments if you have any problems.
Thanks
Stephen

Share
Filed under: Tutorials No Comments
12May/085

JAVASCRIPT: Add BBCode buttons to a form

[i]There is a follow-up tutorial to this available [url=http://www.groomi.net/JAVASCRIPT:_Add_BBCode_buttons_to_a_form_(REVISITED)-,46]here[/url] which further improves the script adding another feature which improves ease and convenience of use.[/i]

Having just completed my code for buttons to insert BBCode into a textarea, I thought it was time to share my code with the world wide web.

First I will show you the HTML code I use at the time of this post

[code]<input type="button" onclick="bbcode_ins('comment', 'b')" value="B" style="width:15px;font-weight:bold;" />
<input type="button" onclick="bbcode_ins('comment', 'u')" value="_" style="width:15px;" />
<input type="button" onclick="bbcode_ins('comment', 'i')" value="I" style="width:15px;font-style:italic;" />
<input type="button" onclick="bbcode_ins('comment', 'img')" value="img" style="width:25px;" />
<input type="button" onclick="bbcode_ins('comment', 'url')" value="url" style="width:25px;" />
<input type="button" onclick="bbcode_ins('comment', 'php')" value="php" style="width:25px;" />
<input type="button" onclick="bbcode_ins('comment', 'code')" value="code" style="width:30px;" />[/code]

This basically puts a button for each available BBCode tag into the form where the textarea is located. The textarea in this example is called comment and when you click the button associated with the tag the following javascript function is called:

[i]bbcode_ins([b]field[/b], [b]tag[/b]);[/i]

Here is the javascript associated with the [i]bbcode_ins()[/i] function

[code]function bbcode_ins(fieldId, tag)
{
field=document.getElementById(fieldId);
if(tag=='b' || tag=='i' || tag=='u' || tag == 'php' || tag == 'code')
{
if (document.selection)
{
field.focus();
sel = document.selection.createRange();
sel.text = '[' + tag + '][/' + tag+']';
}
//MOZILLA/NETSCAPE/SAFARI support
else if (field.selectionStart || field.selectionStart == 0)
{
var startPos = field.selectionStart;
var endPos = field.selectionEnd;
field.focus();
field.value = field.value.substring(0, startPos)
+ '[' + tag + '][/' + tag+']'
+ field.value.substring(endPos, field.value.length);
}
}
else if(tag == 'img')
{
var path = prompt('Enter image path', 'http://');
if(!path)
{
return;
}
if (document.selection)
{
field.focus();
sel = document.selection.createRange();
sel.text = '[' + tag + ']' + path + '[/' + tag+']';
}
//MOZILLA/NETSCAPE/SAFARI support
else if (field.selectionStart || field.selectionStart == 0)
{
var startPos = field.selectionStart;
var endPos = field.selectionEnd;
field.focus();
field.value = field.value.substring(0, startPos)
+ '[' + tag + ']' + path + '[/' + tag+']'
+ field.value.substring(endPos, field.value.length);
}
}
else if(tag == 'url')
{
var url = prompt('Enter link URL', 'http://');
var linkText = prompt('Enter link text', '');
if(!url || !linkText)
{
return;
}
if (document.selection)
{
field.focus();
sel = document.selection.createRange();
sel.text = '[' + tag + '='+url+']' + linkText + '[/' + tag+']';
}
//MOZILLA/NETSCAPE/SAFARI support
else if (field.selectionStart || field.selectionStart == 0)
{
var startPos = field.selectionStart;
var endPos = field.selectionEnd;
field.focus();
field.value = field.value.substring(0, startPos)
+ '[' + tag + '='+url+']' + linkText + '[/' + tag+']'
+ field.value.substring(endPos, field.value.length);
}
}
}[/code]

[b]Now to explain the code:[/b]

[i]field=document.getElementById(fieldId);[/i]
This sets the variable [i]field[/i] to the element to be inserted into. eg. <input id="fieldId" />

The second parameter tag is tested to ask a variety of different questions depending on whether it is a hyperlink, image or simple bbcode tag. The important code is inside the if statements.

The first if inside of these is for IE browsers only. The line [i]if (document.selection)[/i] will only evaluate true if the code is executed in internet explorer. The next few lines of code then add the bbcode and give focus to the field.

The next alternative is with [i]else if (field.selectionStart || field.selectionStart == 0)[/i] and this evaluates to true for firefox/mozilla/safari etc etc. Inside this statement is another method of performing the same task for browsers that don't support the IE method.

[b]In summary[/b]
There it is, the code that makes my wonderful bbcode buttons work. Hope it can be of some use to somebody. If you have any questions/suggestions regarding this post please direct them to the comments

Thanks :)
Stephen
x

Share
Filed under: Tutorials 5 Comments