Showing posts with label JQuery. Show all posts
Showing posts with label JQuery. Show all posts

May 1, 2013

jQuery Context Menu


In this tutorial I am sharing my newly created jQuery Plugin, jQuery Simple Context Menu.


jQuery Simple Context Menu


GITHUB REPO :
https://github.com/nirajmchauhan/jquery-simple-context-menu




Currently this plugin accepts two paramenters:

  • Custom HTML - You have to give entire HTML code with proper attributes in it wrapped inside ul


  • Simple HTML - You have to pass href link and the text to be shown.



Simple HTML usage
Include the jquery file, you can download this from github.


[js]

jQuery(function($){
$(document).ready(function(){

$('#Simple').simpleContextMenu({
options : {
'Home' : '#',
'About Us' : '#',
'Services' : '#',
'Contact Us' : '#'
}
});

});
});

[/js]



Inside options you need to pass text and the link, the above code will generate a HTML in following format :


[html]
<ul>
<li>
<a href="#">Home</a>
</li>
<li>
<a href="#">About Us</a>
</li>
<li>
<a href="#">Services</a>
</li>
<li>
<a href="#">Contact Us</a>
</li>
</ul>
[/html]



Custom HTML usage


[js]

jQuery(function($){
$(document).ready(function(){

$('#CustomHTML').simpleContextMenu({
html: '<div class="dropdown clearfix"><ul style="display: block; position: static; margin-bottom: 5px; *width: 180px;" aria-labelledby="dropdownMenu" role="menu" class="dropdown-menu"><li><a href="#" tabindex="-1">Action</a></li><li><a href="#" tabindex="-1">Another action</a></li><li><a href="#" tabindex="-1">Something else here</a></li><li class="divider"></li><li><a href="#" tabindex="-1">Separated link</a></li></ul></div>'
});

});
});

[/js]



Inside html you need to pass entire html which will be the context menu. Above I am using bootstrap.




Both parameters cannot be used together, use only one at a time. You can have multiple context menus on a single page. Check out the demo and fork me.

Mar 25, 2013

How To Make A Chat Program In Node JS

Today we will start with NodeJS.


NodeJS

So what is NodeJS?


In simple terms, JavaScript on server side. NodeJS uses Googles V8 engine. Its basically a javascript library which is executed on server side. Its also known as JavaScript without browser.


When and why to use nodejs?


Choosing a technology depends on the developer who is going to take it ahead. NodeJS is very simple, you just need to know javascript. NodeJS can be used for online gaming, chat programming, CRM management and also for blogging. There are several plugins available which make your job easy.



So today lets start with a simple chat program.



Installing NodeJS on Windows




First download the latest copy of nodejs from here. After installation open cmd and just type node -v. This will output you the current installed version of nodejs.




Now create a folder on desktop, name it as node-chat, using cmd navigate to that directory. Now inside that folder create a file package.json. This file contains all the dependencies and other plugin information. Paste below code inside it:



[js]
{
"name": "node_chat",
"version": "1.0.0-4",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node app.js"
},
"dependencies": {
"socket.io": "0.9.11",
"connect": "2.7.1"
},
"author": "Niraj Chauhan",
"license": "BSD",
"subdomain": "node-chat",
"engines": {
"node": "0.6"
}
}
[/js]

Above json is simple, it takes few parameters like name of author, filename which is going to be executed first, dependencies etc.



Now in cmd just type npm install. This will install all required dependencies which are mentioned inside the json file.



After above command if you check the folder, it consists with a new folder named as node_modules This ensures that all the important modules are installed.



Create a file app.js and paste the below code in it.


[js]
var io = require('socket.io'),
connect = require('connect'),
url = require('url'),
sys = require('sys'),
http = require('http'),
fs = require('fs');

var port = 3000;


var app = connect().use(connect.static('public')).listen(port);
var chat_room = io.listen(app);
console.log('Listening to port ' + port);

chat_room.sockets.on('connection', function (socket) {
socket.emit('entrance', {
message: 'Welcome to the chat room!'
});

socket.on('disconnect', function () {
chat_room.sockets.emit('exit', {
message: 'A chatter has disconnected.'
});
});

socket.on('chat', function (data) {
message = {
user: data.message.user,
message: data.message.message
};
chat_room.sockets.emit('chat', {
message: message
});
});

chat_room.sockets.emit('entrance', {
message: 'A new chatter is online.'
});
});
[/js]

If you have worked with server side technology like php, java etc then you ll understand the basic from above. Firstly we have included some modules which we will need. We will be using socket.io to make a flawless connection between server and client. We will also be using connect


Connect offers a createServer method, which returns an object that inherits an extended version of http.Server. Connect's extensions are mainly there to make it easy to plug in middleware. That's why Connect describes itself as a "middleware framework," and is often analogized to Ruby's Rack.

After including required files we listen to a port which redirects to a folder public and finally we open the socket after successful connection between server and client.


Using opened socket variable, we define different methods inside the connection function.




  • entrance: Used when a socket connection established between server and client

  • disconnect: Used when a client breaks the connection

  • chat: Used to transfer messages between different clients via server.



So now lets create a foder and name it to public. This folder will contain all the UI html and css files. Here I ll be using twitter bootstrap.



