আগামী ২৩ অক্টোবর -২০১৭ তারিখ থেকে শুরু হচ্ছে পাঁচ মাস ব্যাপী Professional Web Design and Development with HTML,CSS,Bootstrap,PHP,MySQl, AJAX and JQUERY কোর্সের ৮৬ তম ব্যাচ। আগ্রহীদেরকে অতিসত্বর মাসুদ আলম স্যার এর সাথে যোগাযোগ করতে অনুরোধ করা যাচ্ছে। স্যার এর মোবাইল: 01722817591, Email : [email protected] কোর্সের সিলেবাস এর জন্য এখানে ক্লিক করুন ।

Beginning JQUERY Part-2

Introduction

In previous Tutorial we discuss different methods. But just knowing how these methods work and use them separately is not all, implementing these methods together in a project and make your website awesome is a real challenge.  In this tutorial I will show how to create a different project by using simple jquery methods. In this way you have a solid idea how to create a project that’s  meets demand of your clients. We are going to create a slideshow, vertical dropdown menu, image zoomer, animation and so on. You will be wonder after this tutorial that how we can create a awesome jquery project just using simple methods.

Download source code

Animate method

structure  of animate()

.animate( properties [, duration ] [, easing ] [, complete ] )

Parameters  of animate()

Properties: An object of CSS properties and values that the animation will move toward.

duration (default: 400): A string or number determining how long the animation will run.

Type: miliseconds

easing (default: swing):A string indicating which easing function to use for the transition.

Complete:A function to call once the animation is complete.

Learn more from http://api.jquery.com/animate/

Create a like box

Save the following code as facebook_like_box.html

<!doctype html>

<html>

<head>

<meta charset="utf-8">

<title>Basic Animate</title>

<style type="text/css">

#animation{

background-color:#CCF;

width:300px;

height:200px;

padding:10px;

margin-left:-320px;

display:block;

}

</style>

<script src="js/jquery.js"></script>

<script type="text/javascript" src="js/like_box.js"></script>

</head>

<body>

<div id="animation">

<span id="close">X</span>

<a id="link_id" href="https://www.facebook.com/Ptbnews24" target="_self">Like</a>

<p>This is the first step towards to the animation of the Jquery.This is the first step towards to the animation of the Jquery. </p>

</div>

</body>

</html>

Save the following js file as like_box.js to your js folder

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

setTimeout(function(){

$('#animation').animate({'margin-left':'0px'},5000);

},4000)

$('a').click(function(e){

e.preventDefault();

window.open($(this).attr('href'), '');

});

$('#close').on('click',function(e){

$('#animation').animate({

'opacity':'0.5',

'margin-left':'-350px'

},3000,function(){

$('#animation').hide();

})

});

});//end of document ready function

LIVE DEMO

Explanation: We have a div whose id is animation. By css we hide this box just giving margin-left minus 350px.So it will hide in left top side of webpage. Then this box gradually enters into webpage after 4 seconds because setTimeout function run after 4 seconds from document load. In this function we call animate method which will set margin-left  from -350 to 50 over the time of 5 seconds.

Now Visitor can close the box by click X .When X is clicked we run a click event and inside this we run animate method again which will set margin-left:-350px and make it opacity half over the time of 3seconds.When animation done then a function will run which append a h3 into body.

Load method
Load data from the url  and place the returned HTML into the matched element. laod() takes three parameter.

<a href=”url:where”>url:where</a> to sent request

data : which part of that webpage you want l(ike a specific tag,id or class).

Complete: A function will run when loading complete. Below dropdown menu have perfect example of load method.

Create a vertical dropdown menu

<html>

<head>

<meta charset="utf-8">

<title>Menu</title>

<style>

.menu{

width:250px;

height:auto;

float:left;

}

.item{

border:2px solid red;

background-color:rgba(193,193,255,1);

}

a{

background-color:rgba(0,0,0,1);

color:rgba(255,255,255,1);

display:block;

}

.content{

float:left;

width:500px;

border:1px dashed #FF0000;

}

ul li{       cursor:pointer;}

.active{

color:rgba(255,255,128,1);

font-family:"Lucida Console", Monaco, monospace;

}

</style>

</head>

<body>

<div class="menu">

<a href="#">Asia</a>

<div class="item">

<ul>

<li><a href="bangladesh.html">bangladesh</a></li>

<li><a href="india.html">India</a></li>

<li><a href="pakistan.html">Pakistan</a></li>

