Iwp Da4

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 52

INTERNET AND WEB

PROGRAMMING

NAME: ROHITH ANIL KUMAR


REGISTRATION NUMBER: 19BCI0148
COURSE CODE: CSE3002
LAB SLOT: L19+L20
DIGITAL ASSIGNMENT 4
Apply the following to the front-end which you submitted for your previous

assessments (2 & 3).

1. Registration page: Establish the connection with the database and verify the

data is inserted to the appropriate fields.

2. Login page: Verify and authenticate a user using the username and password.

3. Home page (specific to your chosen application): Perform the database

operations such as insert, delete and update by executing the SQL queries

through PHP. Also embed the cookies and sessions.

4. Incorporate AJAX to display the form validation messages (Minimum 2 fields

should be validated using AJAX).

5. Incorporate JQuery to perform customizations for your website like text

change hover, background customization, etc., (Minimum two functions)

1. Registration
registration.php
<?php include('index.php');?>
<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
<meta charset="utf-8">
<title>Registration</title>
<link rel="stylesheet" href="styles.css">
</head>

<body style>
<center>
<div id="respajax">
</div>
<form class="box" action="index.php" method="post">

<h1>Registration</h1>
<table cellspacing="15">
<tr>
<td><strong>* Required Field</strong></td>
</tr>
<tr>
<td>
<label>Username *</label>
</td>
<td>
<input type="text" name="username" value="" placeholder="Enter username"
id="username" required>
</td>
</tr>
<tr>
<td>
<label>First Name *</label>
</td>
<td>
<input type="text" name="firstname" value="" placeholder="Enter First Name"
id="firstname" required>
</td>
</tr>
<tr>
<td>
<label>Last Name *</label>
</td>
<td>
<input type="text" name="lastname" value="" placeholder="Enter Last Name"
id="lastname" required>
</td>
</tr>
<tr>
<td>
<label>E-mail address *</label>
</td>
<td>
<input type="email" name="email" value="" placeholder="Enter E-mail address"
id="email" required>
</td>
</tr>
<tr>
<td>
<label>Date of Birth *</label>
</td>
<td>
<input type="date" name="dob" value="">
</td>
</tr>
<tr>
<td>
<label>Gender *</label>
</td>
<td>
<label><input type="radio" name="gender" value="" required>Male</label>
<label><input type="radio" name="" value="">Female</label>
<label><input type="radio" name="" value="">Other</label>
</td>
</tr>
<tr>
<td>
<label>Occupation *</label>
</td>
<td>
<select class="" name="Occupation">
<option value="occ" selected disabled hidden required>Select an option</option>
<option value="">Student</option>
<option value="">Teacher</option>
<option value="">Software Engineer</option>
<option value="">Cloud Developer</option>
</select>
</td>
</tr>
<tr>
<td>
<label>Company</label>
</td>
<td>
<input type="text" name="company" placeholder="Enter company name" value="">
</td>
</tr>
<tr>
<td>
<label>Nationality *</label>
</td>
<td>
<label><input type="radio" name="nationality" value="" required>Indian</label>
<label><input type="radio" name="nationality" value="">Other</label>
</td>
</tr>
<tr>
<td>
<label>Phone number *</label>
</td>
<td>
<input type="tel" name="phoneno" value="" placeholder="Enter phone number"
id="phonenumber" required>
</td>
</tr>
<tr>
<td>
<label>Password *</label>
</td>
<td>
<input type="password" name="password1" value="" placeholder="Enter password"
id="password" required>
</td>
</tr>
<tr>
<td>
<label>Re-enter password *</label>
</td>
<td>
<input type="password" name="password2" value="" placeholder="Re-enter
password" id="reenter" required>
</td>
</tr>
<tr>
<td>
<label>Social Media Profile Link</label>
</td>
<td>
<input type="url" name="link" value="" placeholder="Enter link">
</td>
</tr>
</table>
<label><input type="checkbox" name="Confirmation of validity of info" value=""
required>I confirm that all the information included is true and complete to the best of my
knowledge.</label>
<br><br>
<input type="reset" name="Reset" value="Reset">
<input type="submit" name="Submit" value="Submit">
<br>
<a href="homepage\index1.html">Go back to home page</a>
</form>
</center>
</body>