So by now your folder structure should be something like this:




node-chat/
|--node_modules/
|--public/
|----css/
|----img/
|----js/
|----index.html
|--app.js
|--package.json



Inside your index.html file paste the below code


[js]
<script src="js/jquery-1.7.2.min.js"></script>
<script src="http://localhost:3000/socket.io/socket.io.js"></script>
<script type="text/javascript" charset="utf-8">
var socket = io.connect('ws://localhost:3000/');
var user = {
name: ''
}
jQuery(document).ready(function() {

jQuery('#chat_box').keypress(function(event) {
if (event.which == 13) {
socket.emit('chat', {
message: {
user: user.name,
message: jQuery('#chat_box').val()
}
});
jQuery('#chat_box').val('');
}
});

});

function startChat() {
user.name = $('#username').val();

var log_chat_message = function(message, type) {

if (type == 'chat') {
var li = jQuery('<li />').html('<span>' + message.user + '</span>: ' + message.message);
} else {
var li = jQuery('<li />').html('<span>' + message + '</span>');
}


jQuery('#chat_log').append(li);
};

if (user.name != '') {
$('#loginDiv').fadeOut();
$('#chat').fadeIn();

socket.on('chat', function(data) {
log_chat_message(data.message, 'chat');
});

socket.on('entrance', function(data) {
log_chat_message(data.message, 'system');
});

socket.on('exit', function(data) {
log_chat_message(data.message, 'system');
});

} else {
alert('Please enter your username');
}
}
</script>
[/js]


Above code is simple jquery, which contains some functions for chatting, login, printing message etc. So quickly I ll explain you the important part of chat.




When user opens the page, we call the socket file, this file is installed inside modules using the json file. Then first we open a socket connection between server and user. This triggers the app.js file and entire connection is established. Then by using the functions of connection which is declared inside app.js file(chat, entrance, exit) we call those functions from here. Each function passes and takes some message. Using chat we take message from user who typed, passed it to server, server takes that message and throws to all user within the socket connection.



To execute this chat, just run this command in cmd within the directory where app.js file exists node app.js, then in browser navigate to http://localhost:3000/


You can check the working demo and download the files. I have just covered the important flow of the code and how nodejs and sockets can be helpful. This chat works in almost all browsers and devices, this is the plus point of using sockets via nodejs

Nov 20, 2012

jQuery Form Validation Plugin

If you are developing websites then you will come across Form validation. I too and I was using jQuery Validation plugin. This is an awesome plugin but really buggy in IE7/8 browser with different jQuery versions. Its not stable and the developer of this plugin is not looking after the bugs. I reported several times but no response. So finally I decided to make my own validation plugin.

Before I start further let me tell you that currently this plugin only validates INPUT types with number, email and blank value fields. Its still in beta or under development mode.

GITHUB REPO : https://github.com/nirajmchauhan/jQuery-form-validation





Form-Validation



I ll explain you the usage of this plugin by a simple form example



HTML:



[html]
<section>
<form method="post" class="form-horizontal" id="loginForm" onsubmit="return false;">
<div class="control-group">
<label class="control-label" for="inputEmail">Email</label>
<div class="controls">
<input type="text" id="inputEmail" name="user" placeholder="Email" class="required email">
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputPassword">Password</label>
<div class="controls">
<input type="password" id="inputPassword" name="password" class="required" placeholder="Password">
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox"> Remember me
</label>
<button id="submit" type="submit" class="btn" onclick="javascript:ajaxThrow('#loginForm','#response');">Sign in</button>



</div>
</div>
<div class="alert alert-info" id="response"></div>
</form>
</section>
[/html]




To make a field mandatory, you need to add a class required.
Currently on input types will be accepted so to make if mandatory, use the following attributes :


















class Output
class="required email" This will check for blank field and whether the value is EMAIL ID
class="required number" This will check for blank field and whether the value is a NUMBER
class="required" This field will check for blank values


So now the final is the jQuery:



JS:


[js]
jQuery(function($) {
$(document).ready(function() {

$('#submit').click(function() {
val = $('#loginForm :input').validateForm();
if (val) {
var qstring = $('#loginForm').serialize();
$('#response').fadeIn().html('Form Validated successfully with following fields<br>' + qstring);
}
});

});
});
[/js]




To validate the form, you ll just need to add a line :
val = $('#loginForm :input').validateForm();

This will return a boolean value. And will also add a class error to the respective input field.

Check this in action here :





Aug 27, 2012

JQuery Treeview List

JQuery Treeview List - Creates a nice expanding and collapsing tree view control using jQuery.

JQuery Treeview List

Tree view Displays a hierarchical collection of labeled items, each represented by a TreeNode. This you'll normally see in windows or MAC folder navigation.

Today I am making it in JQuery for ul, li list.



Basic HTML Markup


