Learning Computer Programming

145
I post articles, tips, tricks, techniques, algorithms etc. related to C++ Programming. Many of the things that I discuss also applies to other programming languages.

RECENT POSTS:

In nowadays web 2.0 world use of Lightbox is very common. While Lightbox, fancybox (similar to the former) are great scripts and have wide uses, creating a script similar to these is never a bad idea. If you learn, read on else use of one of those scripts, they’re great and easy-to-use.

For those of you who haven’t heard about the script or don’t know what they do, see the following image:

Screenshot og Blackbox - Our own Lightbox clone

Chances are, you might surely have seen it somewhere or the other. These scripts are generally used to display some content in kind of like a dialog box (modal one, for those of you who're geeks) while the rest of the content gets blackened. Looks great? Yes it does!

Okay, for those of you still here I wanna confess that I didn’t put enough time knowing how those scripts actually work. I just got an idea myself the other day and thought it just might work. This is not to say that I myself have invented some new way, it’s just that I don’t know how those scripts work but I know one way that gives similar results.

As you can see from the above image, there is not much to a simple Lightbox clone, we have a (1) Blackening effect (2) The content box.

  1. Blackening Effect: For this I’ll create a “div” element on the fly and set its properties such that it has a black color and some transparency, a large z-index means floats on top of the rest of the content and back content (with normal z-index) cannot be interacted with anymore. We’ll fill the current screen with this “div” which will require us to place this element at the topmost and leftmost coordinates relative to the current viewable area. This will be (0, 0) when the page isn’t scrolled at all.

    We’ll also have to size the element to have it span the whole viewable area of the browser.

    These two things will make sure that no matter where we have scrolled in a page and whatever be the window size, this black overlay element always covers the current viewport.

  2. 2. Content Box: A nicely styled box with a close button is all we need. We’ll place it at the center of the screen. Since we have calculated the topmost and leftmost coordinates relative to the current viewport and we also have the current viewport’s dimension, we can easily position this at the center, no brainer! We’ll give this a z-index larger than the black overlay element such that this is at the top of everything.

    Besides this, we’ll also have to take care that these two elements move along with the page in case user tries to scroll the page when the our lightbox is open. This will make sure that (1) black overlay element always fills the screen (2) content box is always at the center.

Sounds pretty simple? Well, it is! It’ll call this Blackbox, you may call it whatever you feel like. Here is the code (Demo here):


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Blackbox - A very simple Lightbox clone</title>

<script type="text/javascript">
/*
 * Script: Blackbox (very simple Lightbox clone)
 * Author: Arvind Gupta ([email protected])
 * Date: 14-Nov-09
 * Copyright: 2009 Arvind Gupta

 *            You may freely use this script wherever
 *         you want and in whatever way you wish
 *         but please don't remove this note.
 *
 */

// OBJECTS

// Black overlay element
var darkbox;
// Content box
var content;

// FUNCTIONS
function init()
{
   // Set "onScroll" event handler

   window.onscroll = scroll_box;
}

function open()
{
   // Create elements
   darkbox = document.createElement('div');
   content = document.createElement('div');

   // Style them with the existing ids
   darkbox.id = 'darkbox';
   content.id = 'content';

   // FILL CONTENT BOX

   // Have the close button
   content.innerHTML = '<a style="position: absolute; top: -30px; right: -30px; text-decoration: none;" href="javascript:close();"><img style="border: none;" src="fancy_closebox.png" /></a>';
   // The main content

   content.innerHTML += '<div id="main_content"><h1>Hello</h1><p>Hello World!<br /> How is this looking?</p></div>';

   // Add these elements to the body

   document.body.appendChild(darkbox);
   document.body.appendChild(content);

   // Calciulate coordinates and such
   var pos_top = document.documentElement.scrollTop
   var pos_left = document.documentElement.scrollLeft;
   var screen_width = document.documentElement.clientWidth;
   var screen_height = document.documentElement.clientHeight;

   // Place the "darkbox" element and give it the size

   darkbox.style.top = pos_top + 'px';
   darkbox.style.left = pos_left + 'px';
   darkbox.style.height = screen_height + 'px';
   darkbox.style.width = screen_width + 'px';

   // Now place the content box at the center
   content.style.left = (pos_left + (screen_width / 2.0) - (content.offsetWidth / 2.0)) + 'px';
   content.style.top = (pos_top + (screen_height / 2.0) - (content.offsetHeight / 2.0)) + 'px';
}


function scroll_box ()
{
   // If "Darkbox" open
   if(darkbox != null)
   {
      // Find new topmost, leftmost position w.r.t the current viewport
      // Also find new window size

      var pos_top = document.documentElement.scrollTop
      var pos_left = document.documentElement.scrollLeft;
      var screen_width = document.documentElement.clientWidth;
      var screen_height = document.documentElement.clientHeight;

      // Positions elements accordingly
      darkbox.style.top = pos_top + 'px';
      darkbox.style.left = pos_left + 'px';
      darkbox.style.height = screen_height + 'px';
      darkbox.style.width = screen_width + 'px';

      content.style.left = (pos_left + (screen_width / 2.0) - (content.offsetWidth / 2.0)) + 'px';
      content.style.top = (pos_top + (screen_height / 2.0) - (content.offsetHeight / 2.0)) + 'px';
   }
}


function close()
{
   // Delete elements
   document.body.removeChild(darkbox);
   document.body.removeChild(content);
}
</script>

<style>
#darkbox {
   position: absolute;
   top: 0px;
   left: 0px;
   opacity: 0.6;
   filter:alpha(opacity=60);
   background: #000;
}

