Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

Friday, May 9, 2014

Multiple File upload with Ajax

Sry Guyz for the late post. I was out of station thats why and my gf my computer was not with me but now I Am Back. In this post we i will show how to create a awsm Multiple File upload with percentage and results with ajax. So get Started.

Live Demo Watch Video Tutorial Download Script

html

markup for this is very simple we are just using a <form> with <input type="file"> and Submit button and we have give the multiple attribute to the file so that the user can select multiple file. We have created 3 empty div for putting result via javascript
<form action="upload.php" method="post" enctype="multipart/form-data">
 <fieldset>
  <legend>File upload</legend>
  <input type="file" name="file[]" id="file" multiple required/>
  <input type="submit" name="upload" id="upload"/>

  <div id="per"></div>
  <div id="sucess"></div>
  <div id="error"></div>
 </fieldset>
</form>

php

In this php script we are getting the file from the html file and checking it if the file is valid we r uploading the file and stroing it in a array else we are storing the error message in a array and in last we are encoding the success and error array into json format
<?php
header('Content-Type: application/json');

//function to get the extension of the file
function getExt($name){
 $array = explode(".", $name);
 $ext = strtolower(end($array));
 return $ext;
}

//create global array
$allowed = array('gif', 'png', 'jpg');
$success = array();
$error = array();

if(isset($_FILES['file']) && !empty($_FILES['file'])){
  foreach ($_FILES['file']['name'] as $key => $name) {
   $tmp = $_FILES['file']['tmp_name'][$key];
   $ext = getExt($name);
   $size = $_FILES['file']['size'][$key];

   // check the extension is valid or not
   if(in_array($ext, $allowed) == true){
    $filename = md5($name) . time() .'.'.$ext;
    //check the size of the file
    if($size <= 2097152){
     if(move_uploaded_file($tmp, 'uploads/'.$filename) === true){
      $success[] = array('name' => $name, 'location' => 'uploads/'.$filename);
     }else{
      $error[] = array('name' => $name, 'msg' => 'File is not uploaded');
     }
    }else{
     $error[] = array('name' => $name, 'msg' => 'File size more than 2MB');
    }
   }else{
    $error[] = array('name' => $name, 'msg' => 'File Type not allowed');
   }
  }
  
  //encode the result in json format
  $json = json_encode(array(
   'success' => $success,
   'error' => $error
  ));

  echo $json;
  exit();
}
?>

javascript

we are sending a XMLHttpRequest to the server and displaying the response given by the upload.php page back to the user in empty div which we have created earlier 
<script type="text/javascript">
 var form = document.querySelector('#upload'),
   fileToUpload = document.querySelector('#file'),
  button = document.querySelector('#submit'),
  per = document.querySelector('#percentage'),
  sucessDiv = document.querySelector('#success'),
  errorDiv = document.querySelector('#failed'),
  sucessMarkup = '',
  errorMarkup = '';

 form.addEventListener('submit', function(e){
  e.preventDefault();

  var files = fileToUpload.files;

  var formdata = new FormData();

  //loop throught all the files

  for (var i = 0; i < files.length; i++) {
   var file = files[i];

   formdata.append('file[]', file);
  }

  var xhr = new XMLHttpRequest();
  xhr.open('POST', 'upload.php');

  xhr.addEventListener('readystatechange', function(){
   if(xhr.readyState === 4){
    if(xhr.status === 200){
     var uploaded = JSON.parse(xhr.response);
     //put the json response to the div
     //success files 
     for(var i = 0; i < uploaded.success.length; i++){
      var name = uploaded.success[i].name;
      var location = uploaded.success[i].location;

      sucessMarkup += "<a href='view.php?id="+location+"' target='_blank'>"+name+"</a>";
     }

     //error file

     for (var i = 0; i < uploaded.error.length; i++) {
      var name = uploaded.error[i].name;
      var msg = uploaded.error[i].msg;

      var errorH1 = document.createElement('h2');
      errorH1.innerHTML = 'Unfortunately '+uploaded.error.length+' files are not uploaded';
      errorDiv.appendChild(errorH1);
      errorMarkup += '<p>'+name+' - '+msg+'</p>';
     };
     
     //put the results in the div
     sucessDiv.innerHTML = sucessMarkup;
     errorDiv.innerHTML = errorMarkup;
    }
   }else{
    console.log('error');
   }
  }, false);
 
  //code for showing the upload percenatge
  xhr.upload.addEventListener('progress', function(e){
   if(e.lengthComputable === true){
    var per = Math.round((e.loaded / e.total) * 100);
    percentage.innerHTML = per + '% uploaded';
   }
  })

  
  xhr.send(formdata);

 }, false);