[html]
<ul>
<li><a>First Level</a>
<ul>
<li><a>Second Level</a></li>
<li><a>Second Level</a></li>
<li><a>Second Level</a></li>
</ul>
</li>
<li><a>First Level</a>
<ul>
<li><a>Second Level</a>
<ul>
<li><a>Third Level</a></li>
<li><a>Third Level</a></li>
<li><a>Third Level</a>
<ul>
<li><a>Fourth Level</a></li>
<li><a>Fourth Level</a></li>
<li><a>Fourth Level</a>
<ul>
<li><a>Fifth Level</a></li>
<li><a>Fifth Level</a></li>
<li><a>Fifth Level</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li><a>Second Level</a></li>
</ul>
</li>
<li><a>First Level</a>
<ul>
<li><a>Second Level</a></li>
<li><a>Second Level</a></li>
</ul>
</li>
</ul>
[/html]

We just created a normal list formation in hierarchical way.



Now lets add some styling - CSS


[css]
.tree {
-moz-border-bottom-colors: none;
-moz-border-image: none;
-moz-border-left-colors: none;
-moz-border-right-colors: none;
-moz-border-top-colors: none;
background: -moz-linear-gradient(center top , #E3E3E3, #FFFFFF 85px) repeat scroll 0 0 transparent;
border-color: #BFC0C2 #BFC0C2 #B6B7BA;
border-radius: 3px 3px 3px 3px;
border-style: solid;
border-width: 1px;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.17), 0 -2px 0 rgba(0, 0, 0, 0.08) inset;
display: inline-block;
margin: 0 0 50px;
min-width: 300px;
padding: 10px 15px 15px;
}
.tree ul {
list-style: none outside none;
}
.tree li a {
line-height: 25px;
}
.tree > ul > li > a {
color: #3B4C56;
display: block;
font-weight: normal;
position: relative;
text-decoration: none;
}
.tree li.parent > a {
padding: 0 0 0 28px;
}
.tree li.parent > a:before {
background-image: url("../images/plus_minus_icons.png");
background-position: 25px center;
content: "";
display: block;
height: 21px;
left: 0;
position: absolute;
top: 2px;
vertical-align: middle;
width: 23px;
}
.tree ul li.active > a:before {
background-position: 0 center;
}
.tree ul li ul {
border-left: 1px solid #D9DADB;
display: none;
margin: 0 0 0 12px;
overflow: hidden;
padding: 0 0 0 25px;
}
.tree ul li ul li {
position: relative;
}
.tree ul li ul li:before {
border-bottom: 1px dashed #E2E2E3;
content: "";
left: -20px;
position: absolute;
top: 12px;
width: 15px;
}
[/css]


In css we are making tree nodes usinf :before

Last we will add jquery functionality to toggle the list on click events.



JQuery


[js]
$('.tree li').each(function(){
if($(this).children('ul').length > 0){
$(this).addClass('parent');
}
});

$('.tree li.parent > a').click(function(){
$(this).parent().toggleClass('active');
$(this).parent().children('ul').slideToggle('fast');
});
[/js]

Here first we search for all parent nodes and if found then we are adding a class named as .parent

Then on click of any parent elements, we just add a class .active and slide the li's in it.

This can be used to show the navigation of the website.

Jul 25, 2012

AJAX Contact Form With Validation

Today I am going to share a simple tutorial on How to make a AJAX contact form with validation.

JQUERY-AJAX



What is AJAX?
AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.


The flow of the form is :


AJAX Process Diagram

So here I am using twitter bootstrap, so files which we need are :-

  • data.php - (here we will write our PHP code)

  • script.js - (here we will write our ajax jquery code)

  • validate.js - (jqueryvalidation plugin)

  • index.php and style.css



So the fields of our form will be Name, Email, Number, City, Area, Message, Submit

Here our city and area will also be using AJAX i.e. on city change area will also be changed.

index.php


[html]
<?php require_once('data.php'); ?>
<div class="hero-unit">
<h2>Contact Us</h2>

<form id="contactUs" name="contactUs" onsubmit="return false;">


<table cellspacing="5" cellpadding="5">
<tr>
<td><label for="name">Name:</label></td>
<td><input type="text" value="" name="name" id="name" class="required name"/></td>
</tr>
<tr>
<td><label for="email">Email:</label></td>
<td><input type="text" value="" name="email" id="email" class="required email"/></td>
</tr>
<tr>
<td><label for="number">Contact Number:</label></td>
<td><input type="text" value="" name="number" id="number" class="required number" minlength="8"/></td>
</tr>
<tr>
<td><label for="city">City:</label></td>
<td>
<select id="city" name="city" onchange="javascript:changeArea('#city', '#area');">
<option value="Any">Any</option>
<?php echo getCities();?>
</select>
</td>
</tr>
<tr>
<td><label for="area">Area:</label></td>
<td><select id="area" name="area" disabled="disabled"></select></td>
</tr>
<tr>
<td><label for="message">Message:</label></td>
<td><textarea id="message" name="message" class="required"></textarea></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="hidden" name="contactFormSubmit" value="Yes" />
<input type="submit" value="Submit" class="btn" onclick="javascript:formSubmit('#contactUs','#responseText');"/>
</td>
</tr>
<tr>
<td colspan="2" align="center">
<div id="responseText"></div>
</td>
</tr>

</form>
</div>
[/html]



Here we just made a simple html structure of form inside a table.

To make a field mandatory, just add class="required" to input.

If you want to validate it with only email or number then add class="required email" or class="required number"

If I add a attribute minlength="8" to the number field then that field should contain at least 8 digits of number.

data.php