#content {
   position: absolute;
   z-index: 1001;
   background: #fff;
   border: 10px solid #000;
   width: 500px;
   height: 300px;
}
#content #main_content {
   overflow: auto;
   width: 500px;
   height: 300px;
}

</style>
</head>

<body onload="init();">
<a href="javascript:open()">Open Box</a>
</body>
</html>

Related Posts:

Happy Diwali
October 16th, 2009 11:40
Wishing you a safe and happy Diwali
A Simple Pong Game using JavaScript
September 15th, 2009 12:21

Pong Game in JavaScript Screenshot

Having the knowledge of moving images using JavaScript, we’ll be creating a small Ping Pong game as an example for this post.

Today we’ll learn to do a few new things in JavaScript:

1. Executing some code every specified time interval (for game loop).
2. Tracking and using mouse movements.
3. Attaching code (function) to events.

Game Theory

As you should be knowing, in this game there is one ball and two paddles at two ends. One is user-controlled the other, for this example, is CPU controlled. User has to move the paddle in order not to let the ball pass through, CPU also has to do the same thing. Whoever’s side the ball passes through looses the game.

There are a few objects which can interact with each other, these are ball, paddles, walls. Let’s see the various interactions that can take place between these:

  1. Ball Hitting Upper/Lower Wall – Ball will bounce off.

  2. Ball Passing Through Either Side – Player or CPU, depending on whose side ball passed through, will loose the game.

  3. Ball Hitting Paddle – It’ll bounce off

We’ll need to take care of these events:

  1. Page Load – Game objects will be initialized

  2. Game Start – Mouse click on the player paddle will start the game.

  3. Mouse Movements – Inside the game area (a div), the paddle will follow the y-position of the mouse. Paddle however should not get past the boundaries.

  4. CPU Paddle – The paddle will follow the ball by moving up/down depending the relative position of the ball. We’ve added a little intelligence by only moving the paddle while ball is coming towards it. This will make the movement as well as the game look more real.

Code

NOTE: Put two files ball_small.png, paddle.png (Right-Click "Save As") in the same directory the script is in.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Pong Game In JavaScript</title>

<style>
#box
{
   width: 500px;
   height: 300px;
   margin: auto;
   border: 5px solid #ccc;
   position: relative;
   overflow: hidden;
}

.ob
{
   position: absolute;
   border: 0px;
}
</style>
<script type="application/javascript">

// CHANGE THESE, IF REQUIRED
var Speed = 5; // Speed of ball (pixels/step)
var CPUSpeed = 5; // Speed of CPU Paddle (pixels/step)