</html>
Comment: Connecting to db and storing values in db
index.php
<?php
if(isset($_POST['username']))
{
$server="localhost";
$username="root";
$password="";
$database="registration";

$con=mysqli_connect($server,$username,$password,$database);

if(!$con){
die("Connection ot this database failed due to ".mysqli_connect_error());
}
echo "<center><h1>Connection to the database successful</h1></center>";

$username1=mysqli_real_escape_string($con,$_POST['username']);
$firstname=mysqli_real_escape_string($con,$_POST['firstname']);
$lastname=mysqli_real_escape_string($con,$_POST['lastname']);
$email=mysqli_real_escape_string($con,$_POST['email']);
$dob=mysqli_real_escape_string($con,$_POST['dob']);
$phoneno=mysqli_real_escape_string($con,$_POST['phoneno']);
$password1=mysqli_real_escape_string($con,$_POST['password1']);
$password2=mysqli_real_escape_string($con,$_POST['password2']);
$link=mysqli_real_escape_string($con,$_POST['link']);

//Check db for existing user with some Username


$user_check_query="SELECT * FROM userreg WHERE username='$username1' or
email='$email' LIMIT 1";
$results=mysqli_query($con,$user_check_query);
$user=mysqli_fetch_assoc($results);

if($user)
{
if($userreg['username']===$username1){echo "Username already exists";}
if($userreg['email']===$email){echo "This email id already has a registered username";}
}
else {
$sql="INSERT INTO userreg
(username,firstname,lastname,email,dob,phoneno,password1,password2,link) VALUES
('$username1','$firstname','$lastname','$email','$dob','$phoneno','$password1','$password
2','$link')";
mysqli_query($con,$sql);
echo "<script>alert('Database updated')</script>";
}
}

?>
2. Login
login.php
<?php
include('index1.php');
if(isset($_SESSION['loginerror']))
{
unset($_SESSION['loginerror']);
echo "<script>alert('Wrong username/password combination. Please try
again.')</script>";
}

?>

<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
<meta charset="utf-8">
<title>Login</title>
<link rel="stylesheet" href="style2.css">
</script>
</head>

<body>
<center>
<form class="box" action="index1.php" method="post">
<h1>Login</h1>
<table>
<tr>
<td>
<label>Enter username: </label>
</td>
<td>
<input type="text" name="username" value="" placeholder="Enter username"
required>
</td>
</tr>
<tr>
<td>
<label>Enter password: </label>
</td>
<td>
<input type="password" name="password" placeholder="Enter password" value=""
required>
</td>
</tr>
</table>
<input type="checkbox" name="" value="">
<label>Stay signed in</label>
<br>
<br>
<input type="submit" name="login_user" value="Login">
<a href="homepage\index1.html">Go back to home page</a>
</form>

</center>
</body>

</html>

Comment: Connecting to db and storing values in db


index1.php
<?php

session_start();

if(isset($_POST['username']))
{
$server="localhost";
$username="root";
$password="";
$database="registration";

$con=mysqli_connect($server,$username,$password,$database);

if(!$con){
die("Connection to this database failed due to ".mysqli_connect_error());
}
$username1=mysqli_real_escape_string($con,$_POST['username']);
$password=mysqli_real_escape_string($con,$_POST['password']);
$query="SELECT * FROM userreg WHERE username='$username1' AND
password1='$password' LIMIT 1";
$results=mysqli_query($con, $query);
$nrows=mysqli_num_rows($results);
if($nrows==1)
{
$_SESSION['username']=$username1;
$_SESSION['loginsucc']=1;
header("location: \iwpda\dashboardblog\index.php");

}
else {
$_SESSION['loginerror']=1;
header("location: \iwpda\login.php");

}
}

?>
If successfully logged in then redirected to dashboard page

If wrong credentials are used to login then an alert message pops up and redirects again
to the login page.
3. Home page
In the index.php the sessions and cookies are implemented.
The session variable is used to store the value of the logged in
username as it is needed when adding data to the table.
The cookies are used to store the username of the user who has
logged in.
index.php
<?php
if(isset($_SESSION['loginsucc']))
{
echo "<script>alert('Logged in successfully')</script>";
unset($_SESSION['loginsucc']);
}
?>

<?php
session_start();
$cookie_name="user";
$cookie_value=$_SESSION['username'];
setcookie($cookie_name,$cookie_value,time()+(86400*1),"/");
?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Dashboard blog</title>
<link rel="stylesheet" href="styles.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link
href="https://fonts.googleapis.com/css2?family=Merriweather:wght@300&family=Montser
rat" rel="stylesheet">
</head>
<body>
<center>
<h1>Dashboard</h1>
<hr>
<table cellspacing="20">
<tr>
<td><button type="button" name="button" class="btn"><a
href="newblog\index.php">Create a new life story</a></button></td>
<td><button type="button" name="button" class="btn"><a
href="editblog\index.php">Edit existing life story</a></button></td>
<td><button type="button" name="button" class="btn"><a
href="deleteblog\index.php">Delete a life story</a></button></td>
</tr>
<tr>
<td></td>
<td><center><button type="button" name="button" class="btn"><a href="#">Post a
life story</a></button></center></td>
<td></td>
</tr>
<tr>
<td></td>
<td><center><button type="button" name="button" class="btn"><a
href="emptycookie.php">Sign Out</a></button></center>
</td>
<td></td>
</tr>
</table>
<hr>
</center>

</body>
</html>
When the user signs out, the cookie is deleted.
emptycookie.php
<?php
setcookie("user","",time()-3600,"/");
header("location: \iwpda\homepage\index1.html");
?>
INSERT, DELETE AND UPDATE OPERATIONS
On clicking on the create a new life story button
NEW BLOG

index.php of new blog


<?php
include('tablenew.php'); ?>

<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
<meta charset="utf-8">
<title>New Blog</title>
<link rel="stylesheet" href="styles.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link
href="https://fonts.googleapis.com/css2?family=Merriweather:wght@300&family=Montser
rat" rel="stylesheet">
</head>

<body>
<center>
<h1><strong>NEW BLOG</strong></h1>
<hr>
<form class="" action="tablenew.php" method="post">
<table cellspacing="20">
<tr>
<td><label for="">Enter Date: </label></td>
<td><input type="text" name="date" value="" required></td>
</tr>
<tr>
<td><label for="">Enter title: </label></td>
<td><input type="text" name="title" value="" requrired></td>
</tr>
<tr>
<td><label for="">Enter theme: </label></td>
<td><input type="text" name="theme" value="" required></td>
</tr>
</table>
<br><br>
<div class="">
<table>
<tr>
<td id="t1"><center>Write down your experience in the textbox given
below</center></td>
</tr>
<tr>
<td><textarea id="" name="story" rows="30" cols="150" required></textarea></td>
</tr>
</table>
</div>
<input type="submit" name="" value="Submit" class="btn">
<br><br>
<a href="http://localhost/iwpda/dashboardblog/index.php">Return to dashboard</a>
</form>
</center>
</body>

</html>

The values from new blog are added to the database by the
tablenew.php
tablenew.php
<?php
session_start();
if(isset($_POST['date']))
{
$server="localhost";
$username="root";
$password="";
$database="blog";

$con=mysqli_connect($server,$username,$password,$database);

if(!$con){
die("Connection to this database failed due to ".mysqli_connect_error());
}
echo "<center><h1>Connection to the database successful</h1></center>";

$uname=mysqli_real_escape_string($con,$_SESSION['username']);
$title=mysqli_real_escape_string($con,$_POST['title']);
$date1=mysqli_real_escape_string($con,$_POST['date']);
$theme=mysqli_real_escape_string($con,$_POST['theme']);
$story=mysqli_real_escape_string($con,$_POST['story']);

$sql="INSERT INTO newblog (uname,title,date1,theme,story) VALUES


('$uname','$title','$date1','$theme','$story')";
mysqli_query($con,$sql);

header("location: \iwpda\dashboardblog\index.php");
}
?>
After clicking submit, the values are added to the database. From the
new blog page, it gets redirected to the dashboard.
The username value has been added to the db. Without even a field
to accept it, we used the global session variable to store the value
and update it in the table.
EDIT BLOG

index.php of edit blog


<?php
include('tableed.php'); ?>
<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
<meta charset="utf-8">
<title>Edit Blog</title>
<link rel="stylesheet" href="styles.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link
href="https://fonts.googleapis.com/css2?family=Merriweather:wght@300&family=Montser
rat" rel="stylesheet">
</head>

<body>
<center>
<h1><strong>EDIT BLOG</strong></h1>
<hr>
<form class="" action="tableed.php" method="post">
<table cellspacing="20">
<tr>
<td><label for="">Enter new date: </label></td>
<td><input type="text" name="date" value=""></td>
</tr>
<tr>
<td><label for="">Enter new title: </label></td>
<td><input type="text" name="title" value=""></td>
</tr>
<tr>
<td><label for="">Enter theme: </label></td>
<td><input type="text" name="theme" value=""></td>
</tr>
<tr>
<td><label for="">Enter entry number: </label></td>
<td><input type="text" name="entryno" value=""></td>
</tr>
</table>
<br><br>
<div class="">
<table>
<tr>
<td id="t1"><center>Write down your experience in the textbox given
below</center></td>
</tr>
<tr>
<td><textarea id="" name="story" rows="30" cols="150"></textarea></td>
</tr>
</table>
</div>
<input type="submit" name="" value="Submit" class="btn">
<br><br>
<a href="http://localhost/iwpda/dashboardblog/index.php">Return to dashboard</a>
</form>
</center>
</body>

</html>

The values from blog are edited and updated in the table of the
database by the tableed.php
tableed.php
<?php
session_start();
if(isset($_POST['date']))
{
$server="localhost";
$username="root";
$password="";
$database="blog";

$con=mysqli_connect($server,$username,$password,$database);

if(!$con){
die("Connection to this database failed due to ".mysqli_connect_error());
}
echo "<center><h1>Connection to the database successful</h1></center>";

$uname=mysqli_real_escape_string($con,$_SESSION['username']);
$title=mysqli_real_escape_string($con,$_POST['title']);
$date1=mysqli_real_escape_string($con,$_POST['date']);
$theme=mysqli_real_escape_string($con,$_POST['theme']);
$story=mysqli_real_escape_string($con,$_POST['story']);
$entryno=mysqli_real_escape_string($con,$_POST['entryno']);

$sql="UPDATE newblog SET title='$title',date1='$date1',theme='$theme',story='$story'


where uname='$uname' and entryno='$entryno'";
mysqli_query($con,$sql);

header("location: \iwpda\dashboardblog\index.php");
}
?>
After clicking submit, the values are edited to the database. From the
edit blog page, it gets redirected to the dashboard.
DELETE BLOG

index.php of delete blog


<?php include('tabledel.php') ?>
<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
<meta charset="utf-8">
<title>Delete Blog</title>
<link rel="stylesheet" href="styles.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link
href="https://fonts.googleapis.com/css2?family=Merriweather:wght@300&family=Montser
rat" rel="stylesheet">
</head>
<body>
<center>
<h1><strong>DELETE BLOG</strong></h1>
<hr>
<form class="" action="tabledel.php" method="post">
<table cellspacing="20">
<tr>
<td><label for="">Enter Date: </label></td>
<td><input type="text" name="date" value=""></td>
</tr>
<tr>
<td><label for="">Enter entry number: </label></td>
<td><input type="text" name="entryno" value=""></td>
</tr>
<tr>
<td><label for="">Enter title: </label></td>
<td><input type="text" name="title" value=""></td>
</tr>
</table>
<br>
<input type="submit" name="" value="Submit" class="btn">
<br><br>
<a href="http://localhost/iwpda/dashboardblog/index.php">Return to dashboard</a>
</form>
</center>
</body>

</html>
The values from blog are deleted and updated in the table of the
database by the tabledel.php
tabledel.php
<?php
session_start();
if(isset($_POST['date']))
{
$server="localhost";
$username="root";
$password="";
$database="blog";

$con=mysqli_connect($server,$username,$password,$database);

if(!$con){
die("Connection to this database failed due to ".mysqli_connect_error());
}
echo "<center><h1>Connection to the database successful</h1></center>";

$uname=mysqli_real_escape_string($con,$_SESSION['username']);
$title=mysqli_real_escape_string($con,$_POST['title']);
$date1=mysqli_real_escape_string($con,$_POST['date']);
$entryno=mysqli_real_escape_string($con,$_POST['entryno']);

$sql="DELETE FROM newblog where uname='$uname' and entryno='$entryno'";


mysqli_query($con,$sql);

header("location: \iwpda\dashboardblog\index.php");
}
?>

After clicking submit, the values are deleted from the table in the
database. From the delete blog page, it gets redirected to the
dashboard.
4. Incorporating ajax to display form validation messages for two
fields.
The two fields are username and email.
getajax.php
<br><br><br><br>
<body style="background-color:powderblue;">

<center>
<p>Enter username to check if it is valid or not.</p>
<p>Suggestions: <span id="txtHint"></span></p>

<form>
First name: <input type="text" onkeyup="showUname(this.value)">
</form>
<br>
<p>Enter email to check if it is valid or not.</p>
<p>Suggestions: <span id="txtHint1"></span></p>
<form>
Email: <input type="text" onkeyup="showPassword(this.value)">
</form>
</center>
</body>

<script>
function showUname(str) {
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
document.getElementById("txtHint").innerHTML = this.responseText;
}
xmlhttp.open("GET", "gethint.php?q=" + str);
xmlhttp.send();
}
}
function showPassword(str) {
if (str.length == 0) {
document.getElementById("txtHint1").innerHTML = "";
return;
} else {
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
document.getElementById("txtHint1").innerHTML = this.responseText;
}
xmlhttp.open("GET", "getpass.php?q=" + str);
xmlhttp.send();
}
}
</script>