[php]
<?php
$cities = array('1'=>'Mumbai',
'2'=>'Chennai',
'3'=>'Noida',
'4'=>'Bangalore');

$areas = array( 'Airoli' => '1',
'Andheri' => '1',
'Bandra' => '1',
'Bhandup' => '1',
'Bhayandar' => '1',
'Boisar' => '1',
'Borivali' => '1',
'Chembur' => '1',
'Gopalapuram' => '2',
'Mount Road' => '2',
'Noida Expressway' => '3',
'Sector 1' => '3',
' Sector 128' => '3',
'Sector 129' => '3',
'Yamuna Expressway' => '3',
'Anekal ' => '4',
'Banashankari ' => '4',
'Banasvadi ' => '4',
'Banaswadi ' => '4',
'Begur ' => '4',
'Bellary Road ' => '4',
'Dobespet ' => '4',
'Electronics City' => '4');


if(isset($_REQUEST['cityID']) && $_REQUEST['cityID'] != 'Any'){

getAreas($_REQUEST['cityID']);

}

if(isset($_REQUEST['contactFormSubmit'])){
if(!isValidEmail($_REQUEST['email'])){
echo 'Enter a valid email ID';
}elseif(!is_mobileNumber($_REQUEST['number'])){
echo 'Enter a valid number';
}elseif($_REQUEST['name'] == '' || $_REQUEST['message'] == ''){
echo 'Enter valid name or message';
}else{
?>
<p><b>Thank you for contacting us, your given information : </b></p>
<table cellspacing="5" cellpadding="5" border="1">
<tr>
<td>Name:</td>
<td><?php echo $_REQUEST['name']?></td>
</tr>
<tr>
<td>Email:</td>
<td><?php echo $_REQUEST['email']?></td>
</tr>
<tr>
<td>Contact Number:</td>
<td><?php echo $_REQUEST['number']?></td>
</tr>
<tr>
<td>City:</td>
<td><?php echo $_REQUEST['city']?></td>
</tr>

<?php if(isset($_REQUEST['area'])) : ?>
<tr>
<td>Area:</td>
<td><?php echo $_REQUEST['area']?></td>
</tr>
<?php endif; ?>

<tr>
<td>Message:</td>
<td><?php echo $_REQUEST['message']?></td>
</tr>
</table>
<?php
}
}



function getCities(){
global $cities;
foreach($cities as $Idx => $city){

echo '<option value="'.$Idx.'">'.$city.'</option>';

}
}

function getAreas($cityID = ''){
global $areas;
foreach($areas as $area => $Idx){

if($Idx == $cityID){

echo '<option value="'.$Idx.'">'.$area.'</option>';

}

}
}

function isValidEmail($email){
return eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email);
}

function is_mobileNumber($mobile) {
$regex1 = '123456789';
$regex2 = '1234567890';
$regex3 = '0123456789';

if(preg_match('/^([0-9])\1*$/', $mobile)){
return false;
}elseif($mobile == $regex1){
return false;
}elseif($mobile == $regex2){
return false;
}elseif($mobile == $regex3){
return false;
}elseif(preg_match("/[^0-9]/", $mobile)){
return false;
}else{
return true;
}
}
?>
[/php]



PHP code is simple, I am making an array of cities and area, made 2 functions to get areas and cities and getting the parameters from URL and passing it to functions.

Now the ajax function :

script.js


[js]
function changeArea(cityBox, areaBox) {
jQuery(function($) {

$(areaBox).attr('disabled','disabled');

$(areaBox).addClass('loading');
$.ajax({ //Starting the AJAX
url : 'data.php', //File to be called or pass the data
data : { //Extra paramters
"cityID" : $(cityBox+' option:selected').attr('value')
},
success : function(data) { // The result from data.php file comes as data
window.setTimeout(function(){
$(areaBox).removeAttr('disabled');

$(areaBox).removeClass('loading');

$(areaBox).html('');

$(areaBox).html(data);

}, 2000);
}
});
});
}
[/js]



The above function is is taking two parameters, the select id of City and area. Then I am saving the value of city in a variable, and inside ajax I am passing the value of city to data.php file.

Inside data.php I wrote a function to return areas according to the city ID. Inside success function I am inserting entire result into the area select box.

Simlarly I am going to make another function which will validate the form and if no error then ajax is called and mail is sent.

script.js


[js]
/* Submission of form */

function formSubmit(formID, displayMssgID) {
jQuery(function($) {

var qstring = $(formID).serialize();

var val = $(formID).validate().form();
if (val) {
$(displayMssgID).html('Registering your Request ... Please Wait ...');
$.ajax( {
url : "data.php",
data : qstring,
success : function(data) {

$(displayMssgID).html('');
$(displayMssgID).html(data);
window.setTimeout(function() {

$(displayMssgID).fadeOut();

}, 6000);

}
});
}
});
}
[/js]



This function takes two parameters, ID of the form and result message div. First I am serializing the form, which will take all the form data and store it in a variable. Then I am validating it, if validation is true then our AJAX is called and entire form data is passed to data.php file.

This is return will give some output which I am showing it in id="responseText"

This is a simple way to make AJAX forms, there might be many other tutorials on other websites but I find this very simple. This way you can make any AJAX form. Try out the demo.