</script>

Sunday, April 27, 2014

Create jQuery like fadeIn animation with javascript

Hi Guyz in this tutorial i am going to teach u how to create a jQuery like fadeIn() animation with javascript

html

html is Super easy in this we have a div and a button. And when we click the button div is fadeIn()
<button id="button">Click me</button>
<div id="div">a</div>

css

In css we are styling the div so that we can see it and giving it the property of display:none; so that it will be shown dynamicaly
<style type="text/css">
#div{
	background: cornflowerblue;
	height: 150px;
	width: 200px;
	padding: 10px;
	display: none;
}
</style>

javascript

The main role is of javascript and all the work is done by the javascript and we fire of the fadeIn() function and that function do the work
<script type="text/javascript">
	var btn = document.getElementById('button');
	btn.addEventListener('click', function(){
		var i = 0,
			el = document.getElementById('div');
		fadeIn(el, i);
	}, false);

	function fadeIn(el, i){
		el.style.display = 'block';
		i = i + 0.01;
		setOp(el, i);

		if(i<1){
			setTimeout(function(){
				fadeIn(el, i);
			},50);
		}
	}

	function setOp(el, i){
		el.style.opacity = i;
	}
</script>

Tuesday, February 25, 2014

Custom html5 video player with JavaScript

In this post we are going to create a custom html5 video player with JavaScript. at 24/2/2014 i got a mail from a reader to explain the html5 video api the funny thing is that i was knowing less about a html5 video api with javascript that why i decided to rub my hands on video api and read a article on w3school about HTML Audio/Video DOM Reference and created a custom html5 video player and now its ready to rock and roll the web
Custom html5 Video Player With JavaScript

Download Script View Demo 

Why Their is a need of a custom video player?

The problem is that every browser develop its own video player and unfortunately they are different from each other. to show same user experience around cross browser we have to create a custom video player.
Native browser video controls across different browsers

html

html is super easy u just need to wrap the <video> tag in a <div> and put some additional divs after the <video> tag to make video controls sounds little bit confusing wait i show the code
<div id="video_container">
 <video load="metadata" id="my_vid" width="550" height="320">
  <source src="http://www.w3schools.com/tags/mov_bbb.mp4" type="video/mp4"></source>
 </video>
 <div id="video_control">
  <button id="playpause">play</button><!--play pause button-->
  <input id="seekbar" class="bar" type="range" min="0" max="100" value="0" step="1"><!-- seekSlider -->
  <span id="currentTimeText">0:00</span> / <span id="durationTimeText">0:00</span><!-- video time display -->
  <button id="mute">mute</button><!-- mute button-->
  <input id="volumeBar" class="bar" type="range" min="0" max="100" value="100" step="1"><!--volume control -->
  <button id="fullScreenBtn" title="fullscreen">[  ]</button><!-- fullscreen -->
 </div>
</div><!--main video wraper-->

JavaScript