</ul>

</div>

<a href="#">Europe</a>

<div class="item">

<ul class="child">

<li><a href="britan.html">Britain</a></li>

<li><a href="france.html">France</a></li>

<li><a href="germany.html">Germany</a></li>

</ul>

</div>

<a href="#">America</a>

<div class="item">

<ul class="child">

<li><a href="usa.html">USA</a></li>

<li><a href="canada.html">Canada</a></li>

</ul>

</div>

</div>

<div class="content">

sdfsd

</div>

<script type="text/javascript" src="../js/jquery.js"></script>

<script type="text/javascript" src="../js/dropdown.js"></script>

</body>

</html>

Save following javascript code as dropdown.js and save into js folder

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

$('.item').hide();

$('.holder').on('click',function(e){

$(this).next('.item').show();

$('.item').not($(this).next('.item')).hide();

$('li a').on('click',function(evt){

var Url=$(this).attr('href');

$('.content').load(Url);

evt.preventDefault();

$(this).addClass('active');

$('li a').not($(this)).removeClass('active');

})

});

});

LIVE DEMO

JQUERY Dropdown

Explanation: we give parent anchor tag a class called holder. When visitor clicked this parent tag box with class item will show up. Second time when visitor click another parent menu immediately, we have to close previously open item. To do that close all item but not current one by using not method. Selector under not method will be out of selection. In item box ,when visitor click page link we prevent default behavior by using preventDefault().To use preventDefault() we have to pass a argument in function like pageX,pageY,which,type. Finally grab clicked anchor tag href and pass this to load method which is responsible to load content for content class from the anchor target page.

On the other side, To make currently clicked anchor active we add a class to current anchor tag and remove active class to others anchor tag but not current one.

 Creating a slideshow with auto generated thumbnails

Save the following html as index.html

<!doctype html>

<html>

<head>

<meta charset="utf-8">

<title>Jquery SLideshow</title>

<link rel="stylesheet" href="style.css">

</head>

<body>

<div class="slider">

<img src="img/flyingbirds.JPG" title="A bird flying over the sea shore.Its amazing scene in nature.">

<img src="img/graps.jpg" title="Forest foods are grown naturally with beautiful taste but nobody there to eat">

<img src="img/horses.jpg" title="Horse was main transport during monarch.">

<img src="img/plant.jpg" title="There are variety of plant in our World.">

<img src="img/spaceship.jpg" title="Science make our life easier and more comfortable day by day">

<img src="img/waterfall.jpg" title="One of the most amazing water fall in Cananda.">

</div>

<div class="controll">

</div>

<script type="text/javascript" src="jquery.js"></script>

<script type="text/javascript" src="myslider.js"></script>

</body>

</html>

Now everything is ready to make slideshow. Lets build a jquery file to run the slideshow. Save below jquery code into myslider.js with your js folder

var counter=0;

$('.slider img').hide();

var imgArr=[];

var imgTitle=[];

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

//Fulfil the imgArr and ImgTitle array by loop over each image

$('.slider img').each(function(index, element) {

var Src=$(this).attr('src');

var Title=$(this).attr('title');

imgTitle[index]=Title;

imgArr[index]=Src;

});

/*create thumbnails for all image in container class div give them a special class which is their index value for further selection*/

for(var thumb=0;thumb<imgArr.length;thumb++){

$('.controll').append('<img src="'+imgArr[thumb]+'"width="150px" height="150px">');

}

function slider(){

//if ocunter is equal to number of image then set counter again 0.So it start again when reach at the end

if(counter==imgArr.length)

{

counter=0;

}

//for giving fading effect to image and its title just hide them

$('.slider div img').hide();

$('.slider p').hide();

/*imgArr is an array with numeric index like 0,1,2,3.Counter will increase each time by one.For that, each time imgArr index will chagne and finally image will change in the slider */

$('.slider div img').attr('src',imgArr[counter]).fadeIn(600);

$('.slider p').text(imgTitle[counter]).delay(1000).fadeIn(500);                   // we add a class to currently showing image thumnail

// below selector is equal to .1 ,.0 and so on.

$('.'+counter).addClass('running');

//remove <b>running</b> class from each image under <b>controll</b> class div but not current image which is showing on slider

$('.controll img').not($('.'+counter)).removeClass('running');

//finally increase the counter

counter++;

}//end of slider function boundary

//now lets make a div to show current image on slider and paragraph tag to show its title

$('.slider').append('<div></div><p></p>');