Thanks to Jacob for server validation tip.

Jul 18, 2012

JQuery Allow Only Numbers

For a frontend developer when it is asked to do something unique that person will think of JQuery first. Today a simple jquery code to allow only numbers to a text-box. Below code will allow following key events :


  • Backspace

  • Delete

  • Tab

  • Escape

  • Enter

  • Ctrl+A

  • Home

  • end

  • left

  • right



Just add a class to textbox .onlyNumbers and paste the following jquery code :



[js]
$(document).ready(function() {

$(".onlyNumbers").keydown(function(event) {

if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 13 || (event.keyCode == 65 && event.ctrlKey === true) || (event.keyCode >= 35 && event.keyCode <= 39)) {
return;
}
else {

if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105)) {
event.preventDefault();
}
}
});

});
[/js]



You can also apply this to textarea.

Demo:





Jul 11, 2012

Simple JQuery Tabs

JQuery tabs. Whenever I start any new project tabs is something which I have to use, so instead of using any external js library I created a small function.

JQuery Tabs



[html]
<div id="tabs">
<div class="divTabs"> <!-- divTabs class is important, this will be passed in function -->
<div id="tab_menu_1" class="tab selected first">PHP</div>
<div id="tab_menu_2" class="tab last">JQUERY</div>
</div>
<div class="divTabs-container">
<div id="divTabs_tab_content_1" class="tabcontent" style="display:block;">Content 1</div>
<div id="divTabs_tab_content_2" class="tabcontent">Content 2</div>
</div>
</div>
[/html]



First we are creating a div with a class name, this class name is really important. This class name will be passed in entire tabs, just check the class naming of the div in the above html. It is prefixed with other classes.

CSS is simple just make the .tabcontent{display:none;}

Now time for js function



[js]
function generateTabs(element) {
jQuery(function($) {
$("."+element+" .tab[id^=tab_menu]").click(function() {
var currentDiv=$(this);
$("."+element+" .tab[id^=tab_menu]").removeClass("selected");
currentDiv.addClass("selected");
var index=currentDiv.attr("id").split("tab_menu_")[1];
$("."+element+"-container .tabcontent").css('display','none');
$("."+element+"-container #"+element+"_tab_content_"+index).fadeIn();
});
});
}
[/js]



Now call this function by passing the classname.
generateTabs('divTabs');

Check the demo below




Jul 3, 2012

JQuery Slide Left Right | JQuery Toggle Left Right

Recently I completed a project where I had to show a panel to the left side using JQuery, on mouse hover it comes out and on mouse leave it goes back. Its seems to be easy but to maintain the functionality is not that easy.

Here's a small snippet on how to do it.

HTML


[html]
<div id="sidePanel">
<div id="panelContent">
<iframe src="//www.facebook.com/plugins/likebox.php?href=http%3A%2F%2Fwww.facebook.com%2FWebsTutorial&amp;width=200&amp;height=258&amp;colorscheme=light&amp;show_faces=true&amp;border_color&amp;stream=false&amp;header=false&amp;appId=253401284678598" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:200px; height:258px;" allowTransparency="true"></iframe>
</div>
<div id="panelHandle">
<p>Facebook</p>
</div>

</div>
[/html]




JQuery


[js]
jQuery(function($) {
$(document).ready(function() {
$('#panelHandle').hover(function() {
$('#sidePanel').stop(true, false).animate({
'left': '0px'
}, 900);
}, function() {
jQuery.noConflict();
});

jQuery('#sidePanel').hover(function() {
// Do nothing
}, function() {

jQuery.noConflict();
jQuery('#sidePanel').animate({
left: '-201px'
}, 800);

});
});
});
[/js]



Demo :





Dec 19, 2011

How To Show Latest Tweets Using PHP JQuery

Today I am sharing my newly PHP and JQuery coded snippet which is going to display your latest tweets in a fade in and fade out effect using Twitter timeline RSS feeds.



Here is the PHP function to get the tweets:

 
[php]
<?php
function latest_tweets(){
//global $post;
$doc = new DOMDocument();
$meta='webstutorial';
$feed = "http://twitter.com/statuses/user_timeline/$meta.rss";
$doc->load($feed);

$outer = '<ul id="tweets">';
$max_tweets = 15;
$i = 1;
foreach ($doc->getElementsByTagName('item') as $node) {
$tweet = $node->getElementsByTagName('title')->item(0)->nodeValue;
//if you want to remove the userid before the tweets then uncomment the next line.
//$tweet = substr($tweet, stripos($tweet, ':') + 1);
$tweet = preg_replace('@(https?://([-w.]+)+(:d+)?(/([w/_.]*(?S+)?)?)?)@',
'<a href="$1">$1</a>', $tweet);
$tweet = preg_replace("/@([0-9a-zA-Z]+)/",
"<a href="http://twitter.com/$1">@$1</a>",
$tweet);

$outer .= "<li>". $tweet . "</li>n";


if($i++ >= $max_tweets) break;
}
$outer .= "</ul>n";
return "<div class='post'><p><b>Latest Tweets </b>".$outer."</div>";
}
echo latest_tweets();
?>
[/php]
 

In the above function we are fetching the RSS feed from the twitter timeline. Then we finally break it into segments and display it using the loop method.