// Short references to objects
var paddle1;
var paddle2;
var ball;
var box;
var msg;


// For internal use
var dx, dy; // Speed in x and y directions
var ballX, ballY; // x and y positions of ball
var playerY; // y position of player paddle (x fixed)

var cpuY; // y position of CPU paddle (x fixed)
var iID; // To store ID of set interval used to clear it when required

// Attach a function to onLoad event
window.onload = Init;

// INITIALIZE GAME OBJECTS
function Init()
{
   // Make short refrences to objects

   paddle1 = document.getElementById('paddle1');
   paddle2 = document.getElementById('paddle2');
   ball = document.getElementById('ball');
   box = document.getElementById('box');
   msg = document.getElementById('msg');

   // Initial values
   ballX = (box.offsetWidth / 2) - (ball.offsetWidth / 2);
   ballY = (box.offsetHeight / 2) - (ball.offsetHeight / 2);
   cpuY = (box.offsetHeight / 2) - (paddle2.offsetHeight / 2);
   playerY = (box.offsetHeight / 2) - (paddle1.offsetHeight / 2);
   dx = dy = Speed;

   paddle1.style.left = 20 + 'px';
   paddle1.style.top = playerY + 'px';
   paddle2.style.left = box.offsetWidth - (20 + paddle2.offsetWidth) + 'px';
   paddle2.style.top = cpuY + 'px';
   ball.style.left = ballX + 'px';
   ball.style.top = ballY + 'px';

   // Show message

   msg.innerHTML = '<h2>Click on Paddle to Start Game.</h2>';
}

// START GAME
function Start()
{
   // Attach a function to onmousemove event of the box
   box.onmousemove = MovePaddle;
   // Call 'GameLoop()' function every 10 milliseconds

   iID = setInterval('GameLoop()', 10);

   msg.innerHTML = '';
}

// MAIN GAME LOOP, CALLED REPEATEDLY
function GameLoop()
{
   // MOVE BALL
   ballX += dx;
   ballY += dy;

   // See if ball is past player paddle

   if(ballX < 0)
   {
      clearInterval(iID);
      Init();

      box.onmousemove = '';

      msg.innerHTML = '<h2>You Loose!<br/>Click on Paddle to Re-Start Game.</h2>';
   }

   // See if ball is past CPU paddle

   if((ballX + ball.offsetWidth) > box.offsetWidth)
   {
      clearInterval(iID);
      Init();

      box.onmousemove = '';

      msg.innerHTML = '<h2>You Win!<br/>Click on Paddle to Re-Start Game.</h2>';
   }

   // COLLISION DETECTION

   // If ball hits upper or lower wall
   if(ballY < 0 || ((ballY + ball.offsetHeight) > box.offsetHeight))
      dy = -dy; // Make x direction opposite

   // If ball hits player paddle

   if(ballX < (paddle1.offsetLeft + paddle1.offsetWidth))
      if(((ballY + ball.offsetHeight) > playerY) && ballY < (playerY + paddle1.offsetHeight))
         dx = -dx;

   // If ball hits CPU paddle
   if((ballX + ball.offsetWidth) > paddle2.offsetLeft)
      if(((ballY + ball.offsetHeight) > cpuY) && ballY < (cpuY + paddle2.offsetHeight))
         dx = -dx;

   // Place ball at calculated positions

   ball.style.left = ballX + 'px';
   ball.style.top = ballY + 'px';

   // MOVE CPU PADDLE
   // Move paddle only if ball is coming towards the CPU paddle
   if(dx > 0)
   {
      if((cpuY + (paddle2.offsetHeight / 2)) > (ballY + ball.offsetHeight)) cpuY -= CPUSpeed;
      else cpuY += CPUSpeed;

      paddle2.style.top = cpuY + 'px';
   }
}