//create a empty image tag within newly created div under slider class

$('.slider div').append('<img src=#>');

//this slider function will run every 5 seconds.But start after 5 seconds from page load. Remember it runs each 5 seconds after until browser is closed.

setInterval(slider,5000);

/* This setTimeout run once only.To solve setInterval function problem.We run this function after 100 milosedond with is 1/10 of a second.So our slider function start as soon as page load */

setTimeout(slider,100);

});

LIVE DEMO

slideshow

Every section in above jquery are well commented. It is clear enough who things going on. If some part are not clear make a comements below

Create a responsible layout

Let me introduce yourself with few new methods

Height(): return currently selected element or tag total height.

Width(): return currently selected element or tag total width.

Resize(): will run each time when browser is resizing.

Ready(): when browser complete rendering html. After that , this will run.

Save the following code as responsible_layout.html

<!doctype html>

<html>

<head>

<meta charset="utf-8">

<title>Responsible layout</title>

<!-- LOad diffeent layout based on current browser width-->

<link rel="stylesheet" href="#">

</head>

<body>

<h3></h3>

<p>Jquery is most popular javascript library which is used by many web developer for its easy use.</p>

<span></span>

<div class="blank">

</div>

<script type="text/javascript" src="js/jquery.js"></script>

<script type="application/javascript" src="js/responsibe.js"></script>

</body>

</html>

Save the following jquery code as responsible.js to your js folder

// JavaScript Document

$('document').ready(function(e) {

function layout (){

// Get the dimensions of the viewport

var width = $(window).width();

var height = $(window).height();

&nbsp;

$('.blank').html('current browser width is : '+width);// Display the width

$('span').html('current browser height is : '+height); // Display the height

if(width>=500 && width<750)

{

$('link').attr('href','style.css');

$('h3').text('You are now table view');

}

if(width>=750)

{

$('link').attr('href','tablet.css');

$('h3').text('You are Computer view');

}

if(width<=500)

{

$('link').attr('href','mobile.css');

$('h3').text('You are now mobile view');

}

};

$(document).ready(layout);    // When the page first loads

$(window).resize(layout);

});

Explanation: Create a function called layout and write all of our logic inside it. Firstly we have to check window height and width. Then run three if condition to check what is the current width of window. If current width is greater than 750 then we just load style.css file by changing link tag href attribute. Same work is done in table and mobile view.

Finally we run our function first when document is ready or just complete rendering. Then each time browser resize we run our function by using resize method.

Changing the right click on webpage.

Generally, we see a context menu when right click on webpage.  This menu option varies from browser to browser. But instead of context menu we can set our own menu bar by preventing default behavior of browser.

Both of them are property not method and only access by function parameter and will be clear after the example

Evt.which: will tell what key pressed by giving that key code

Evt.type: will tell you what event like click, keyup,  keydown, blur happened.

Save the following code as context_menu.html

<!doctype html>

<html>

<head>

<meta charset="utf-8">

<title>evt</title>

<style type="text/css">

.box{

width:200px;

height:auto;

background-color:rgba(147,201,255,1);

border:3px solid #fff;

box-shadow:0px 0px 10px #000000;

position:absolute;

}

.box ul{margin-left:-40px}

.box ul li{

list-style:none;

border-bottom:1px solid rgba(255,255,255,1);

margin:0px;

padding-left:10px;

}

.box ul li:hover{

background-color:rgba(255,255,255,1);

color:rgba(51,51,51,1);

cursor:pointer;

}

</style>

</head>

<body>

<h3>Learn Jquery</h3>

<p>Jquery is most <a href="www.gogle.com">popular</a> javascript library which is used by many web developer for its easy use.</p>

<span></span>

<div class="blank">

</div>

<div class="box">

<ul>

<li>Copy</li>

<li>Paste</li>

<li>Move</li>

<li>Edit</li>

<li>delete</li>

<li>Undo</li>

</ul>

</div>

<script type="text/javascript" src="js/jquery.js"></script>

<script type="application/javascript" src="js/contexmenu.js"></script>

</body>

</html>

Save the following code as contexmenu.js

$('.box').hide();

$('document').ready(function(et) {

$(document).on('mousedown',function(e){

document.oncontextmenu=function(){return false};

if(e.which===3)

{

$('.box').show().css({

'left':e.pageX,

'top':e.pageY

});

}

$('.box').on('mouseleave',function(){

$('.box').hide();

})

})

});

LIVE DEMO