The two php files called by getajax.php are gethint.php and


getpass.php. They validate and send the response from the server
to the website. Hence, the fields get validated without refreshing
the page.
gethint.php
<?php

$q = $_REQUEST["q"];

$hint = "";

if ($q !== "") {


$q = strtolower($q);
$len=strlen($q);
function validateUsername($username){
if(preg_match('/^[a-zA-Z0-9]{5,}$/', $username)) {
return true;
}
else {
return false;
}

}
if ((validateUsername($q))) {
$hint="Valid username";
}
else {
$hint="Invalid username";
}
}

echo $hint === "" ? "no suggestion" : $hint;


?>

getpass.php
<?php

$q = $_REQUEST["q"];

$hint = "";
if ($q !== "") {
function validateEm($email)
{
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
return true;
}
else {
return false;
}
}
if (!(validateEm($q))) {
$hint="Valid email id";
}
else {
$hint="Invalid email id";
}

}
echo $hint === "" ? "no suggestion" : $hint;
?>

This is the validation page.

When wrong input is entered in the fields


When the right input is entered in the fields

5. jQuery
HOME PAGE
When mouseover COVID LIFE STORIES, the text color changes to
white. The motto button is used to toggle some text using jQuery.
The text above the Simon Game button keeps blinking and is
implemented by jQuery.