the main thing is javascript you can control the video behaviour via JavaScript api to learn more visit HTML Audio/Video DOM Reference
//create golbal variables of the video controls ======================//
 var playbtn,
   seekbar,
   vid,
   currentTimeText,
   durationTimeText,
   muteBtn,
   volumeBar,
   fullScreenBtn;

 function GetPlayerReady(){
  //set object referance of video control ======================//
  vid = document.getElementById('my_vid');
  seekbar = document.getElementById('seekbar');
  playbtn = document.getElementById('playpause');
  currentTimeText = document.getElementById('currentTimeText');
  durationTimeText = document.getElementById('durationTimeText');
  muteBtn = document.getElementById('mute');
  volumeBar = document.getElementById('volumeBar');
  fullScreenBtn = document.getElementById('fullScreenBtn');

  //add event listener ======================//
  playbtn.addEventListener('click', playPause, false);
  seekbar.addEventListener('change', vidSeek, false);
  vid.addEventListener('timeupdate', seekTimeUpdate, false);
  muteBtn.addEventListener('click', vidMute, false);
  volumeBar.addEventListener('change', changeVolume, false);
  fullScreenBtn.addEventListener('click', fullScreen, false);
 }

 window.onload = GetPlayerReady; //call the main function when document is loaded

 //play pause function ======================//
 function playPause(){
  if(vid.paused){
   vid.play();
   playbtn.innerHTML = 'pause';
  }else{
   vid.pause();
   playbtn.innerHTML = 'play';
  }
 }

 //video seek slider function ======================//
 function vidSeek(){
  var seekTo = vid.duration * (seekbar.value / 100);
  vid.currentTime = seekTo;
 }

 //video time display function ======================//
 function seekTimeUpdate(){
  var newTime = (vid.currentTime / vid.duration) * 100;
  seekbar.value = newTime;
  //currentTime & duration display//
  var curSec = Math.floor(vid.currentTime / 60);
  var curMin = Math.floor(vid.currentTime - curSec * 60);
  var durSec = Math.floor(vid.duration / 60);
  var durMin = Math.floor(vid.duration - durSec * 60);
  if(curSec < 10){
   curSec = "0"+curSec;
  }
  if(curMin < 10){
   curMin = "0"+curMin;
  }
  if(durSec < 10){
   durSec = "0"+durSec;
  }
  if(durMin < 10){
   durMin = "0"+durMin;
  }
  currentTimeText.innerHTML = curSec+":"+curMin;
  durationTimeText.innerHTML = durSec+":"+durMin;
 }

 //mute function ======================//
 function vidMute(){
  if(vid.muted){
   vid.muted = false;
   muteBtn.innerHTML = 'mute';
   volumeBar.value = 100;
  }else{
   vid.muted = true;
   muteBtn.innerHTML = 'unmute';
   volumeBar.value = 0;
  }
 }

 //volume bar function ======================//
 function changeVolume(){
  vid.volume = (volumeBar.value / 100);
 }

 //full screen fnction ======================//
 function fullScreen(){
  if(vid.requestFullScreen){
   vid.requestFullScreen();
  }else if(vid.webkitRequestFullScreen){
   vid.webkitRequestFullScreen();
  }else if(vid.mozRequestFullScreen){
   vid.mozRequestFullScreen();
  }else{
   alert('Your Browser Does Not Support Fullscreen');
  }
 }


css

we are using css to make the video control pretty. i have not focused on making the control pretty because i was not having time but in next post i will make a jQuery plugin which u can include easily
div#video_container{width: 550px;background: #000;margin:0 auto;}
 div#video_control{background: #333;padding: 10px;color: #ccc;}
 input#seekbar{width: 180px;}
 input#volumeBar{width: 80px;}
 .bar{
  -webkit-appearance:none !important;
  -moz-appearance:none !important;
  appearance: none !important;
  background: #000;
  border: #666 1px solid;
  height: 5px;
  outline: none;
 }
 .bar::-webkit-slider-thumb{
  -webkit-appearance:none !important;
  -moz-appearance:none !important;
  appearance: none !important;
  background: #fff;
  height: 15px;
  width: 15px;
  border-radius: 100%;
 }
 .bar::-webkit-slider-thumb:hover{
  cursor: pointer;
  opacity: 0.7;
 }
 .bar::-moz-slider-thumb{
  -webkit-appearance:none !important;
  -moz-appearance:none !important;
  appearance: none !important;
  background: #fff;
  height: 15px;
  width: 15px;
  border-radius: 100%;
 }
 .bar::-moz-slider-thumb:hover{
  cursor: pointer;
  opacity: 0.7;
 }

Like Us on Facebook / Add Hunk As Friend


Sunday, February 23, 2014

Image Rotator with jQuery & JSON

In this post i am going to create a image rotator with jQuery and JSON for this i am using a logic less template libraries Mustache.js which get the data from the external JSON file and a jQuery plugin cycle.js which rotate the data
Image Rotator with jQuery and JSON

Download Script View Demo 

html

html is very simple in html we have a main div a rotaor div in this div all the data from the json file will be feeded. we have 2 a tag which acts like next and previous button
<div id="main">
 <a href="#" id="prev_btn" class="btn">&laquo;</a>
        <a href="#" id="next_btn" class="btn">&raquo;</a>
 <div id="rotaor">
 </div>
</div>

JavaScript