Now we have to display the tweets with jquery effect.

So here is the jquery function to display the tweets in a fadeIn effect.

 
[js]
<script type="text/javascript">
function tweetRender( prospectID )
{
prospectID.delay() .fadeIn() .delay(2000).fadeOut(
function(){
if(prospectID.next().length > 0)
{tweetRender( prospectID.next() );}
else
{tweetRender( prospectID.siblings(':first'));}

}
);
}

$(function(){
$('#tweets li').hide();
tweetRender( $('#tweets li:first') );

});
</script>
[/js]
 

In this tutorial we are using basic PHP and JQuery to display the tweets. You can download it and check the Demo.

Dec 17, 2011

JQuery Page Loading Popup

In a website whenever a user clicks a link, that user has to wait for seconds to see the new loaded page. In today’s tutorial we will show an interesting popup after the click event occurs and after few seconds the page will load.

This is just an interactive way to load a page; it will take the same time to load as it was before.

The basic HTML Code:
[html]
<div style="display: none;" id="overlay"></div>
<div style="display: none;" id="popup">
<img src="loading.gif" />
</div>

<a href="www.webstutorial.com/jquery-page-loading-popup/jquery" id="link">Click Here</a>
[/html]

The JQuery code:

[js]
<script type="text/javascript">
$(document).ready(function(){
jQuery("#link").click(function(event) {
event.preventDefault(); //to stop the default loading
var a_href = $('#link').attr('href'); // getting the a href link
jQuery("#overlay").css('display','block'); // displaying the overlay
jQuery("#popup").css('display','block'); // displaying the popup
jQuery("#popup").fadeIn(500); // Displaying popup with fade in animation
setTimeout(function() {
jQuery("#popup").fadeIn(4000); //function to redirect the page after few seconds
window.location.replace("http://"+a_href); // the link
}, 3000);
});
});
</script>
[/js]


Try the Demo, and suggestions are always open.

Dec 9, 2011

JQuery Popup | JQuery Slide Popup

Now a day’s JQuery’s are used almost in all websites. In today’s tutorial I am going to share a new way to show a pop up message. Everyone is getting bored with typical fade in fade out pop up messages. So let’s make it interesting with a pinch of jquery and css.

In this tutorial we are going to make two javascript functions which will be used to slide in and slide out a div.

[js]
function openOffersDialog() {
$('#overlay').fadeIn('fast', function() {
$('#boxpopup').css('display','block');
$('#boxpopup').animate({'left':'30%'},500);
});
}

function closeOffersDialog(prospectElementID) {
$(function($) {
$(document).ready(function() {
$('#' + prospectElementID).css('position','absolute');
$('#' + prospectElementID).animate({'left':'-100%'}, 500, function() {
$('#' + prospectElementID).css('position','fixed');
$('#' + prospectElementID).css('left','100%');
$('#overlay').fadeOut('fast');
});
});
});
}
[/js]

In the first function we are making a call to a div to fadeIn and in that fade in function we are sliding our popup from right to left.

The next function is used to slide the function from center of the screen to the extreme left side so it appears us to be disappeared. In this function we also set the overlay div to fadeout.

So let’s construct with our HTML part.

[html]
<body onload="openOffersDialog();">
<div id="wrapper">
<div id="overlay" class="overlay"></div>
<a onclick="openOffersDialog();">Click Here To See The PopUp</a>
<div id="boxpopup" class="box">
<a onclick="closeOffersDialog('boxpopup');" class="boxclose"></a>
<div id="content">
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet. Quisque rutrum.
</div>
</div>
</div>
</body>
[/html]

This was a small tutorial on sliding a popup without using any JQuery UI and making it different from other popups.

UPDATE: CHECK THE NEW DEMO FOR LOAD THE POPUP ON CLICK. THIS WILL NOT LOAD THE POPUP ON LOAD OF PAGE



 

Dec 4, 2011

Simple JQuery Toggle Tutorial | CSS JQuery Slide Toggle

Today I am going to share a very common and easy jquery tutorial with you. A JQuery Slide Toggle function.

.slideToggle() function is used to hide or show matched elements in a sliding effect.

So the basic syntax is

[js]$("div").slideToggle("slow");[/js]

So this was the basic syntax on how to slide toggle a div, now lets start with some real working examples.

So first the basic html code:



[html]
<div id="toggle">
<ul>
<li>Youtube Video Scraping</li>
<div>
Always I wondered to display youtube videos below my posts or for some other purpose. But always had to use some plugins or some complicated scripts. So finally coded for you people a small function which will fetch or scrape...<a href="http://webstutorial.com/youtube-video-scraping-fetch-youtube-video-through-rss/programming/php">Continue reading</a>
</div>
<li>WordPress Multiple Category Search</li>
<div>
Since when I started wordpress, I had a question in my mind, why wordpress doesn’t give multiple search option? I googled a lot, but couldn’t find a plugin or code which exactly works. So finally decided to go more into...<a href="http://webstutorial.com/wordpress-multiple-category-search/content-management-system-cms/wordpress-cms">Continue reading</a>
</div>