The index1.html of the homepage


<!DOCTYPE html>
<html lang=" " dir="ltr">

<head>
<meta charset="utf-8">
<title>CL Stories</title>
<link rel="icon" href="favicon0.ico">
<link rel="stylesheet" href="styles.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link
href="https://fonts.googleapis.com/css2?family=Merriweather:wght@300&family=Montser
rat" rel="stylesheet">
</head>

<body>
<center>
<br>
<h1>Covid Life Stories</h1>
<hr size="5">
<p><em>A place to share one's experiences during Covid</em></p>
<button class="btn" class="mottobt" type="button" name="button">Motto</button>
<br><br>
<table id="motto">
<tr>
<td>
<ul>
<li>Share your Stories</li>
</ul>
</td>
<td>
<ul>
<li>Be Aware</li>
</ul>
</td>
<td>
<ul>
<li>Be Safe</li>
</ul>
</td>
</tr>
</table>
<img id="image1" src="NatureStory.jpg" alt="Picture(NatureStory)" width="600"
height="300">
<table border="1">
<tr>
<td><strong>Quote for the day: </strong></td>
<td>It is during our darkest moments that we must focus to see the light.</td>
<td>Aristotle</td>
</tr>
</table>
<table style="border-spacing:20px;">
<tr>
<td>
<a class="btn" href="\iwpda\login.php">Login</a>
</td>
<td>
<a class="btn" href="\iwpda\registration.php">Sign up</a>
</td>
</tr>
</table>
<button name="button"><a href="https://covid.giveindia.org">Covid 19 Relief
Services</a></button>
<br>
<div id="blink1">
Feeling bored during COVID times. Play the Simon game to improve your memory and
have fun. Try to beat your friend's high score.
</div>
<br><br>
<a class="btn" href="\iwpda\Simon Game Challenge Starting Files\index.html"
style="color: #ffffff;">Simon Game</a>
<br><br>
<hr>
<table cellspacing="20">
<tr>
<td>
<img id="image2" src="https://media-
exp1.licdn.com/dms/image/C5603AQEcLcubYPcEcA/profile-displayphoto-
shrink_400_400/0/1606972443158?e=1640217600&v=beta&t=xX1D80LPdEEZ54UWkLfjlbtK
-siWW-swi4hxU-wmyDY" alt="Creator image" width="110"
height="110">
</td>
<td>
<h3>Rohith Anil Kumar</h3>
<p><em>Computer Science student</em></p>
<a href="C:\Users\User\OneDrive\Desktop\Web Development\CSS-My
Site\index.html">About Me</a>
</td>
</table>
</center>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="anim.js" charset="utf-8"></script>
</body>

