Showing posts with label jquery. Show all posts
Showing posts with label jquery. Show all posts

How to use jQuery events on content loaded via AJAX

I am working on a project, where I have to perform some jQuery/Ajax events on contents loaded via Ajax.
I have search on Google and found a solution which is working for me. I am sharing it with you.

May be it would be helpful for you.


jQuery selectors select matching elements that exist in the DOM when the code is executed, and don't dynamically update. When you call a function, such as .click() to add event handler(s), it only adds them to those elements. When you do an AJAX call, and replace a section of your page, you're removing those elements with the event handlers bound to them and replacing them with new elements. Even if those elements would now match that selector they don't get the event handler bound because the code to do that has already executed.

Event handlers

Specifically for event handlers (i.e. .click()) you can use event delegation to get around this. The basic principle is that you bind an event handler to a static (exists when the page loads, doesn't ever get replaced) element which will contain all of your dynamic (AJAX loaded) content. You can read more about event delegation in the jQuery documentation.

For your click event handler, the updated code would look like this:

$(document).on('click', "#click", function () { 
$('#click').css({       
"background-color": "#f00",        "color": "#fff",        "cursor": "inherit"    
}).text("Open this window again and this message will still be here.");    
return false; 
});

That would bind an event handler to the entire document (so will never get removed until the page unloads), which will react to click events on an element with the id property of click. Ideally you'd use something closer to your dynamic elements in the DOM (perhaps a <div> on your page that is always there and contains all of your page content), since that will improve the efficiency a bit.

Please share on you social sites, if you found it useful.
Thanks
Read More

WebGL with Three.js tutorial and demo

Hello freinds in this tutorial we will be working with sprites and texture animation. If you do not know, sprites are simply images, that could be attached to objects. These sprite images are always orthogonal to our camera.

Three.js provides a special material for the sprites – THREE.SpriteMaterial, as well as a special object – THREE.Sprite. Also in this tutorial we will learn how to play the animation using sprites.

Check this tutorial : How to make a Virtual Reality 3D Tracking headset

Demo

Preparation

As usual, we have to prepare a small index.html file with necessary html markup to work on:

index.html

<!DOCTYPE html>
<html lang="en" >
  <head>
    <meta charset="utf-8" />
    <meta name="author" content="Script Tutorials" />
    <title>WebGL With Three.js - Sprites and Texture Animation | S2P Tech</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <link href="css/main.css" rel="stylesheet" type="text/css" />
  </head>
  <body>
    <script src="js/three.min.js"></script>
    <script src="js/THREEx.WindowResize.js"></script>
    <script src="js/OrbitControls.js"></script>
    <script src="js/stats.min.js"></script>
    <script src="js/script.js"></script>
    <div style="position: absolute; top: 10px; left: 20px; text-align: center;"><a href="http://s2ptech.blogspot.com/2015/05/webgl-with-threejs-tutorial-and-demo.html" target="_blank">"WebGL With Three.js Tutorial"</a> is prepared by <a href="http://www.s2ptech.com/" target="_blank">S2P Tech</a> team.<br>Drag to spin</div>
  </body>
</html>
In this code, we connect the main Three.js library and few additional utilites: WindowResize event handler, Orbit controls and Stats

File Explorer and Download File

Preparation of the main webgl scene

Now let’s create the main ‘script.js’ file and place the code shown below:

Check this tutorials : How to add multiple recaptcha on same page

script.js

var lesson8 = {
  scene: null,
  camera: null,
  renderer: null,
  container: null,
  controls: null,
  clock: null,
  stats: null,
  anim1: null, anim2: null, // animations
  animReady1: false, animReady2: false,
  init: function() { // initialization
    // create main scene
    this.scene = new THREE.Scene();
    this.scene.fog = new THREE.FogExp2(0xcce0ff, 0.0003);
    var SCREEN_WIDTH = window.innerWidth,
        SCREEN_HEIGHT = window.innerHeight;
    // prepare perspective camera
    var VIEW_ANGLE = 60, ASPECT = SCREEN_WIDTH / SCREEN_HEIGHT, NEAR = 1, FAR = 1000;
    this.camera = new THREE.PerspectiveCamera(VIEW_ANGLE, ASPECT, NEAR, FAR);
    this.scene.add(this.camera);
    this.camera.position.set(100, 0, 0);
    this.camera.lookAt(new THREE.Vector3(0,0,0));
    // prepare webgl renderer
    this.renderer = new THREE.WebGLRenderer({ antialias:true });
    this.renderer.setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
    this.renderer.setClearColor(this.scene.fog.color);
    this.renderer.shadowMapEnabled = true;
    this.renderer.shadowMapSoft = true;
    // prepare container
    this.container = document.createElement('div');
    document.body.appendChild(this.container);
    this.container.appendChild(this.renderer.domElement);
    // events
    THREEx.WindowResize(this.renderer, this.camera);
    // prepare controls (OrbitControls)
    this.controls = new THREE.OrbitControls(this.camera, this.renderer.domElement);
    this.controls.target = new THREE.Vector3(0, 0, 0);
    this.controls.maxDistance = 3000;
    // prepare clock
    this.clock = new THREE.Clock();
    // prepare stats
    this.stats = new Stats();
    this.stats.domElement.style.position = 'absolute';
    this.stats.domElement.style.left = '50px';
    this.stats.domElement.style.bottom = '50px';
    this.stats.domElement.style.zIndex = 1;
    this.container.appendChild( this.stats.domElement );
    // add lights
    this.scene.add( new THREE.AmbientLight(0x606060) );
    var dirLight = new THREE.DirectionalLight(0xffffff);
    dirLight.position.set(200, 200, 1000).normalize();
    this.camera.add(dirLight);
    this.camera.add(dirLight.target);
    // display skybox
    this.addSkybox();
    // display animated objects
    this.addAnimatedObjects();
  },
  addSkybox: function() {
      // define path and box sides images
      var path = 'skybox/';
      var sides = [ path + 'sbox_px.jpg', path + 'sbox_nx.jpg', path + 'sbox_py.jpg', path + 'sbox_ny.jpg', path + 'sbox_pz.jpg', path + 'sbox_nz.jpg' ];
      // load images
      var scCube = THREE.ImageUtils.loadTextureCube(sides);
      scCube.format = THREE.RGBFormat;
      // prepare skybox material (shader)
      var skyShader = THREE.ShaderLib["cube"];
      skyShader.uniforms["tCube"].value = scCube;
      var skyMaterial = new THREE.ShaderMaterial( {
        fragmentShader: skyShader.fragmentShader, vertexShader: skyShader.vertexShader,
        uniforms: skyShader.uniforms, depthWrite: false, side: THREE.BackSide
      });
      // create Mesh with cube geometry and add to the scene
      var skyBox = new THREE.Mesh(new THREE.BoxGeometry(500, 500, 500), skyMaterial);
      skyMaterial.needsUpdate = true;
      this.scene.add(skyBox);
  }
};
// animate the scene
function animate() {
  requestAnimationFrame(animate);
  render();
  update();
}
// update controls and stats
function update() {
  var delta = lesson8.clock.getDelta();
  lesson8.controls.update(delta);
  lesson8.stats.update();
}
// Render the scene
function render() {
  if (lesson8.renderer) {
    lesson8.renderer.render(lesson8.scene, lesson8.camera);
  }
}
// Initialize lesson on page load
function initializeLesson() {
  lesson8.init();
  animate();
}
if (window.addEventListener)
  window.addEventListener('load', initializeLesson, false);
else if (window.attachEvent)
  window.attachEvent('onload', initializeLesson);
else window.onload = initializeLesson;
This code creates a basic scene with renderer, camera, controls, lights, stats and skybox. Similar code you already saw earlier in previous lessons. There is nothing new.

Sprites

As mentioned earlier, sprites are (two-dimensional) images, which are orthogonal (perpendicular) to our camera. Now let’s add the sprites to our scene with the following function:
addAnimatedObjects: function() {
  var texture1 = new THREE.ImageUtils.loadTexture('images/sprite1.png', undefined, function() {
    var material1 = new THREE.SpriteMaterial( { map: texture1, useScreenCoordinates: false, side:THREE.DoubleSide, transparent: true } );
    var mesh1 = new THREE.Sprite(material1);
    mesh1.position.set(0, 0, -40);
    mesh1.scale.set(64, 64, 1.0);
    lesson8.scene.add(mesh1);
  });
  var texture2 = new THREE.ImageUtils.loadTexture('images/sprite2.png', undefined, function() {
    var material2 = new THREE.SpriteMaterial( { map: texture2, useScreenCoordinates: false, transparent: true } );
    var mesh2 = new THREE.Sprite(material2);
    mesh2.position.set(0, 0, 40);
    mesh2.scale.set(24, 46, 1.0);
    lesson8.scene.add(mesh2);
  });
}
This code loads two textures (sprite1.png and sprite2.png). After both images are loaded, we create two sprite materials and the Sprite object, and add them to our scene. If you run the code now, you will see two two-dimensional images on our scene. As you may have noticed, the images are drawn as is – we see a lot of small images (tiles) – these image files were taken due to the fact that we will use these tiles to do the animation.

Texture Animation

Now we need to add a new function to our script:

TileTextureAnimator function

function TileTextureAnimator(texture, hTiles, vTiles, durationTile) {
  // current tile number
  this.currentTile = 0;
  // duration of every tile
  this.durationTile = durationTile;
  // internal time counter
  this.currentTime = 0;
  // amount of horizontal and vertical tiles, and total count of tiles
  this.hTiles = hTiles;
  this.vTiles = vTiles;
  this.cntTiles = this.hTiles * this.vTiles;
  texture.wrapS = texture.wrapT = THREE.RepeatWrapping;
  texture.repeat.set(1 / this.hTiles, 1 / this.vTiles);
  this.update = function(time) {
    this.currentTime += time;
    while (this.currentTime > this.durationTile) {
      this.currentTime -= this.durationTile;
      this.currentTile++;
      if (this.currentTile == this.cntTiles) {
        this.currentTile = 0;
      }
      var iColumn = this.currentTile % this.hTiles;
      texture.offset.x = iColumn / this.hTiles;
      var iRow = Math.floor(this.currentTile / this.hTiles);
      texture.offset.y = iRow / this.vTiles;
    }
  };
}
The ‘TileTextureAnimator’ function adjusts the original images to display animation. It turns between tiles of the image from first to last tile. This does at a specified interval of time. Every tile is visible within the certain duration time, after it turns to another tile. Now let’s update the

‘addAnimatedObjects’ function 

addAnimatedObjects: function() {
  var texture1 = new THREE.ImageUtils.loadTexture('images/sprite1.png', undefined, function() {
    lesson8.anim1 = new TileTextureAnimator(texture1, 8, 8, 100);
    var material1 = new THREE.SpriteMaterial( { map: texture1, useScreenCoordinates: false, side:THREE.DoubleSide, transparent: true } );
    var mesh1 = new THREE.Sprite(material1);
    mesh1.position.set(0, 0, -40);
    mesh1.scale.set(64, 64, 1.0);
    lesson8.scene.add(mesh1);
    lesson8.animReady1 = true;
  });
  var texture2 = new THREE.ImageUtils.loadTexture('images/sprite2.png', undefined, function() {
    lesson8.anim2 = new TileTextureAnimator(texture2, 9, 8, 100);
    var material2 = new THREE.SpriteMaterial( { map: texture2, useScreenCoordinates: false, transparent: true } );
    var mesh2 = new THREE.Sprite(material2);
    mesh2.position.set(0, 0, 40);
    mesh2.scale.set(24, 46, 1.0);
    lesson8.scene.add(mesh2);
    lesson8.animReady2 = true;
  });
}
The first sprite image contains 8 tiles in row, 8 rows total, the second image contains 9 tiles in row. Every tile will be visible for 100ms. Finally, in the main ‘update’ function, we need to put the following code:
if (lesson8.animReady1) {
  lesson8.anim1.update(1000 * delta);
}
if (lesson8.animReady2) {
  lesson8.anim2.update(1000 * delta);
}
This code invokes the ‘update’ function of ‘TileTextureAnimator’ class objects.

As a result we got that only one tile is visible at a time. And every tile is visible within 100ms. So, the animation works pretty fast, as we needed to make.

Read More

How to use Ajax or Jquery to GET and Post Data - 2

In last post, I have explain a method to get or post data using ajax. Here i am going to explain a method to interact from server using Jquery.

Note: If you want to use jquery in your application, you must add a latest jquery library.

How to use Ajax or Jquery to GET and Post Data


Check carefully inside <head></head>. If a jquery library is already included then ignore to add this library.
Otherwise, add following code before </head>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>

Next step:

You can use GET or POST to interact with server. See following example:

1. Add following code above </head> 
<script type="text/javascript" language="javascript">
  $(document).ready(function() {
       var mname = document.getElementById("myname").value;
      $("#driver").click(function(event){
          $.post(
             "result.php",
             { "name": mname },
             function(data) {
                $('#mydata').html(data);
                 document.getElementById("getname").value = data;
             }
          );
      });
   });
   </script>
2. Add following code anywhere inside body

<div id="stage"></div>
<input id="myname" name="myname" value="" /><br />
<input id="getname" name="getname" value = "" />
<input type="button" id="driver" value="Load Data" />

3. Create a page "result.php" on server (localhost or Online server). Put following code
<?php
      echo 'Welcome '.$_POST['name'];
?>

4. When you click "Load Data" button
You will get output on browser without page refresh.

Explanation:

Check below code:
var mname = document.getElementById("myname").value;
Here javascript variable  "mname" is string data from input field having id "myname".

 $("#driver").click(function(event)
   {
      // Your code
   }
);

When you click a html tag having id = "driver", Your code will work. You can also use other events in the place of click. For example, onclick, onkeyup, onchange etc.

$.post(
             "result.php",
             { "name": mname },
             function(data) {
                $('#mydata').html(data);
               document.getElementById("getname").value = data;
             }
          );

Here I am using post method to send data to server. You can use get method in place of post.

See parameters of post method. 

Parameter 1: URL of  the server, where you want to send the data. In this example, I am using "result.php"
Parameter 2: {"key1" : "value1", "key2": "value2"}. You will get $_POST['key1'] = value1 and $_POST['key2'] = value2 on result.php page. If you use get method, then you will get data like $_GET['key1'] and $_GET['key2'] on result.php
Parameter 3:
function(data) {
                $('#mydata').html(data);
             }
Its a callback function, You will get response from server. In this example, data is string echo value from result.php and storing into html tag having id "mydata" and id "getname".



Read More

How to use Ajax or Jquery to GET and Post Data

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.

How to use Ajax or Jquery to GET and Post Data

How does it work?

Ans:

There are two section Ajax coding:

Http Request:

To make browser compatibility, we write code for different browsers:

For IE6 and IE5:
Create an instance for ActiveXObject. Check below code
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

For IE7+, Firefox, Chrome, Opera, Safari:
Create an instance for XMLHttpRequest. Check below code
xmlhttp=new XMLHttpRequest();

Next thing is to check your browser running this script:

If window.XMLHttpRequest is true. It means that your code is compatible with IE7+ or Firefox or Chrome, Opera or Safari.

If we combine above codes, You get a new on to send Http Request


if (window.XMLHttpRequest)
   {
        // code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
   }
else  {
             // code for IE6, IE5
           xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
 }


Http Response:

Check few terms before writing codes for http response
if xmlhttp.readyState = 4, It means your http request sent completed
if xmlhttp.status = 200, It means you  get http response successfully


Following is code for Http response:

xmlhttp.onreadystatechange=function()
 {
     if (xmlhttp.readyState==4 && xmlhttp.status==200)  
        {  
             document.getElementById("ID OF HTML TAG").innerHTML=xmlhttp.responseText;  
         }
 }

Now open http response under "getmydata" using method GET

xmlhttp.open("GET","URL WITH QUERYSTRINGS",true);xmlhttp.send();
Now i am combining above codes to make a complete code to use.


<script>
    function sendData(str)  
    {    
         if (str=="")      
            {            
               document.getElementById("getmydata").innerHTML="";        
               return;      
            }  
         if (window.XMLHttpRequest)      
           {            
                    // code for IE7+, Firefox, Chrome, Opera, Safari            
                xmlhttp=new XMLHttpRequest();  
   
            }  
        else      
           {
                    // code for IE6, IE5          
               xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");        
             }
 
       xmlhttp.onreadystatechange=function()    
             {        
                 if (xmlhttp.readyState==4 && xmlhttp.status==200)              
                     {                    
                          document.getElementById("getmydata").innerHTML=xmlhttp.responseText;            
                     }      
               }
        xmlhttp.open("GET","test.php?p="+str,true);    
        xmlhttp.send();
   }
</script>

1. Put this javascript before </head>
2. Suppose i have a form with dropdown. See Below
<select name="mydate" onChange="sendData(this.value)">
   <option value="2001">2001</option>
   <option value="2002">2002</option>
   <option value="2003">2003</option>
</select>
If you see this dropdown form carefully, you can see that an even is running onchange. When you change dropdown selection. Selected value send to SendData function.

When you are using ajax coding, few browsers are not supporting that syntax. So, We should write browser compatible code.
In ajax operation, You send http request to server on events like onClick, onChange, onKeyup etc and get back a http response.


SendData function calling an ajax. Under SendData function, Your selected value transfer using str. Here str storing your selected value.

Suppose you have selected "2002" from dropdown form. Then SendData transfer value "2002" to str.

Using following syntax to transfer value to your server,

xmlhttp.open("GET","test.php?p=2002",true);

Next thing, Where do you want to show result from test.php?p=2002

Write a html tag with id to see your result on webpage.

For example:

I have created a tag, <div id="getmydata"></div>

Now your test.php page:

Create a page test.php.
Write following code and put following code
<?php
      echo $_GET['p'];
?>
You will see output of $_GET['p'] under div with id getmydata.

Note:
1. You can take any unique id, it's not necessary to write "getmydata" always.
2. You can use any html tag, depends on your requirement. It's not necessary to write div only.
3. Similarly you can replace test.php and its querystrings.

In next post, I will show you a different code for ajax.

Enjoy coding.
Read More