jqueryRight Button

Explanation: When mouse down we run an anonymous function. First of all use JavaScript oncontextmenu method and this will run an anonymous function which  return false. That will prevent showing context menu on browser when user right click on mouse. Now its time to check right or left mouse click.right click keyCode is 3. So when right click e.which value will 3.If so, show our custom context menu. we set our context menu box position absolute to show below the cursor where mouse right button clicked. To accomplish that grab the current mouse pointer position and set as left and top value of that context menu box.

Finally, hide our context menu when move leave from context menu box.

Give a confirm message when attempt to close browser tab

Do you want to give user a confirm message to an important web page when they are closing it. If so then use javascript   onbeforeunload().

This method work only when try to close web page. Add the following code to any webpage to  show an confirm message before close.

<script type="text/javascript">

//this is partial javascript code.You use this piece of code into  any jquery or //javascript   methods or functions

window.onbeforeunload = function() {

var message = 'Do you want to leave this page?';

return message;

</script>

LIVE DEMO

confirm before close

Prevent coping your page content

Just add this piece of code to your webpage to prevent copy content.

 <script type="text/javascript">

document.oncopy = function() {

var bodyEl = document.body;

var selection = window.getSelection();

selection.selectAllChildren(document.createElement('div'));

}

</script>

You can make your webpage secure by preventing default context menu and copy. This two option are very helpful when you creating a exam system where examinee should not copy question from webpage. So they cannot search it to Google and other search engine for answer. Moreover, they also unable to view page source normally. That would be the practical use of two techniques.

Until now you may have a solid idea how to write jquery and javascript code to fulfill website demand. Now I am showing you some ready product. They are javascript libraray. All you have to do just know to use them.

Jquery UI

It would nice if we can make a slideshow or menu bar just calling a method like menu().Yes Jquery UI gives you that opportunity. Go to www.jqueryui.com

From left side in home page you see different option like Dragable,Dropable and many more. Choose your desire item and you will see demo followed  view source.Copy the source or see what method they call from jquery-ui

Go to http://jqueryui.com/menu/ and from footer copy jquery-ui cdn. You must have jquery library prior to jquery-ui cdn. You can  also use jquery-ui themes.But it optional.

Like Jquery UI there are other site you can get similar ready product for your webpage.

http://www.jeasyui.com/

http://www.jqwidgets.com/

http://jquery.malsup.com/cycle2/demo/

http://jquery.malsup.com

http://learn.jquery.com/plugins/

Go these website and watch demo if nice then use in your webpage following their instruction.Again you do not write any javascript code for this just know which method you have to call.

Google form validation

Gvalidate is a powerful and nice way of validate client side form.It have nice features. Download gvalidator and see examples and learn from there how to use in your form. Just add gvalidator.js into your web page and its ready to validate your form.Do not forget to add gform class on form tag.You have to add class into input field based on your requirement. See the below example carefully.

 <!doctype html>

<html>

<head>

<meta charset="utf-8">

<title>Google Form validation</title>

</head>

&nbsp;

<body>

<h1>GValidator Example</h1>

<p>Fields marked with a <span class="required">*</span> are required.</p>

<form action="" method="post" id="autoform" >

<div><label for="firstname">First Name</label><input type="text" name="firstname"  id="firstname" maxlength="30"></div>

<div><label for="lastname">Last Name</label><input type="text" name="lastname" id="lastname" maxlength="30"></div>

<div><label for="password">Password</label><input type="password" name="password" id="password" maxlength="32"></div>

<div><label for="confirmpassword">Confirm Password</label><input type="password" name="confirmpassword" class="confirmpassword required" id="confirmpassword" maxlength="32"></div>

<div id="submitdiv"><input id="submit" type="submit"><input type="reset"></div>

</form>

<script type="text/javascript" src="gvalidator/js/gvalidator.js"></script>

</body>

</html>
 

Now are are no more beginner in jquery.You learn how to create menu bar,slideshow and other.Now you have solid knowledge to build any jquery plugin for your website.In the next tutorial we discuss jquery ajax methods and their implementation in real life.

Hi,I am Tuhin Bepari from Bangladesh. I am a freelancer since 2011 working on odesk. I am not from Computer science background. But my passion about web programming make me a web developer. I am self motivated and always try to update with latest technology in my field.Now I am working on Yii Framework and Mongo DB.I have two other blog one is higher php and another is learn html5.

Leave a Reply

Your email address will not be published. Required fields are marked *