</html>

The anim.js where the jQuery animations are added to the


homepage.
anim.js
$("#motto").hide();

$("h1").on("mouseenter",function(){
$("h1").css("color","white");
});
$("h1").on("mouseleave",function(){
$("h1").css("color","black");
});
$("button").on("click",function()
{
$("#motto").toggle(1500);
});

var temp=false;

function animatePress() {
$("#blink1").fadeIn(1000).fadeOut(1000).fadeIn(1000);
blinkrep(temp);
}

function blinkrep(temp)
{
if(!temp)
{
animatePress();
}
}
animatePress();

THE SIMON GAME PAGE


index.html
<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
<meta charset="utf-8">
<title>Simon</title>
<link rel="stylesheet" href="styles.css">
<link href="https://fonts.googleapis.com/css?family=Press+Start+2P" rel="stylesheet">
</head>

<body>
<h1 id="level-title">Press A Key to Start</h1>
<div class="container">
<div class="row">

<div type="button" id="green" class="btn green">

</div>

<div type="button" id="red" class="btn red">

</div>
</div>

<div class="row">

<div type="button" id="yellow" class="btn yellow">

</div>
<div type="button" id="blue" class="btn blue">

</div>

</div>

</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="game.js" charset="utf-8"></script>
</body>

</html>