<li>Youtube Video Scraping</li>
<div>
Always I wondered to display youtube videos below my posts or for some other purpose. But always had to use some plugins or some complicated scripts. So finally coded for you people a small function which will fetch or scrape...<a href="http://webstutorial.com/youtube-video-scraping-fetch-youtube-video-through-rss/programming/php">Continue reading</a>
</div>

<li>Ten WordPress Useful Functions And Snippets</li>
<div>
Some useful WordPress PHP funtions. Just copy and paste these functions in your themes functions.php file Change the WP Login Logo & URL Link Load JQuery From Google CDN How to remove the WordPress Version Information Remove Default WordPress Meta...<a href="http://webstutorial.com/ten-wordpress-useful-functions/content-management-system-cms/wordpress-cms">Continue reading</a>
</div>

<li>A Good PHP Developer Can Answer This | PHP Test</li>
<div>
PHP developers go through 3 stages in their life Beginner Good Best A beginner PHP coder is some one who just started making some PHP projects in CMS like WordPress, Joomla, Magento and other PHP based CMS. A good PHP... <a href="http://webstutorial.com/good-php-developer-answer-php-test/programming/php">Continue reading</a>
</div>

</ul>
</div>
[/html]


And finally our js


[js]
<script type="text/javascript">
$(document).ready(function() {
$("li").click(function(){
$(this).toggleClass("active");
$(this).next("div").stop('true','true').slideToggle("slow");
});
});
</script>
[/js]

Explanation:

In our basic html layout, we have placed a div exactly next to our li. So we tell the jquery to slide exactly the next div of the current clicked li. If we directly write slideToggle then it will slide all the div's of the current page. In the above js code, we are also using a stop() function. This is essential to use, to avoid multiple clicks on a same li making it to slide for continuous multiple times of sliding.

Here's a working demo of the above code

Sep 11, 2011

JQuery Color Changing Background | JQuery Continous Color Change | JQuery Rainbow

In today's tutorial, I am going to share an easy way to change the background color of a page in infinite loops. In other words, change the background to rainbow.


Concept:The actual logic behind changing the color in infinite loops, is to get infinite colors. So trick is simple, take a RGB pattern and keep on changing the color code. So for that a logic of RGB code is written in jquery.color.js

So the index javascript consists of two major codes.

[html]

var rainbow = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';

[/html]

We are creating a variable named as rainbow and setting its value to rgb(random numbers). They are calculated and by using math.round and math.floor functions, the decimals are removed from it.

The last important thing is to append the color to the background of an HTML element.

[html]
$('#welcome').animate( { backgroundColor: rainbow }, 1000);
[/html]
The most important thing is how to get into infinite loops?????

Simple, within the function declare the same function, which will give us infinite loop.

So the entire javascript function will be.

[html]
<script type="text/javascript">// <![CDATA[
$(document).ready(function() {

spectrum();

function spectrum(){
var rainbow = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';
$('#welcome').animate( { backgroundColor: rainbow }, 1000);
spectrum();
}

});
// ]]></script>
[/html]

Aug 16, 2011

Wordpress JQuery Slide Show | How To Add A Wordpress Jquery Slide Show | Wordpress JQuery Nivo Slider

So finally you reached here in search of adding a slide show in your wordpress site. Why to use flash if jquery can help you.


In this tutorial I am using the NIVO SLIDER.


So lets get started, just follow these simple steps:-


First mainly decide where you want to display this slide show in your blog or site? For this example we will use this slide show in the header, as an image banner.


So first you need to add some files in your theme, just that they don't get mixed up with your other files, we will create a folder in your theme directory, name it as slider, in that folder we will place some css files and images.(Download)
So after completion, your folder structure should be like the below image.
Slider folder


After this you need to add some js files in your folder js, if you don't have any folder named as js, then you can create one and place files into it.(Download)


The two js, files are:




  • jquery.nivo.slider.pack.js

  • jquery-1.6.1.min.js


Then you need to open your theme's header.php file, and paste the following code before wp_head();



[html]
<link rel="stylesheet" href="<?php bloginfo('template_directory'); ?>/slider/default.css" type="text/css" media="screen" />
<link rel="stylesheet" href="<?php bloginfo('template_directory'); ?>/slider/nivo-slider.css" type="text/css" media="screen" />
<link rel="stylesheet" href="<?php bloginfo('template_directory'); ?>/slider/style5.css" type="text/css" media="screen" />

<script type="text/javascript" src="<?php bloginfo('template_directory'); ?>/js/jquery-1.6.1.min.js"></script>
<script type="text/javascript" src="<?php bloginfo('template_directory'); ?>/js/jquery.nivo.slider.pack.js"></script>
<script type="text/javascript">
jQuery(window).load(function() {
jQuery('#slider').nivoSlider();
});
</script>
[/html]

In the above code we are just telling the wordpress theme to pick the necessary style sheets, js files and JQuery.


So here we complete major part of the tutorial, now finally we will just paste some html code to appropriate section in the site.



As in this tutorial I am making a header banner so I ll paste this code in header.php.

