Posts

Home Lists+

I’m Making Some Simple But Useful Online Tools for Developers

Hey guys! How are you? Today I’m sharing these three simple but useful (well, at least for me) online tools for developers like you.

I developed it using Bootstrap to have a decent user interface, .htaccess for clean URL location, PHP for input processing and of course, jQuery AJAX requests to prevent reloading the whole page get what you want faster. It’s really fun to built knowing that other developers might find it useful too.

simple online tools for developers

For now we only have three tools, but I’m planning to make more. But first, let’s take a look!

Read more

Home Android

Saying Goodbye to Google Blogger

Hey guys! How are you? I’m so happy today. I’m almost done re-creating this website. Why? I switched from Blogger to WordPress! Yes, you read it right.

I love WordPress!

Read more

Home jQuery

jQuery UI Autocomplete Example

We, the developers, want to help our users search for the data they are looking for – in an easy manner. This jQuery UI autocomplete tutorial will help you achieve it!

Having an autocomplete feature in our search box is really good for the user experience, it is like having a user assistant while he is trying to search.

Our code for today will make use of a textbox where the user can type his search term. The sample data we use are person names (firstname and lastname).

So, when the user types a name, our program will suggest some names that might be what the user is looking for.

Contents:

1.0 Project Files
2.0 Database
3.0 The User Interface
4.0 Getting Search Results
4.1 JSON Data
5.0 Adding Some Style
6.0 Download Source Code

1.0 Project Files

Our code for today includes the following files:

libs/db_connect.php
images/ajax-loader.gif
css/style.css
index.php
results.php

2.0 Database

The table structure used and some sample data were provided below:

--
-- Table structure for table `users`
--

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `firstname` varchar(32) NOT NULL,
  `lastname` varchar(32) NOT NULL,
  `gender` varchar(6) NOT NULL,
  `email` varchar(32) NOT NULL,
  `username` varchar(32) NOT NULL,
  `password` varchar(32) NOT NULL,
  `created` datetime NOT NULL,
  `modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=76 ;

--
-- Dumping data for table `users`
--

INSERT INTO `users` (`id`, `firstname`, `lastname`, `gender`, `email`, `username`, `password`, `created`, `modified`) VALUES
(49, 'Justine', 'Bongola', 'Male', 'justine@coanmail.com', 'jaja', 'jaja123', '0000-00-00 00:00:00', '2013-03-03 14:06:03'),
(51, 'Lourd', 'De Veyra', 'Male', 'lourd@coanmail.com', 'lourd', 'lourd123', '0000-00-00 00:00:00', '2013-03-03 14:06:03'),
(73, 'Mike', 'Dalisay', '', '', 'ninjazhai', 'allisfine', '0000-00-00 00:00:00', '2013-05-12 06:39:04'),
(74, 'Darwin', 'Dalisay', '', '', 'dada', 'dada123', '0000-00-00 00:00:00', '2013-05-12 06:39:24'),
(75, 'Marykris', 'Dalisay', '', '', 'mary143', 'mary123', '0000-00-00 00:00:00', '2013-05-13 16:51:14');

Here’s how we connect to the database, just change the variable values that will make you connected to your database.

<?php
$host = "yourHost";
$db_name = "yourDatabaseName";
$username = "yourDatabaseUsername";
$password = "yourPassword";

try {
    $con = new PDO("mysql:host={$host};dbname={$db_name}", $username, $password);
}catch(PDOException $exception){ //to handle connection error
    echo "Connection error: " . $exception->getMessage();
}
?>

3.0 The User Interface

index.php – this is where the user can find the textbox, tries to type on it and our system suggests some keywords as autocomplete, and this is also where we include our jQuery UI theme and jQuery scripts.

<!DOCTYPE HTML>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>jQuery UI auto-complete tutorial live demo</title>

		<!-- include the jquery ui theme css and your own css -->
		<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.0/themes/smoothness/jquery-ui.css" />
		<link rel="stylesheet" href="css/style.css" />

    </head>
<body>

<!--
	-this is our text box, we didn't use type='text' but type='search' instead
	 to have a clear (x) function in case a user wants to easily remove what's in the textbox
	-placeholder='Search firstname or lastname' - is an HTML5 attribute the can give your
	 users a clue on what to search or type in the textbox
-->
<div>Try to type "dalisay" below:</div>
<input type='search' id='nameSearch' placeholder='Search firstname or lastname' />

<!--
	-now we'll include the jQuery and jQuery UI libraries
-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.0/jquery-ui.min.js"></script>

<script type="text/javascript">
$(document).ready(function(){

	// this is how to add autocomplete functionality in a textbox
	// source:'results.php' - where it will pass the search term and generates the JSON data
	// minLength:1 - how many characters user enters in order to start search
	$('#nameSearch').autocomplete({

		source:'results.php',
		minLength:1,
		select: function(event, ui){

			// just in case you want to see the ID
			var accountVal = ui.item.value;
			console.log(accountVal);

			// now set the label in the textbox
			var accountText = ui.item.label;
			$('#nameSearch').val(accountText);

			return false;
		},
		focus: function( event, ui ) {
			// this is to prevent showing an ID in the textbox instead of name
			// when the user tries to select using the up/down arrow of his keyboard
			$( "#nameSearch" ).val( ui.item.label );
			return false;
		},

   });

});
</script>

</body>
</html>

4.0 Getting Search Results

results.php – this is where the search term were passed, queries the database and generates the JSON data needed to show the autocomplete terms in the user interface.

<?php
// connect to the database
include "libs/db_connect.php";

// get the search term
$search_term = isset($_REQUEST['term']) ? $_REQUEST['term'] : "";

// write your query to search for data
$query = "SELECT 
            id, firstname, lastname 
        FROM 
            users 
        WHERE 
            firstname LIKE "%{$search_term}%" OR 
            lastname LIKE "%{$search_term}%" 
        LIMIT 0,10";

$stmt = $con->prepare( $query );
$stmt->execute();

// get the number of records returned
$num = $stmt->rowCount();

if($num>0){ 

    // this array will become JSON later
    $data = array();

    // loop through the returned data
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
        extract($row);

        $data[] = array(
            'label' => $firstname . " " . $lastname,
            'value' => $id
        );
    }

    // convert the array to JSON
    echo json_encode($data);

}

//if no records found, display nothing
else{
    die();
}
?>

4.1 Wondering how the returned JSON data looks like?

[
  {
    "label": "Mike Dalisay",
    "value": "28"
  },
  {
    "label": "Darwin Dalisay",
    "value": "40"
  }
]

You can also take a look at your own JSON data by browsing your results.php?term=your_search_term

5.0 Adding Some Styles

style.css – this is where you can change the loading GIF image and add some style to our textbox.

.ui-autocomplete-loading {
    /* you can replace ajax-loader.gif with another gif image you want for your design */
    background: white url('images/ajax-loader.gif') right center no-repeat;
}

/* some style for our textbox */
#nameSearch{
    padding:.5em;
    width:20em;
}

6.0 Download Source Code

You can download all the code used in this tutorial for only $9.99 $5.55!

THANK YOU!

has been added to your cart!

Powered by Easy Digital Downloads

Thank you!

have been added to your cart!

Powered by Easy Digital Downloads

Congratulations! Now you can make your users happier by this search assistant feature, and as always, thanks for reading!

Home jQuery

Google said “The web should be fast”: How to Optimize Your Website for Speed

Hey guys! Today we have a guest post about some tips on how to speed up your website! He’s currently working for an e-commerce website and one of his tasks is to make the site load fast. So enjoy reading below! ~ Mike
Website speed becomes an obsession of search engines like Google and one of the reasons is the rapid growth of mobile internet browsing. If you’re working with the https://www.igloosoftware.com/product/integrations/org_chart_now/ (developers, designers, bloggers and students), it is now a requirement to have knowledge in making a website load fast, and our post for today will give you some ideas on why and how to achieve it.

jQuery Tutorial for Beginners – Step By Step Guide!

jquery-step-by-step-tutorial-for-beginners

Previously, we learned how to use Bootstrap to make our web applications look good. This time, we will learn how to use jQuery.

Many of you asked me how to use jQuery. This tutorial is my answer to you. I want to give you links but I feel like it’s easier to teach someone about something that is your own version of work! We hope you guys will find this step by step guide useful.

Contents of this tutorial include:
1.0 Getting Started with jQuery
2.0 Run jQuery in 5 Easy Steps
3.0 Download Source Code
4.0 jQuery Basic Concepts
5.0 Online Resources
6.0 What’s Next?
7.0 Related Tutorials
8.0 Some Notes

1.0 Getting Started with jQuery

1.1 What is jQuery? Okay here’s the simplest definition I can give. jQuery is a JavaScript library. It can:

  1. Make your JavaScript code shorter, faster and cross browser.
  2. Manipulate your HTML, like showing or hiding something from the page.
  3. Handles events – it can do something when a user click a button or any other activity a user can do with a mouse.
  4. Animation – for example make a part of your page fade in, fade out or just simply make something move.
  5. AJAX – do a server request without refreshing your whole web page.

1.2 This post. I assume you already know basic HTML, CSS and JavaScript. In this post, aside from the simple definition of jQuery above, we are just going to have two parts:

  1. The super straightforward, step by step tutorial or guide in running a very basic jQuery script. (2.0)
  2. We are going to take a look more of the jQuery basic concepts, as shown in #1 (3.0)

2.0 Run jQuery in 5 Easy Steps

2.1 Follow the steps below – these steps will lead you to run a very basic jQuery script that does a slide and toggle.

Step 1: Create HTML page with its basic structure.

<!-- step 1 -->
<!DOCTYPE html>
<html>
<head>
    <title>jQuery Tutorial for Beginners Live Demo</title>
</head>
<body>

</body>
</html>

Step 2: Add element to be clicked. We’re gonna have a button in this example, we added an ID name to this button called myButton. Add the following code inside the “body” tag.

<!-- step 2 -->
<button id='myButton'>Click to Slide or Toggle</button>

Step 3: Add the element to be shown or hidden. We’re gonna have a “p” tag with bunch of sample words inside. Add the following code below step 2′s code.

<!-- step 3 -->
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero. Sed cursus ante dapibus diam. Sed nisi. Nulla quis sem at nibh elementum imperdiet. Duis sagittis ipsum. Praesent mauris. Fusce nec tellus sed augue semper porta. Mauris massa. Vestibulum lacinia arcu eget nulla. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Curabitur sodales ligula in libero. Sed dignissim lacinia nunc. Curabitur tortor. Pellentesque nibh. Aenean quam. In scelerisque sem at dolor. Maecenas mattis. Sed convallis tristique sem. Proin ut ligula vel nunc egestas porttitor. Morbi lectus risus, iaculis vel, suscipit quis, luctus non, massa. Fusce ac turpis quis ligula lacinia aliquet. Mauris ipsum. Nulla metus metus, ullamcorper vel, tincidunt sed, euismod in, nibh. Quisque volutpat condimentum velit. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nam nec ante. Sed lacinia, urna non tincidunt mattis, tortor neque adipiscing diam, a cursus ipsum ante quis turpis. Nulla facilisi. Ut fringilla. Suspendisse potenti. Nunc feugiat mi a tellus consequat imperdiet. Vestibulum sapien. Proin quam. Etiam ultrices. Suspendisse in justo eu magna luctus suscipit. Sed lectus. Integer euismod lacus luctus magna. Quisque cursus, metus vitae pharetra auctor, sem massa mattis sem, at interdum magna augue eget diam. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Morbi lacinia molestie dui. Praesent blandit dolor. Sed non quam. In vel mi sit amet augue congue elementum. Morbi in ipsum sit amet pede facilisis laoreet. Donec lacus nunc, viverra nec.
</p>

Step 4: Add the jQuery library. Aren’t you excited? You can also download your own copy of jQuery but in today’s example, we’ll be linking to Google’s copy of jQuery. Add the following code below step 3′s code.

<!-- step 4 -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>

Step 5: Add jQuery script. This script will show or hide the “p” tag and the words inside it. Notice that we selected the button by referencing our button’s ID myButton.

<!-- step 5 -->
<script>
$("#myButton").click(function () {
    $("p").slideToggle("slow");
});
</script>

3.0 Download Source Codes

You can download all the code used in this tutorial for only $9.99 $5.55!

THANK YOU!

has been added to your cart!

Powered by Easy Digital Downloads

Thank you!

have been added to your cart!

Powered by Easy Digital Downloads

Congratulations! You are now a jQuery coder! Just kidding. Not yet. But don’t lose hope!

To achieve being a real jQuery coder, like any other skill, it must be practiced and be well versed with its concepts. So continue to read below and make your jQuery wisdom a little bit better.

4.0 jQuery Basic Concepts

4.1 Run jQuery when DOM is ready. We didn’t implement this in our example above because I want to give you a quick look on how to run a jQuery script and it is a very small web page anyway.

But in reality, if you use jQuery in larger web pages, you have to run it when the DOM is ready. Here’s how:

$(document).ready(function() {
    // jQuery will run once everthing else in your web page is already loaded.
    // All your jQuery codes here.
});

4.2 How to Select an Element in jQuery? Learning jQuery selectors are very important because you’re dealing with HTML elements within your web page.

I’m gonna give you some of the most basic selectors being used:

// selects 'only one' HTML element with ID "myButton", such as our example above
// notice that we use hashes (#) for ids, like that of CSS
$("#myButton");

// selects all HTML elements with class "myClass", for instance: <div class='myClass'></div>
// notice that we used dots (.) for classes, like that of CSS
$(".myClass");

// selects all button HTML element, for example: <button>Click Me!</button>
$("button");

// selects all div element, example: <div>Me and all other div will be selected!</div>
$("div");

// selects all anchor link element, for example: <a href="https://codeofaninja.com/">Me and all other 'a' tags will be selected!</a>
$("a");

Learn more jQuery Selectors

4.3 jQuery Events. In our example above (2.0), we use a click event, in jQuery it was represented by the click() method. Here are some more jQuery events that you might find useful:

$("button").click(function(){
    // do something when user click the button
});

$("form").submit(function(){
    // do something when user submits a form
});

$("#myDiv").hover(function(){
    // do something when user hover an HTML element
});

$("#myTextbox").keyup(function(){
    // do something when user types on a textbox with ID myTextbox
});

Learn more jQuery Events

4.4 Animation Effects with jQuery. On our example above (2.0), the animation effect we used is the slideToggle(). Here are some other animations that you can do with jQuery:

// slide or toggle animation with a <p> tag
// you can change 'slow' to 'fast' or any number in milliseconds
$("p").slideToggle("slow");

$("p").slideToggle(1000, function() {  
    // do something when slide up or down animation is done
});

// hide the matched elements with a sliding motion.
$( "#book" ).slideUp( "slow", function() {
    // animation complete
});

// display or hide the matched elements by animating their opacity.
$( "#book" ).fadeToggle( "fast", function() {
    // animation complete
});

Learn more jQuery Animation Effect

Remember that the examples above are just some of the basics. Continue to practice, search and learn more in the process. And as always, thanks for reading!

5.0 Online Resources

6.0 What’s Next?

Up Next: You have two choices.

a. Learn PHP and MySQL CRUD Tutorial for Beginners – build a simple web application with PHP and MySQL database. Or,

b. Learn jQuery UI Tutorial for Beginners – Learn how to use date picker and other user interface interactions, effects, widgets, and themes built on top of the jQuery.

7.0 Related Tutorials

8.0 Some Notes

#1 Found An Issue?

If you found a problem with this code, we can solve it faster via Email or FB message, please send me a message via email mike@codeofaninja.com, or via our official Facebook page!

Please be more detailed about your issue. Best if you can provide an error message and your test or page URL. Thanks!

Please feel free to comment if you have any questions, suggestions, found something wrong or want to contribute to this code.

#2 Become a true Ninja!

We constantly add new tutorials and improve our existing tutorials and source codes. Be one of the first to know an update by subscribing to our FREE newsletter. Get a FREE EBOOK as well. CLICK HERE TO SUBSCRIBE FOR FREE!

#3 Thank You!

Thank you for learning with our jQuery Tutorial for Beginners! Please share this tutorial to one of your friends if you have time.

jQuery UI Tutorial for Beginners – Your Step by Step Guide!

jquery-ui-tutorial-for-beginners

Previously, we learned how to use jQuery to add some interactivity to our web pages. This time, are you getting started with jQuery UI? You’ve come to the right place!

This step by step tutorial aims to give you a head start in using jQuery UI. You probably know what jQuery is so you want to take a beautiful step forward with jQuery UI, and that’s awesome!

jQuery UI jQuery UI is a curated set of user interface interactions, effects, widgets, and themes built on top of the jQuery JavaScript Library.

Whether you’re building highly interactive web applications or you just need to add a date picker to a form control, jQuery UI is the perfect choice.

For me, Bootstrap and jQuery UI look good together. It also allows us to choose from different themes available, you can even create your own theme! But this post only covers running a very simple jQuery UI script in your web browser.

Contents of this post include:

1.0 Run jQuery UI in 6 Easy Steps
2.0 jQuery UI Sample Codes and Live Demos
3.0 Download Source Codes
4.0 Online Resources
5.0 What’s Next?
6.0 Related Tutorials
7.0 Some Notes

1.0 Run jQuery UI in 6 Easy Steps

The following steps below will make an awesome date picker with jQuery UI. Let’s code!

Step 1: Prepare your HTML file with just its basic structure.

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title></title>
        
    </head>
<body>

</body>
</html>

Step 2: Add a text box inside the tag. User will be able to click this and show a jQuery UI calendar picker later.

<input type="text" id="myDatepicker" placeholder="Click to pick date" />

Step 3: Add the jQuery library before the ending tag. This is because jQuery UI is built on top of jQuery library.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

Step 4: Add the jQuery UI library under the code of step 3. This is actually the first step in enabling jQuery UI in your page.

<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>

Step 5: Add jQuery UI theme via CSS external link, put it inside the tag, after the tag. This CSS will make our UI stylish.

<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/smoothness/jquery-ui.min.css" />

Step 6: Enable jQuery UI date picker to our text box on Step 1. Add the following code under the code of step 5. This is how you make a simple text box to awesome jQuery UI date picker.

<script>
$( "#myDatepicker" ).datepicker();
</script>

Quick Tip: Always use the minified version. For instance, use jquery-ui.min.css instead of just jquery-ui.css

Continue to read below, you will see the complete code of the steps above.

2.0 jQuery UI Sample Codes and Live Demos

In the demo page, you have to click the text box saying “Click to pick date” to see jQuery UI with different themes in action.

By the way, examples 2.1 and 2.2 uses Google’s content delivery network to run jQuery UI, meaning you won’t have to download the jQuery and jQuery UI library, you just have to include it.


2.1 jQuery UI with Smoothness theme hosted in Google CDN.

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>jQuery UI Tutorial for Beginners - smoothness theme - by codeofaninja.com</title>
        
        <!-- step 4 - include you jquery ui theme -->
        <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/smoothness/jquery-ui.min.css" />
        
    </head>
<body>

<!-- step 1 -->
<input type="text" id="myDatepicker" placeholder="Click to pick date" />

<!-- step 2 -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<!-- step 3 -->
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>

<script>
/* step 5 */
$( "#myDatepicker" ).datepicker();
</script>

</body>
</html>

2.2 jQuery UI with Vader theme hosted by Google too.

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>jQuery UI Tutorial for Beginners - vader theme - by codeofaninja.com</title>
        
        <!-- step 4 - include you jquery ui theme -->
        <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/vader/jquery-ui.min.css" />
        
    </head>
<body>

<!-- step 1 -->
<input type="text" id="myDatepicker" placeholder="Click to pick date" />

<!-- step 2 -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<!-- step 3 -->
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>

<script>
/* step 5 */
$( "#myDatepicker" ).datepicker();
</script>

</body>
</html>

2.3 What if I don’t want a CDN? I want to host my own jQuery UI library? No problem, you can always go to the jQuery UI download builder, you just have to select your preferred theme using the dropdown at the lower part of the page.

jquery ui download builder

jQuery UI library is self hosted in the example code below.

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>jQuery UI Tutorial for Beginners - vader theme - by codeofaninja.com</title>
        
        <!-- step 4 - include you jquery ui theme -->
        <link rel="stylesheet" href="jquery-ui-1.10.3.custom/css/le-frog/jquery-ui-1.10.3.custom.min.css" />
        
    </head>
<body>

<!-- step 1 -->
<input type="text" id="myDatepicker" placeholder="Click to pick date" />

<!-- step 2 -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<!-- step 3 -->
<script src="jquery-ui-1.10.3.custom/js/jquery-ui-1.10.3.custom.min.js"></script>

<script>
/* step 5 */
$( "#myDatepicker" ).datepicker();
</script>

</body>
</html>

3.0 Download Source Code

You can download all the code used in this tutorial for only $9.99 $5.55!

THANK YOU!

has been added to your cart!

Powered by Easy Digital Downloads

Thank you!

have been added to your cart!

Powered by Easy Digital Downloads

4.0 Online Resources

Want to see more of jQuery UI? You can always visit:

5.0 What’s Next?

Up Next: Learn PHP and MySQL CRUD Tutorial for Beginners – build a simple web application with PHP and MySQL database.

6.0 Related Tutorials

7.0 Some Notes

#1 Found An Issue?

If you found a problem with this code, we can solve it faster via Email or FB message, please send me a message via email mike@codeofaninja.com, or via our official Facebook page!

Please be more detailed about your issue. Best if you can provide an error message and your test or page URL. Thanks!

Please feel free to comment if you have any questions, suggestions, found something wrong or want to contribute to this code.

#2 Become a true Ninja!

We constantly add new tutorials and improve our existing tutorials and source codes. Be one of the first to know an update by subscribing to our FREE newsletter. Get a FREE EBOOK as well. CLICK HERE TO SUBSCRIBE FOR FREE!

#3 Thank You!

Thanks for reading our jQuery UI tutorial for beginners!

Home jQuery

jQuery UI Dialog Example with Source Code Downloads

jquery-ui-tutorial
Dialog boxes, modals, confirm boxes can also be done with awesomeness in jQuery UI. In this post we are going to take a look at the three jQuery UI dialog code examples I commonly use in my projects. Live demos and code download button links were also provided below. Keep on reading!

jquery ui dialog example

In this post we will cover the following:

1. jQuery UI Basic Modal
2. jQuery UI Confirm Dialog
3. jQuery UI Load Content from URL
3.1 Save the loaded URL content
3.2 Destroy or remove the loaded URL content
4. Download Source Code

Our jQuery, jQuery UI and jQuery UI theme are hosted by Google. You can choose your jQuery UI theme here.

1. jQuery UI Basic Modal

I love modals, or a “modal window” or “modal dialog”, it is a child window that pops up in your application that requires a user interaction. It can display information, gives you choices or even contain an HTML form!

In jQuery UI, when you set modal: true parameter, it will be able to dim the background of your page when showing the dialog. If it is set to false, the background will remain as is.

This is useful when a client (like mine) did not like dimming the background. But I like dimming the background when showing a dialog, so in our code below, we’ll set the modal to true.

basic-dialog.html code:

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>jQuery UI Dialog Modal Example by codeofaninja.com</title>
        
        <!-- include you jquery ui theme -->
        <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/smoothness/jquery-ui.css" />
        
        <!-- you can have your own style -->
        <style>
        body {
            font-family: "Trebuchet MS", "Helvetica", "Arial",  "Verdana", "sans-serif";
            font-size: .8em;;
        }
        
        /* dialog div must be hidden */
        #basicModal{
            display:none;
        }
        </style>
        
    </head>
<body>

<!-- sample content in your page -->
<div>You can click the button to show the basic jQuery UI dialog box.</div>
<input type='button' value='Show basic dialog!' id='showDialog' />

<!-- 
    -this is the actual dialog, yes, it is included in your html body, it is just hidden
    -you can set the dialog title via the 'title' tag 
-->
<div id="basicModal" title="A message from codeofaninja.com">
    Thank you for visiting codeofaninja.com!
</div>

<!-- include the jquery library -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<!-- include the jquery ui library -->
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>

<script>
// show the dialog on click of a button
$( "#showDialog" ).click(function(){

    /* -select the div you want to be a dialog modal, in our case it is 'basicModal'
       -you can add parameters such as width, height, title, etc. */
    $( "#basicModal" ).dialog({
        modal: true,
        height: 300,
        width: 400
    });
    
});
</script>

</body>
</html>

2. jQuery UI Confirm Dialog

Instead of the old JavaScript confirm dialog box, I use jQuery UI. This is for a better user interface and to control the number of buttons and their labels, instead of just “ok” and “cancel”.

confirm-dialog.html code:

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>jQuery UI Confirm Dialog Example by codeofaninja.com</title>
        
        <!-- include you jquery ui theme -->
        <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/smoothness/jquery-ui.css" />
        
        <!-- you can have your own style -->
        <style>
        body {
            font-family: "Trebuchet MS", "Helvetica", "Arial",  "Verdana", "sans-serif";
            font-size: .8em;;
        }
        
        /* dialog div must be hidden */
        #basicModal{
            display:none;
        }
        </style>
        
    </head>
<body>

<!-- sample content in your page -->
<div>You can click the button to show the basic jQuery UI dialog box.</div>
<input type='button' value='Show confirm dialog!' id='showDialog' />

<!-- 
    -this is the actual dialog, yes, it is included in your html body, it is just hidden
    -we did not set the dialog 'title' here, we set it in the js parameter
-->
<div id="basicModal">
    Go to codeofaninja.com?
</div>

<!-- include the jquery library -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<!-- include the jquery ui library -->
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>

<script>
// show the dialog on click of a button
$( "#showDialog" ).click(function(){

    /* select the div you want to be a dialog, in our case it is 'basicModal'
    you can add parameters such as width, height, title, etc. */
    $( "#basicModal" ).dialog({
        modal: true,
        title: "Are you sure?",
        buttons: {
            "YES": function() {
                window.open("https://codeofaninja.com/", '_blank');
            },
            "NO": function() {
                $( this ).dialog( "close" );
            }
        }
    });
    
});
</script>

</body>
</html>

3. jQuery UI Load Content from URL

URL to be loaded must be in the same domain or subdomain name. If you really want to load from different domain, use iframes, example code here.

In this example, we will use sample_page.php as the file of URL to be loaded, it has the following contents:

<?php
echo "Here's the sample page loaded.<br /><br />";
echo "Only a page from the same domain/subdomain can be loaded using this technique.<br /><br />";
echo "If you really want to load a page from another domain/subdomain, use an iframe.<br /><br />";
echo "<a href='http://stackoverflow.com/a/14570255/903298' target='_blank'>Example code here</a>";
?>

3.1 Save the loaded URL content

Here’s is the default behaviour of the jQuery UI dialog, it appends the URL content to the HTML body.

load-url-dialog.html code:

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>jQuery UI Dialog Example by codeofaninja.com</title>
        
        <!-- include you jquery ui theme -->
        <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/smoothness/jquery-ui.css" />
        
        <!-- you can have your own style -->
        <style>
        body {
            font-family: "Trebuchet MS", "Helvetica", "Arial",  "Verdana", "sans-serif";
            font-size: .8em;;
        }
        
        /* dialog div must be hidden */
        #basicModal{
            display:none;
        }
        </style>
        
    </head>
<body>

<!-- sample content in your page -->
<div>You can click the button to show the basic jQuery UI dialog box.</div>
<input type='button' value='Show basic dialog!' id='showDialog' />

<!-- 
    -this time, we don't have the dialog html in the body, it is in another url
    -we use the image loader to add some good effect when the system loads the url (after user click)
 -->
<img src="images/ajax-loader.gif" id="imgLoader" style="display:none;" />

<!-- include the jquery library -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<!-- include the jquery ui library -->
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>

<script>
// show the dialog on click of a button
$( "#showDialog" ).click(function(){

    /* here you can specify the url */
    var url = "sample-page.php";
    
    /* container of the content loaded from a url */
    var tag = $("<div></div>");
    
    console.log("url: " + url);
    
    /* show the image loader */
    $('#imgLoader').show();
    
    $.ajax({
        url: url,
        success: function( data ) {
        
            tag.html(data).dialog({
                modal: true,
                title: "Content is loaded from a URL!",
                width: 600,
                height: 450
            }).dialog('open');

            /* hide the image loader */
            $('#imgLoader').hide();
            console.log("success!");
        }
    });
    
});
</script>

</body>
</html>

To prove that the URL contents will be appended in the body of your HTML document, see the screenshot below, I used Google Chrome’s inspect element to view this live source code of the current page.

jquery ui dialog not destroyed or removed

LIVE DEMO

3.2 Destroy or remove the loaded URL content

By default, the jQuery UI append the URL contents in your HTML body, if you want to prevent it, we can we add the close parameter on the dialog and use the jQuery remove() method.

load-url-destroy-dialog.html code:

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>jQuery UI Dialog Example by codeofaninja.com</title>
        
        <!-- include you jquery ui theme -->
        <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/smoothness/jquery-ui.css" />
        
        <!-- you can have your own style -->
        <style>
        body {
            font-family: "Trebuchet MS", "Helvetica", "Arial",  "Verdana", "sans-serif";
            font-size: .8em;;
        }
        
        /* dialog div must be hidden */
        #basicModal{
            display:none;
        }
        
        </style>
        
    </head>
<body>

<!-- sample content in your page -->
<div>You can click the button to show the basic jQuery UI dialog box.</div>
<input type='button' value='Show basic dialog!' id='showDialog' />

<!-- 
    -this time, we don't have the dialog html in the body, it is in another url
    -we use the image loader to add some good effect when the system loads the url (after user click)
-->
<img src="images/ajax-loader.gif" id="imgLoader" style="display:none;" />

<!-- include the jquery library -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<!-- include the jquery ui library -->
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>

<script>
// show the dialog on click of a button
$( "#showDialog" ).click(function(){

    /* here you can specify the url */
    var url = "sample-page.php";
    
    /* container of the content loaded from a url */
    var tag = $("<div></div>");
    
    /* show the image loader */
    $('#imgLoader').show();
    
    $.ajax({
        url: url,
        success: function( data ) {
        
            tag.html(data).dialog({
                modal: true,
                title: "Content is loaded from a URL!",
                width: 600,
                height: 450,
                close: function(){
                     tag.dialog('destroy').remove()
                }
            }).dialog('open');

            /* hide the image loader */
            $('#imgLoader').hide();
            console.log("success!");
        }
    });
    
});
</script>

</body>
</html>

To prove that the URL content did not append in the HTML body, see the screenshot of the live source code below.

jquery ui dialog was destroyed and removed

4.0 Download Source Code

You can download all the code used in this tutorial for only $9.99 $5.55!

THANK YOU!

has been added to your cart!

Powered by Easy Digital Downloads

Thank you!

have been added to your cart!

Powered by Easy Digital Downloads

If you think of any other jQuery UI dialog example, please drop it in the comments section below, we’ll try our best to add it in this post. Thanks!

Optimize Image for Web Using Photoshop and Thoughts on Faster Web Pages

This post is supposed to be a quick-tip on how you can optimize your images for web pages. But it feels like I also want to give some thoughts about website speed. There are many websites saying that your images must be optimized for the web, that should be updated and say, “your images must be optimized for web and mobile devices” in which the amazing Adobe Photoshop can help us with.