javascript has very less code in simple word we are getting the data from the json file via jQuery and formatting the data with mustache.js and creating the rotator with cycle.js plugin
<!--formating the data fetched from the json file with mustache.js start-->
 <!--mustache.js template code-->
 <script type="text/template" id="mustacheTemplate">
 {{#hunklessons}}
  <div id="info">
  <h3>{{name}}</h3>
  <img src="{{photo}}" style="height:100px;" alt="image of {{name}}">
  </div>
 {{/hunklessons}}
 </script>
 <!--formating the data fetched from the json file with mustache.js end-->
 <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.0/jquery.js"></script>
 <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery.cycle/3.03/jquery.cycle.all.min.js"></script>
 <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/mustache.js/0.7.2/mustache.js"></script>
 <script type="text/javascript">
 $(document).ready(function(){
  $.getJSON('hunklessons.json', function(data){//get the data from json file
   var temp = $('#mustacheTemplate').html(); //target the mustache.js template code
   var html = Mustache.to_html(temp, data);//using mustache.js to_html function to match template from the json data
   $('#rotaor').html(html);//put the data to the rotaor div

   $('#rotaor').cycle({ //using cycle.js plugin
    fx: 'fade',
    pause: 1,
    next: '#nxt_btn',
    prev: '#prev_btn',
    speed: 500,
    timeout: 1000
   });
  });
 });
 </script>

json

{"hunklessons":[
 {
  "name":"husain saify",
  "photo":"http://lh5.googleusercontent.com/-oqoAWmCo7CA/AAAAAAAAAAI/AAAAAAAAAPk/osoYaXlwlxI/s512-c/photo.jpg"
 },
 {
  "name":"hunk lessons",
  "photo":"https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEigZ8Dc5YPz139SECKcfjInGQJRj_hfp1rgwKJYlRzkms6E8K8hMKamhYkBAX7bOH25PJq1b71nLnN8XR9IvN4L7Nob-LKAmEKP789o5rXK-PshLR4PynBOCslR_LeCfoEIE3YuxOWYgwOT/s1600/hunlessonslogo.png"
 },
 {
  "name":"Embed Youtube Videos With JavaScript",
  "photo":"https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi_j54IvA7Aq33ki6M3434urcid27n0ClRiqmBMM8vMYCDN5ridXXSD0G9a7XjN8Fat-aK_9zinWWH2kkjoWRAK-ZzVW8apBEPXFyIJZnIXaOtW2Oab9Aj1eyI10c_LUX8IUju6axtlNzYC/s1600/embed-yt-videos.png"
 },
 {
  "name":"Drag and Drop Game With html5 & javascript",
  "photo":"https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEilI4aVbre0Eb3XiyTw-OgU4zpKCZn3biRSMOwpEENgAUjNQDtKXEO7u6SAWvZrowC7dLaiVNFp_2RgETn8lcU2Hrk3q7B0lYOL3xc6Uql4xVLofm2Rm6RcqtWxFVIkmRVzLu10rMEtivdM/s1600/dragndropgame.png"
 },
 {
  "name":"Css3 Progress Bar",
  "photo":"https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhi2C5B0K11byBRwxtZf16Pyvoib-Iuurh65LTBZniZNlli-4hqB7Zom8xMNZJtV7XoKCUqZGv5E9LdQst61c-5C7r_zRks1CimgyUEg6xn8aJR2BXK4KhEjw_xI4hhZV5FCZ7dwp9UlnRD/s1600/cssprogressbar.png"
 },
 {
  "name":"jQuery Username Availability check",
  "photo":"https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhK4STXWSx7wncxFrAvo6C5kzbqP3L0NBWjE1HdDVcKdNMem9aBeBiKtxCiyIqtHraMMoapeInyVRcNGBajUoa_Y86j82oGyyCyHqSZsOxS_JTYYDbWE6P4ppenZhUSivnbdhf9zhT-JmwJ/s1600/username+available.png"
 },
 {
  "name":"Select And Upload Multiple Images With jQuery & Ajax",
  "photo":"https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi31ZFckzzjR2X33q0m5HhqCQr8jWYO8dfDdVBq-ZdhYnYxlM-4f_WElDsSB3ow_obcsS7soAuAkcQMzrC5UG9qUFzEe7F-tGZPY9pXRxtg5i5B2CbJGF3agXsu8uE3P_Q_zUY9Wcz1zWz0/s1600/selectanduploadmultipleimaes.png"
 },
 {
  "name":"hunk husain",
  "photo":"http://lh5.googleusercontent.com/-oqoAWmCo7CA/AAAAAAAAAAI/AAAAAAAAAPk/osoYaXlwlxI/s512-c/photo.jpg"
 }
]}

Like Us on Facebook / Add Hunk As Friend





Thursday, February 20, 2014

Embed Youtube Videos With JavaScript

Guyz i got a request from a reader to make a post for dynamic youtube video embed script so its here. Embed youtube videos is very easy the main thing is a key(id) which i will be explaining up next.
Embed Youtube Videos
Embed Youtube Videos

Download Script View Demo 

what is key(id)

in simple words it is the id and every video has is separate id. And this id make every video differnet from each other 
key

html

html has nothing interesting in it. Their is a form with a textarea and a submit button and a preview div where videos are displayed
<div id="wrapper">
  <h3>Embed youtube videos</h3>
  <form action="yt.php" method="post" id="yt_form">
   <textarea id="yt-link" name="yt" placeholder="For ex-: http://www.youtube.com/watch?v=6Ai6K2VIEXM" required></textarea>
   <input type="submit" value="upload" name="upload">
   <div id="feedback"></div>
  </form>
  <div id="preview"></div>
 </div>

CSS

body{
 background: #ccc;
}
#wrapper{
 width: 500px;
 height: 100%;
 border: 1px solid #eee;
 margin-left: auto;
 margin-right: auto;
 top: 0;
 padding: 5px;
 background: #eee;
 box-shadow: 1px 0px 3px #000;
}
#feedback{
 height: 20px;
 width: 435px;
 float: right;
 text-align: center;
 color: black;
 font-family: verdana;
}
textarea{
 width:490px;
 height:40px;
 max-width: 490px;
 height: 40px;
}