[html]
<div class="slider-wrapper theme-default">
<div class="ribbon"></div>
<div id="slider">
<img src="<?php bloginfo('template_directory'); ?>/images/header1.jpg" alt=""/>
<img src="<?php bloginfo('template_directory'); ?>/images/header2.jpg" alt=""/>
<img src="<?php bloginfo('template_directory'); ?>/images/header3.jpg" alt=""/>
<img src="<?php bloginfo('template_directory'); ?>/images/header4.jpg" alt=""/>
<img src="<?php bloginfo('template_directory'); ?>/images/header5.jpg" alt=""/>
</div>
</div>
[/html]
Just in img src tag give your appropriate images location, in this tutorial I have kept the images into images folder of my wordpress theme directory.

You can paste the JQuery code in footer.php file just to avoid the conflict of javascripts.


In This tutorial I am using the header banner size, that is 995X288, so if your slider goes off screen, then you can customize our css files.
This Slider is IE7 compliant.


download

Jul 14, 2011

Wordpress Make A Featured Post Jquery Ticker | Wordpress Make featured Posts

Now a days blogging is very common, every human being wants to have their own blog or website where they can put some useful stuffs, but out of that blogs, there are some important or hot blogs, which we say as featured blogs, if you are wordpress user then why to adopt plugin, where you can create a simple one.
So lets get started.

First decide where you want to display the featured post section, usually it is on the home page. So considering it on home page, we will edit two files in this tutorial.
index.php
header.php

So lets get started with header.php, open that file, and in the head section put this small piece of code

[css]
<style>
#posts-container{ }
#posts-container ul li div{
border: 1px solid #aaaaaa;
background: #ffffff;}
</style>
[/css]

You can see that the style is not fully complete, cause I have left it upto you, so that you can have your own style, but if you leave this also it doesn't matter, cause this will also give the blog a simple and neat looks to featured posts

After styling we will add some javascript code to head section.
Be very careful while adding javascript code, as it may conflict with other js files.

[javascript]
<script type="text/javascript" src="<?php echo get_template_directory_uri(); ?>/js/jquery.vticker-min.js"></script>
<script type="text/javascript">
jQuery(function(){
jQuery('#posts-container').vTicker({
speed: 600,
pause: 3000,
animation: 'fade',
mousePause: true,
showItems: 3
});
});
</script>
[/javascript]

As you can see the $ is been replaced by jQuery just to avoid the conflict.
So the final header code will look something like this:

[html]
<style type="text/css" media="all">
#posts-container{ }
#posts-container ul li div{
border: 1px solid #aaaaaa;
background: #ffffff;}
</style>
<script type="text/javascript" src="<?php echo get_template_directory_uri(); ?>/js/jquery.vticker-min.js"></script>
<script type="text/javascript">
jQuery(function(){
jQuery('#posts-container').vTicker({
speed: 600,
pause: 3000,
animation: 'fade',
mousePause: true,
showItems: 3
});
});
</script>
[/html]

In the above javascript, you can change the attribut as per your need, like speed, animation, on-mouse-over-pause etc etc. You can change it anytime. I have kept the js file into the js folder of the theme, if you are keeping it in any other folder then be sure to edit the code.

This part completes the main jquery.
But the question is how will you select the posts as featured?
For this we can use custom fields.
Add a new custom field in your Add-new or Edit posts page, and replicate the same as in below image
How TO Add Custom Field

Tip: Instead Of Manually Adding one-one custom field, I recommend that you use More Fields Plugin. Which Will help you to have a custom field for all post.

Do the above step for only those posts which you want to display as featured posts.

Now open index.php file and just paste this code just above the if ( have_posts() ) code

[php]
<?php
$key = 'featured';
$themeta = get_post_meta($post->ID, $key, TRUE);
if($themeta == 'no') {
echo 'No Featured Posts';
}
elseif($themeta == 'yes'){
?>
<?php query_posts('meta_key=featured&meta_value=Yes');  ?>
<div style="border:4px solid #666666; -moz-border-radius:5px; -webkit-border-radius:5px; padding:12px; color:#333333;font-weight:bold; background-color:#FFFFE0;">
<h1 style="color:#880000; font-weight:bold; font-size:18px; text-decoration:underline;">Featured Posts:</h1>
<div id="posts-container">
<ul>
<?php while ( have_posts() ) : the_post(); ?>
<li>
<a href="<?php the_permalink() ?>" style="color:#333333;"><?php echo the_title() ?></a>
</li>
<?php endwhile; ?>
</ul>
</div>
</div>

<?php wp_reset_query();

}?>
[/php]

In this code we are taking the posts which has custom field value set to yes for featured, and displaying it in a list format, here I have given the css into the style tag of a div, you can change it any time as per your theme design.  I am also using wp_reset_query just to be sure that it doesn't conflicts with other posts.

This above tutorial is just going to display posts title, but if you also want to display posts content, then just make a small change to the above code, just add the 3 line to the code.

[php]
<li>
<a href="<?php the_permalink() ?>" style="color:#333333;"><?php echo the_title() ?></a>
<br><em><php echo the_excerpt(); ?></em>
</li>
[/php]

You can see the demo on my websites homepage
Demo | Download [download id="3"]

Jul 10, 2011

Best way to include JQuery | Correct way to include JQuery

JQuery is the javascript library, but just copy pasting the JQuery snippet will not do, it will start conflicting with other JQeries, so the best practice is to use the following method

[php]<?php wp_enqueue_script("jquery"); ?>[/php]