styles.css
body {
text-align: center;
background-color: #011F3F;
}

#level-title {
font-family: 'Press Start 2P', cursive;
font-size: 3rem;
margin: 5%;
color: #FEF2BF;
}

.container {
display: block;
width: 50%;
margin: auto;

.btn {
margin: 25px;
display: inline-block;
height: 200px;
width: 200px;
border: 10px solid black;
border-radius: 20%;
}

.game-over {
background-color: red;
opacity: 0.8;
}

.red {
background-color: red;
}

.green {
background-color: green;
}

.blue {
background-color: blue;
}

.yellow {
background-color: yellow;
}

.pressed {
box-shadow: 0 0 20px white;
background-color: grey;
}

game.js which added the animations using jQuery to the page.


game.js
var gamePattern = [];
var userClickedPattern = [];
var buttonColours = ["red", "blue", "green", "yellow"];

var started = false;

var level = 0;

$(".btn").click(function() {
var userChosenColour = $(this).attr("id");
userClickedPattern.push(userChosenColour);
playSound(userChosenColour);
animatePress(userChosenColour);
checkAnswer(userClickedPattern.length - 1);
});

$(document).keypress(function() {
if (!started) {

nextSequence();
started = true;
}
});

function playSound(name) {
var audio1 = new Audio("sounds/" + name + ".mp3");
audio1.play();
}

function nextSequence() {

userClickedPattern = [];

level++;
$("#level-title").text("Level " + level);

var num = Math.floor(Math.random() * 4);


var randomChosenColour = buttonColours[num];
gamePattern.push(randomChosenColour);

$("#" + randomChosenColour).fadeIn(100).fadeOut(100).fadeIn(100);

var audio = new Audio("sounds/" + randomChosenColour + ".mp3");


audio.play();
}

function animatePress(currentColor) {
$("#" + currentColor).addClass("pressed");

setTimeout(function() {
$("#" + currentColor).removeClass("pressed");
}, 100);
}

function checkAnswer(currentLevel) {
if (gamePattern[currentLevel] === userClickedPattern[currentLevel]) {

console.log("success");
if (userClickedPattern.length === gamePattern.length) {

//5. Call nextSequence() after a 1000 millisecond delay.


setTimeout(function() {
nextSequence();
}, 1000);

}
else {

console.log("wrong");
playSound("wrong");

$("body").addClass("game-over");
setTimeout(function () {
$("body").removeClass("game-over");
}, 200);

$("#level-title").text("Game Over, Press Any Key to Restart");


startOver();

}
}
function startOver()
{
level=0;
gamePattern=[];
started=false;

You might also like