if ($('#myDiv').length) $('#myDiv').show();
Source:
http://docs.jquery.com/Frequently_Asked_Questions#How_do_I_test_whether_an_element_exists.3F
if ($('#myDiv').length) $('#myDiv').show();
Source:
http://docs.jquery.com/Frequently_Asked_Questions#How_do_I_test_whether_an_element_exists.3F
Here is how to do this:
var offset = $('#OBJECT-ID').offset().top; $('html,body').animate({ scrollTop: offset }, 500);
We are closing down our forums, it’s time to move on, but we are keeping some important threads, here are the AJAX tutorials…
What you need to know before you read this tutorial:
You need to read the previous two tutorials, they are located at here:
Beginner Ajax Tutorial
Beginner AJAX Tutorial – Display a Progress Bar or a Loading Message
(It will only takes a few minutes and will catch you up to this point.)
We are going to make a simple AJAX website with 4 pages.
A few things to note:
1. We are going to make a website that works just fine for users without JavaScript.
2. The back-end will be PHP, it might not be the best way to implement but it’s simple and effective for the purpose of this tutorial.
3. You will be able to download the complete source code for this AJAX tutorial.
4. In this AJAX tutorial the browser back button is ‘broken’, and users can’t bookmark internal pages of this website; fixing these issue is the topic of the next tutorial.
5. In this tutorial I’m going to demonstrate what can be done with AJAX in a simple way using inline JavaScript; separating presentation and behavior will be the topic of later tutorials.
Inline JavaScript looks like this:
<a href="?page=about" onClick="return get_page('about');">About us</a>Let’s start with the back-end
Here is the directory structure of this website:
/index.php
/templates/main.php
/templates/home.php
/templates/about.php
/templates/services.php
/templates/contact.php
/images/few images
/yui/our yui code libraries
Here is the index.php source code:
<?php $templates_folder = 'templates/'; if( !isset($_GET['page']) ) { $_GET['page'] = 'home'; } /** * Because we are going to get the content of a file based on user input and display it * to the user, we use basename function to make sure a sneaky user doesn't try * something like ../../ to get a password file or something important. **/ $page = trim(basename($_GET['page'])) .'.php'; $page_file = $templates_folder .$page; /** * Note: This assumes your templates are static, that is: there is no PHP code * in them, I will write about how to handle that situation later but for now, * let's keep it simple :) **/ if( file_exists($page_file) ) { $page_content = file_get_contents($page_file); } else { $page_content = 'This page doesn\'t exist here.'; } /** * If the $_GET['AJAX'] is set, then the request is coming from our JavaScript * get_page() function, so we just send the $page_content to the browser. **/ if( isset($_GET['AJAX']) ) { echo $page_content; } else { include $templates_folder .'main.php'; } ?>
What it does is straightforward and you can understand the code just by reading it.
But here is how it works:
1. It checks the contents of the $_GET['page'] variable for the name of the page a visitors wants to visit and assigns it to $page.
$page = trim(basename($_GET['page'])) .'.php'; $page_file = $templates_folder .$page;
$page_file now contains the exact path to our template.
Also note that, this part of the code:
if( !isset($_GET['page']) ) { $_GET['page'] = 'home'; }
Makes sure that the home page is the default page, and if $_GET['page'] is empty it assigns ‘home’ to it.
2. It checks if the page exists in the templates folder.
if( file_exists($page_file) ) { $page_content = file_get_contents($page_file); } else { $page_content = 'This page doesn\'t exist here.'; }
If it exists then it assigns it’s content to $page_content variable if not an error message that this page does not exist.
3. It checks the content of $_GET['AJAX'] variable and if its set, the request is coming from our JavaScript code:
if( isset($_GET['AJAX']) ) { echo $page_content; } else { include $templates_folder .'main.php'; }
If it is coming from our JavaScript code then it only prints out the content of the page, but if not, it prints the main.php template.
Main.php source code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Sample AJAX-XHR Website</title> </head> <body> <?php echo $page_content; ?> </body> </html>
This is the main.php in it’s simplest format, I omitted the JavaScript.
What it does is just printing the $page_content variable in the page.
Other templates:
They only contain plain HTML code, you will see everything together soon.
The front end
All the JavaScript code goes into main.php, here is the JavaScript code we had so far in the previous tutorial:
<script type="text/javascript" src="yahoo.js"> </script>
<script type="text/javascript" src="event.js"> </script>
<script type="text/javascript" src="connection.js"> </script>
<script type="text/javascript">
function success_handler(o) {
replace_html('content', o.responseText);
}
function failure_handler(o) {
replace_html('content', 'Server or your connection is death');
}
function replace_html(id, content) {
document.getElementById(id).innerHTML = content;
}
function show_progressbar(id) {
replace_html(id, '<img src="http://images.code-head.com/progress-bars/4.gif" border="0" alt="Loading, please wait..." />');
}
function send_request() {
show_progressbar('content');
var callback = { success:success_handler, failure:failure_handler, timeout: 10000 };
YAHOO.util.Connect.asyncRequest('GET', 'http://images.code-head.com/tutorials/ajax/beginner-ajax-tutorial.php', callback);
}
function test_failure() {
show_progressbar('content');
var callback = { success:success_handler, failure:failure_handler, timeout: 10000 };
YAHOO.util.Connect.asyncRequest('GET', 'http://images.code-head.com/tutorials/ajax/some-file-that-doesnt-exists.php', callback);
}
var progress_bar = new Image();
progress_bar.src = 'http://images.code-head.com/progress-bars/4.gif';
</script>The code we use for this tutorial is similar, we will only replace send_request() and test_failure() with one function, get_page():
<script type="text/javascript" src="yui/yahoo.js"> </script>
<script type="text/javascript" src="yui/event.js"> </script>
<script type="text/javascript" src="yui/connection.js"> </script>
<script type="text/javascript">
function replace_html(id, content) {
document.getElementById(id).innerHTML = content;
}
function show_progressbar(id) {
replace_html(id, '<img src="http://images.code-head.com/progress-bars/4.gif" border="0" alt="Loading, please wait..." />');
}
function success_handler(o) {
replace_html('content', o.responseText);
}
function failure_handler(o) {
replace_html('content', 'Server or your connection is death.');
}
function get_page(page) {
if( page == '' ) {
/* Do nothing if 'page' is empty, you might want to show some error message. */
return false;
}
show_progressbar('content'); /* Show progress bar while waiting */
var callback = { success:success_handler, failure:failure_handler, timeout: 10000 };
YAHOO.util.Connect.asyncRequest('GET', 'index.php?AJAX=true&page=' + page, callback);
return false;
/**
* return false!
* Because this will prevent the browser from navigating to page specified in
* the link's href attribute.
**/
}
/* Let's preload our progress bar */
var progress_bar = new Image();
progress_bar.src = 'http://images.code-head.com/progress-bars/4.gif';
</script>get_page() function is very simple, here is what it does:
1. It receives the page name as an argument.
function get_page(page) { // ... }
2. It check if the page variable is empty.
if( page == '' ) { return false; }
Here, this function does nothing if page variable is empty, you might want to show an error message.
3. It shows the progress bar before sending the request to the server, letting the user know that something is actually happening:
show_progressbar('content');
4. It sends the request to server and sets our success_handler and failure_handler as callbacks:
var callback = { success:success_handler, failure:failure_handler, timeout: 10000 }; YAHOO.util.Connect.asyncRequest('GET', 'index.php?AJAX=true&page=' + page, callback);
Note: We are sending a request to:
'index.php?AJAX=true&page=' + page
We set the AJAX variable to true and we set the page variable to the page variable that passed to the function. (It can be ‘about’, ’services’, etc.)
5. It returns false. Return false will result in any link that uses this function to appear as not working, that is, the browser won’t try to navigate
to the page specified in the links href attribute. Instead of letting the browser navigate to that page we replace the content of the page with JavaScript.
main.php with the JavaScript and a menu:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Sample AJAX-XHR Website</title>
<!-- Usual yui stuff -->
<script type="text/javascript" src="yui/yahoo.js"> </script>
<script type="text/javascript" src="yui/event.js"> </script>
<script type="text/javascript" src="yui/connection.js"> </script>
<script type="text/javascript">
function replace_html(id, content) {
document.getElementById(id).innerHTML = content;
}
function show_progressbar(id) {
replace_html(id, '<img src="http://images.code-head.com/progress-bars/4.gif" border="0" alt="Loading, please wait..." />');
}
function success_handler(o) {
replace_html('content', o.responseText);
}
function failure_handler(o) {
replace_html('content', 'Server or your connection is death.');
}
function get_page(page) {
if( page == '' ) {
/* Do nothing if 'page' is empty, you might want to show some error message. */
return false;
}
show_progressbar('content'); /* Show progress bar while waiting */
var callback = { success:success_handler, failure:failure_handler, timeout: 10000 };
YAHOO.util.Connect.asyncRequest('GET', 'index.php?AJAX=true&page=' + page, callback);
return false;
/**
* return false?!
* Because this will prevent the browser to navigate to page specified in
* the link's href attribute.
**/
}
/* Let's preload our progress bar */
var progress_bar = new Image();
progress_bar.src = 'http://images.code-head.com/progress-bars/4.gif';
</script>
</head>
<body>
<div id="main-wrapper">
<div id="main-padding">
<h1>Sample AJAX-XHR Website</h1>
<div id="menu">
<a href="?page=about" onClick="return get_page('about');">About us</a>
<a href="?page=services" onClick="return get_page('services');">Our services</a>
<a href="?page=contact" onClick="return get_page('contact');">Contact us</a>
<a href="?page=home" onClick="return get_page('home');">Home</a>
</div>
<div id="content">
<?php echo $page_content; ?>
</div>
</div>
</div>
</body>
</html>2 notes:
1. Menu links are like:
<a href="?page=about" onClick="return get_page('about');">About us</a>Their href attribute is actually pointing to the right page, so users without JavaScript will be able to navigate through these pages, and search engines will have
no problem indexing these pages as well.
2. On the other hand their onClick event is set to call get_page() function and passes the page name as the argument to the get_page().
Here is how it works all together:
http://images.code-head.com/tutorials/ajax/sample-AJAX-XHR-website/
Please note: Ignore the look of this example, the point is the functionality.
You can try turning off your JavaScript and see that the example site still works just fine without it.
Download the complete source code here if you want to take a closer look at everything:
http://images.code-head.com/tutorials/ajax/sample-AJAX-XHR-website/sample-AJAX-XHR-website.zip
If you have questions or suggestions, feel free to reply to this thread.
-Codehead
Update:
I should mention that it’s a long time that I moved on to use jQuery rather than yui and I think jQuery is much nicer and easier to use library. I will hopefully write some tutrials on jQuery.
If you don’t know jQuery yet, download it here and HAVE FUN FOREVER!
Download jQuery
markItUp is a cool little text editor and the nice thing about it is that it’s very simple and light weight.
I had some layout issues in Gecko and Webkit browsers and the way to fix it is this:
1 – Go to:
/markitup/skins/markitup
2 – Open style.css and find:
.markItUpEditor { font:12px 'Courier New', Courier, monospace; padding:5px 5px 5px 35px; border:3px solid #3C769D; width:643px; height:320px; background-image:url(images/bg-editor.png); background-repeat:no-repeat; clear:both; display:block; line-height:18px; overflow:auto; }
3 – Replace the it it with:
.markItUpEditor { font:12px 'Courier New', Courier, monospace; padding:5px; border:1px solid #AAAAAA; width: 275px; height: 150px; line-height:18px; overflow:auto; }
I hope this helps someone…
I know I haven’t posted anything lately, I have been busy which is a good thing but I couldn’t resist this one, here is a simple news ticker using JavaScript and the great jQuery library.
Here is the example:
http://images.code-head.com/code/javascript/jquery-news-ticker.html
I know you might be able to write this using objects in a nicer form but this will work and it’s to demonstrate the idea…
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jQuery New Ticker</title>
<script type="text/javascript" src="http://images.code-head.com/jquery/jquery.js"> </script>
<script type="text/javascript">
$(document).ready(function() {
var current = -1;
var elems = new Array();
var elems_i = 0;
$('.items').each(function() {
elems[elems_i++] = $(this);
});
var num_elems = elems_i - 1;
var animate_out = function() {
elems[current].animate({ top: '-100px' }, 'fast', 'linear', animate_in);
}
var animate_out_delay = function() {
setTimeout(animate_out, 1000); /****************************** Change 1000 to make it longer/shorter/whatever */
}
var animate_in = function() {
current = current < num_elems ? current + 1 : 0;
elems[current].css('top', '200px').animate({ top: '0px' }, 'fast', 'linear', animate_out_delay);
}
animate_in();
});
</script>
<style type="text/css">
.ticker {
position: relative; /* So we can absolute the .items */
width: 400px;
height: 100px;
overflow: hidden;
margin: 100px;
border: 1px dashed #666666;
}
.items {
position: absolute;
top: 200px;
margin: 10px;
}
</style>
</head>
<body>
<div class="ticker">
<div class="items">I'm a Cool</div>
<div class="items">JavaScript</div>
<div class="items">News Ticker</div>
<div class="items">Using jQuery</div>
<div class="items">For Smooth</div>
<div class="items">And Nice</div>
<div class="items">Animation</div>
<div class="items">By Hamid Alipour</div>
<div class="items">@ <a href="http://blog.code-head.com" target="_blank">blog.code-head.com</a></div>
</div>
</body>
</html>Again, the code is straight forward, you must be able to understand what happens but here is a little explanation.
<div class=”items”> … </div> are the news headlines to be animated and using CSS, they are absolute-positioned somewhere under the parent <div class=”ticker”> … </div> box.
Normally, .itmes would be visible under the box, even when they are absolute-positioned but if you look into the stylesheet you will see:
.ticker { ... width: 400px; height: 100px; overflow: hidden; ... }
That will prevent this from hapenning, so now our .items are floating somewhere under the box which is what we want. (Change it’s ‘width’ and ‘height’ to fit in whatever space you want…)
The JavaScript code starts with the first one and animates it all the way to the top and then pauses for a second (you can change it to whatever time you want), then it animates the one on the top to the top of the box by animating it all the way to ‘top: -100px;’, note that the same ‘overflow: hidden;’ prevents it from showing.
It then picks up the next item, sets it’s top to 200px and animates it all the way to the top again and then repeat forever.
You might ask why it’s first setting the .items top to 200px; it’s because we are animating them to top of the box so we have to set their top to 200px again each time (we did this first in CSS), this is not important in the first iteration but after that every single item is on top of the box and has to be moved under the box.
I hope this makes sense.
I was searching the web yesterday for this and didn’t really find a simple way of doing this and suddenly, I remembered something.
It’s extremely simple, someone could build on it with all sorts of features but for now, here is an example:
http://images.code-head.com/code/javascript/js-threads.html
As you can see there are two counters, one is counting up and the other down simultaneously.
Here is the start_thread function:
function thread_start(callback) { setTimeout(callback, 1); return true; }
The trick is that setTimeout *does not* block the execution
I hope this helps someone
Funny, I would imagine that they have developed an in house JavaScript library by now but this is great, using a well maintained and good library is a great programming practice.
You can check it out here:
http://www.google.com/ig
(Right click and view the source)
Yes, I have to see the source code for everything I can find
I personally can’t imagine living without jQuery, I used yui for a long time but jQuery is a beautiful piece of engineering.
yui is still great and has so many components but it’s not my type, I’m lazy