JavaScript

in JavaScript file we taking the youtube url from the textarea and matching it with the regular experation and breaking the url and getting the key from the url.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript">
//select the form
document.querySelector('#yt_form').addEventListener('submit', function(e){
e.preventDefault();//prevent the form from submiting
var url = e.target[0];//select the textarea
var feedback = document.querySelector('#feedback'); //select the feedback div
var parse_url = /^(https?:\/\/)?(www\.)?youtube\.com\/watch(.*?)v=([^#&$]*)/; //pattern to match the youtube url
var parts = parse_url.exec(url.value);
 if(parts){
  var key = parts[4]; //video id
  var embedUrl = '<div><iframe width="500" height="300" src="//www.youtube.com/embed/'+key+'?feature=player_detailpage" frameborder="0" allowfullscreen></iframe></div>';
  $('#preview').append(embedUrl);
 }else{
  feedback.innerHTML = 'Wrong Url';
 }
}, false);
</script>

Like Us on Facebook / Add Hunk As Friend


Tuesday, February 18, 2014

Drag and Drop Game With html5 & javascript


In this post i am going to teach how to create a Drag & Drop Game with Html5 and javaScript. It is very easy and Quite Interesting to create so i stop talking get started
Drag and Drop Game

Download Script View Demo 

html

html is super easy one thing to keep in mind is that the element you wanted to be draggable should be set as draggable="true"

<img src="./salman.png">
<img draggable="true" src="./shirt1.png" style="top:30px; position: absolute;z-index:5px;">
<img draggable="true" src="./shirt2.png" style="top:240px; position: absolute; left:600px;absolute;z-index:5px;">
<img draggable="true" src="./shirt3.png" style="top:240px; position: absolute;absolute;z-index:5px;"> 
<img draggable="true" src="./shirt4.png" style="top:30px; position: absolute; left: 600px;absolute;z-index:5px;">

css

Their is nothing in special in css just we are setting the cursor to move
[draggable]{
    cursor: move;
}

JavaScript

The main thing is JavaScript in the file we are controlling the drag and drop events
var x = '';
var y = '';
var shirt = '';

function dragOver(e){
 e.preventDefault();
}

function dragStart(e){
 shirt = e.target;//select the shirt

 if(e.offsetX === undefined){//get the x & y of the image
  x = e.layerX;
  y = e.layerY;
 }else{
  x = e.offsetX;
  y = e.layerY;
 }

 shirt.style.zIndex = 10;//set the image above the all
 shirt.style.opacity = '0.4'; //set image opacity 40%

 //when drag end remove image opacity
 shirt.addEventListener('dragend', function(){
  shirt.style.opacity = '1';
 }, false);
}


function dropHandler(e){
 e.preventDefault();
 //postion the shirt
 shirt.style.left = e.pageX - x + 'px';
 shirt.style.top = e.pageY - y + 'px';
}

document.querySelector('body').addEventListener('dragstart', dragStart, false);//when drag start
document.querySelector('body').addEventListener('dragover', dragOver, false);//when drag end
document.querySelector('body').addEventListener('drop', dropHandler, false);//when the image is drop


Like Us on Facebook / Add Hunk As Friend