// TO MOVE PLAYER PADDLE ON MOUSE MOVE EVENT
function MovePaddle(e)
{
   // Fetch y coordinate of mouse
   var y = (e.clientY - (box.offsetTop - document.documentElement.scrollTop));
   // Here, (box.offsetTop - document.documentElement.scrollTop) will get the relative
   // position of "box" w.r.t to current scroll postion

   // If y below lower boundary (cannot go above upper boundary - 
   // mousemove event only generated when mouse is inside box
   if(y > (box.offsetHeight - paddle1.offsetHeight))
      y = (box.offsetHeight - paddle1.offsetHeight);

   // Copy position
   playerY = y;
   // Set position

   paddle1.style.top = y + 'px';
}
</script>
</head>

<body bgcolor="#fff">
<h1 align="center">Pong Game Example in JavaScript</h1>

<div id="box">
<img class="ob" id="paddle1" src="paddle.PNG" onclick="javascript: Start()"/>

<img class="ob" id="paddle2" src="paddle.PNG" />
<img class="ob" id="ball" src="ball_small.PNG" />

</div>
<div id="msg" align="center"></div>
</body>
</html>

Related Posts:

Screenshot

In this post we’re going to learn how we can move an image around using JavaScript. We’ll have four control links (Left, Right, Up, Down) that’ll move the image.

Reading along you’ll learn:

  1. What the absolute and relative positions do
  2. How some JavaScript function can be invoked automatically on page load
  3. How JavaScript can be used to manipulate the “style” properties of elements
  4. How JavaScript can be used to change these properties

Okay, now let’s start!

THEORY

We’re going to have the following elements in the page:

  1. A container (div)
  2. An image
  3. Control links

Container

The container would be styled to have a size of 500px by 300px. It’d have position: relative which makes anything inside to be positioned with respect to this container. It’s done to make the image move independent of the placement of the container. We’ll also make the overflows from the container to be “hidden”.

Image

The image would be given position: absolute which means it can be positioned with absolute (left (x), top (y)) values. Normally images (like other elements) are positioned, aligned, wrapped accordingly with other elements. The absolute position however, gives us the power to place the image (or other element) freely.

Control Links

Control Links  will be used to invoke the functions to move the image in the respective directions.

Misc.

The functions being called by the Control links will manipulate the position of the image using one document.getElementbyId() function.

This function is used to reference elements in the document uniquely by using their IDs (which are supposed to be unique for each element). The style properties of elements are referenced as:

document.getElementById(<ID>).style.<STYLE-NAME>

We’ll be using the onload event of the body element to invoke the Init() function initially on page load.

<body onload="javascript:Init()">

WORKING

When the page loads, the function Init() is getting called which sets the initial position of the image.

When a control link is clicked, the respective coordinate (x or y) is modified and the new value is set in the following line:

document.getElementById('img1').style.left = x + 'px';

document.getElementById('img1').style.top = y + 'px';

CODE

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>JavaScript: Moving an Image</title>
<script type="application/ecmascript">

// --CHANGE THESE IF REQUIRED--
// Initial x-position of image
var x = 200;
// Initial y-position of image
var y =100;
// Pixels to move in each step
var inc = 10;

function Init()
{
   document.getElementById('img1').style.left = x + 'px';
   document.getElementById('img1').style.top = y + 'px';
}
function moveRight()
{
   x += inc;

   document.getElementById('img1').style.left = x + 'px';
}

function moveLeft()
{
   x -= inc;

   document.getElementById('img1').style.left = x + 'px';
}

function moveUp()
{
   y -= inc;

   document.getElementById('img1').style.top = y + 'px';
}

function moveDown()
{
   y += inc;

   document.getElementById('img1').style.top = y + 'px';
}
</script>


<style>
#box
{
   width: 500px;
   height: 300px;
   position: relative;
   margin: 20px auto 0px auto;
   border: 5px outset #000;
   overflow: hidden;
}

.image
{
   position: absolute;
   z-index: 100;
}
</style>
</head>

<body onload="javascript:Init()">
<div id="box"><img class="image" id="img1" src="ball.png"/></div>
<a href="javascript:moveLeft()">Left</a>
<a href="javascript:moveUp()">Up</a>
<a href="javascript:moveDown()">Down</a>
<a href="javascript:moveRight()">Right</a>
</body>
</html>

NOTE: An image with name "ball.png" must be there in the same directory as this file for the above ocde to work "as-is".

Related Posts: