A simple slider(carousel) using vanilla JavaScript: vitaSlider

No comments

Tuesday, 23 January 2018

A simple slider(carousel) using vanilla JavaScript: vitaSlider

Sliders are a common feature for websites. many JavaScript libraries have this feature already implemented. Today I will take you through the process of building your own custom slider, that is very simple to use and customize.
Create a new folder and open it using using your favorite editor. In the new folder you created, create an additional folder for images and three files as follows:
a sample vitaSlider
A folder called “img”
A JavaScript file “script.js”
A CSS file “style.css” and an “index.html” file
In the index.html file, inside the head element, reference your css and javascript files as shown:
<html lang=”en-US”>
 <head>
 <title>Simple Slider</title>
 <link rel=”stylesheet” href=”css/style.css” />
<script type=”text/javascript” src=”js/script.js”></script>
 </head>
 …
</html>
Your JS file is now referenced in your HTML web page. You can write JavaScript application logic in this file that will run on your web page.
Create Figure Elements For Carousel
Within the body element, add a new section element after the header element add:
<body>
 <header>
 …
 </header>
 <section>
 </section>

</body>
Within the section element, add a new figure element:
<section id=”carousel”>
 <figure>
 </figure>
</section>
Within the new figure element, add a new img element:
<figure>
 <img />
</figure>
Update the new img element by setting the src attribute to the value img/picurename.png:
Update the new img element by setting the alt attribute to the value of your choice. Within the new figure element, add a new figcaption element: Update the new figcaption element by setting the content to any caption of your choice.
Your index.html page will look like this
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8">
<meta name=”viewport” content=”width=device-width, initial-scale=1.0">
<meta http-equiv=”X-UA-Compatible” content=”ie=edge”>
<link rel=”stylesheet” href=”style.css”>
<script src=”script.js”></script>
<title>Document</title>
</head>
<body>
<section id=”carousel”>
<figure class=”visible”>
<img src=”img/car.png” alt=”Efficient Cars”>
<figcaption>2020, scientists promised us electric cars </figcaption>
</figure>
<figure class=”hidden”>
<img src=”img/health.png” alt=” Health is wealth”>
<figcaption>Health iswealth</figcaption>
</figure>
<figure class=”hidden”>
<img src=”img/nature.png” alt=” Nature”>
<figcaption> Hurricane Threatens to Touch Down on the East Coast This Weekend</figcaption>
</figure>
</section>
Lorem ipsum, dolor sit amet consectetur adipisicing elit.
Ipsa distinctio alias, nobis numquam repudiandae possimus
nam aliquid vel rerum soluta quam! Esse molestias hic neque
incidunt recusandae fuga, omnis laborum?
</body>
</html>
Apply Carousel CSS Styles to target the img elements that are direct descendants of figure elements that are direct descendants of the section element with an id of carousel. This rule set should include the following declarations:
This rule will hide the figure elements by default.
section#carousel > figure > img {
display: none;
margin: 0px auto;
}
Add a CSS rule set that targets the img elements that are direct descendants of figure elements referencing the visible class that are direct descendants of the section element with an id of carousel. This rule set should include the following declarations:
This rule will show only the figure elements that reference the class visible.
section#carousel > figure.visible > img {
display: block;
position: relative;
overflow: hidden;
}
Add a CSS rule set that targets the figcaption elements that are direct descendants of figure elements that are direct descendants of the section element with an id of carousel. This rule set should include the following declarations:
This rule will hide the figcaption elements by default.
section#carousel > figure > figcaption {
display: none;
}
Add a CSS rule set that targets the figcaption elements that are direct descendants of figure elements referencing the visible class that are direct descendants of the section element with an id of carousel. This rule set should include the following declarations:
This rule will show only the figcaption elements that reference the class visible.
section#carousel > figure.visible > figcaption {
display: block;
text-align: center;
font-weight: bold;
font-size: 1.5em;
}
Your style.css should look like this:
body {
font-family: Itim;
color: aqua;
text-align: center;
}
section#carousel>figure>img {
display: none;
margin: 0px;
}
section#carousel>figure.visible>img {
display: block;
overflow: hidden;
position: relative;
margin: 0px auto;
}
section#carousel>figure>figcaption {
display: none;
}
section#carousel>figure.visible>figcaption {
display: block;
text-align: center;
font-weight: bold;
font-size: 1.5em;
}
Implement Carousel JavaScript

Add a new variable named slideInterval with the initial value set to 4000;
var slideInterval = 4000;
Create a new function named getFigures.
function getFigures() {
}
In the getFigures function, retrieve all of the figure elements within the section element using the id of carousel. Return the resulting array as the result of this function.
function getFigures() {
 return document.getElementById(‘carousel’).getElementsByTagName(‘figure’);
}
Create a new function named moveForward. Implement the new function with the following logic:
This function iterates over the figure elements in the section element. It removes the visible class from the current figure element, then adds the class to the next figure element. Once complete, it uses the setTimeout function to invoke itself again after a specified amount of time (4000 milliseconds = 4 seconds).
function moveForward() {
 var pointer = 0;
 var figures = getFigures();
 for (var i = 0; i < figures.length; i++) {
 if (figures[i].className == ‘visible’) {
 figures[i].className = ‘hidden’;
 pointer = i;
 }
 }
 if (++pointer == figures.length) {
 pointer = 0;
 }
 figures[pointer].className = ‘visible’;
 setTimeout(moveForward, slideInterval);
}
Create a new function named startPlayback.
function startPlayback() {
}
In the startPlayback function, use the setTimeout function in JavaScript to invoke the moveForward method after a specified amount of time. Use the slideInterval variable for the time interval.
function startPlayback() {
 setTimeout(moveForward, slideInterval);
}
In the last line of the JavaScript file, invoke the startPlayback function.
startPlayback();
The JavaScript logic simply adds the visible CSS class to the next image in the rotation approximately every 4 seconds, and adds the hidden CSS class to others.
Thanks as I hope this little tutorial helps you. Download and star the full version of this code at my github repository.
Don’t forget share because sharing is caring… Follow me on twitter @vita_developer for more wonderful updates, and on my blog for more gist.

UNN STUDENTS (MALE) PROTESTS ON LACK OF LIGHT, WATER, ETC(PHOTOS)

No comments

Sunday, 21 January 2018

 

Just this evening. Some group of boys left their hostels for a massive protest.  This was as a result of lack of electricity,  water and poor provisions of properties of  good living in their hostels. We currently do not know if it's a peaceful protest or not.  We'll be dropping pictures soon.  Stay tuned!  Thanks

How to create a simple calculator using vanila Javascript

5 comments

Thursday, 18 January 2018

Javascript is by no doubt the most popular programming language, it is a very powerful language used for both frontend and backend(Nodejs) website
development. It is the language with the highest number of frameworks which can be used for a number of things.

Alot of beginnes of this language tries to get their hands dirty by building some simple applications like a simple calculator, sometimes they
get stocked with no one to help.

In this tutorial, I will show you one out of the several ways by which you can build a simple calculator using Javascript. I will use  HTML and CSS to make the interface look pretty cool.



This tutorial assumes you have a little foundation in any programming language not necessary Javascript. I Will take it  step by step as I
try to explain what every line of code is doing.

Step 1:
 Build the interface of your  calculator using html and use CSS to make it look awesome.
 I will use the <button> tags to make the calculator buttons and the <input> tag of 'type' text to make the calculator screen, as shown in the code sample


<div id="outer-wrapper">
 <div id="inner-wrapper">
 <div id ="screen-show">
  <input type="text" name="screen" value="0"  id="screen" placeholder="0" disabled="true">
 </div>
 <div id="button-show">
  <button id="7" value="7" onclick="numbers(7)">7</button>
  <button id="8" value="8" onclick="numbers(8)">8</button>
  <button id="9" value="9" onclick="numbers(9)">9</button>
  <button id="divide" value="/" onclick="numbers('/')">/</button>
  <button id="del" value="del" onclick="deleted(del)">DEL</button>
  <br>
  <button id="6" value="6" onclick="numbers(6)">6</button>
  <button id="5" value="5" onclick="numbers(5)">5</button>
  <button id="4" value="4" onclick="numbers(4)">4</button>
  <button id="multiply" value="*" onclick="numbers('*')">x</button>
  <button id="percent" value="%" onclick="numbers('%')">%</button>
  <br>
  <button id="3" value="3" onclick="numbers(3)" >3</button>
  <button id="2" value="2" onclick="numbers(2)">2</button>
  <button id="1" value="1" onclick="numbers(1)">1</button>
  <button id="substrct" value="-" onclick="numbers('-')">-</button>
  <button id="equal" value="=" onclick="numbers('=')">=</button>
  <br>
  <button id="b0" value="0" onclick="numbers(0)">0</button>
  <button id="dot" value="." onclick="dots('.')">.</button>
  <button id="add" value="+" onclick="numbers('+')">+</button>
 </div>
 <div><p>vita!</p></div>
 </div>
 
</div>



Step 2:
On each of these <buttons> tags which I used for my calculator buttons, I have a function 'number()' which is triggered on button click of
the buttons. This function ships in the value of the particular button clicked and this value is stored in a string inside the number function.


function numbers(value){

   
    //wherever this functon is called, get the value of what is on the screen
    var screen=document.getElementById("screen");

    //I used top down approach to code this, read from the elseif statement to enable easy understanding  
    //check if the = sign has been pressed. the variable value is where anything that is pressed is stored. it is passed through the function number()
    if(value=="=")
    {
        //split the input using the split function, which returns it as an array 
        var all=screen.value.split(" ")
        firstpart=parseFloat(all[0]);
        op=all[1];
        secondpart=parseFloat(all[2]);
        
        var screen=document.getElementById("screen");

        if (secondpart==0) 
        {
            screen.value="division by zero!"
        }
        switch(op)
        {   

            case '+':
                result = firstpart + secondpart;
                screen.value= result;
                break;
            case '-':
                result = firstpart - secondpart;
                screen.value= result;
                break;
            case '*':
                result = firstpart*secondpart;
                screen.value= result;
                break;
            case '/':
                result = firstpart / secondpart;
                screen.value= result;

                break;
            case '%':
                result = firstpart % secondpart;
                screen.value= result;
                break;
            default:

            break;
        }
    }

    //if the equals sign wasnt pressed,then the following will be evaluated.
    // checks for what is on the screen and what is pressd
    else if(screen.value =="0" && value=="0")
    {
        return null;
    }

    //it checks for what is on the screen and what is pressed
    else if(screen.value=="0" && !((value=="*" || value=="/" )|| ((value =="+"|| value=="-")|| (value=="%"))))
    {
        screen.value=value;
        //secondpart+=value;
    }
    //if actually a number was pressed, it will save it on an already decleared variable and on the screen
    else if(!((value=="*" || value=="/" )||((value =="+"|| value=="-")|| (value=="%"))))
    {
        screen.value+=value;
        //secondpart+=screen.value;
    }

    //when eventually an operation is pressed,it will build this sting as say 2  *  2 with spaces in between to help me split the array
    else if (op=="0" && ((value=="*" || value=="/" )|| ((value =="+"|| value=="-")|| (value=="%"))))
    {
    //
    //building the string
    screen.value+=" ";
    screen.value+=value;
    screen.value+=" ";
    op=value;
    }
    
    else
    {
        return;
    }
}

The number() functions performs a series of checks to validate the users input, stores it appropriately.

Step 3:
One each of the operations buttons,(buttons for  +,/,*,-), I have a functions attached to them which is triggered on click of the operators
buttons, this function makes the operation to be performed to be saved in the same sting as the numbers. This function also allows for the
deletion of characters.



function deleted(del){
   var screen=document.getElementById("screen");
   screen.value='';
   op=0;
   del=0;
   var firstpart ="0";
   var secondpart = "0";
   var dot=0;
   //console.log(secondpart);
   
  }
   
  function dots(dt){
   //var op= 0;
   if (dot== 0){
   var screen=document.getElementById("screen");
   screen.value+=dt;

   // i changed the value of dot to avoid pressing it two times 
   dot="recoded"
   }
   else
   {
    //returns an empty stuff if you have pressed dot for the first time
    return;
   }
  }

Step 4:
In order to calculate the final result, on the click of the equals(=)sign button, I used a Javascript 'splict' function, to splict the string
at which the characters where stored in to three and then calculate the operation required using a switch statement.

         
var all=screen.value.split(" ");
    firstpart=parseFloat(all[0]);
    op=all[1];
    secondpart=parseFloat(all[2]);


Thanks as I hope this little tutorial helps you. Download and star the full version of this code at my github repository.
Don't forget share because sharing is caring... Follow me on twitter @vita_developer for more wonderful updates

How to register and login a user using Ajax in Laravel

No comments

Monday, 15 January 2018

Today, I will share with you how to use  ajax to register a user in laravel using bootstrap modal. The error displayed will be shown on the bootstrap modal.

I assume you are a bit familiar with Laravel simple validation on post request  which provides basic validation and return errors when the rules are not met. This tutorial will show you how to configure laravel  validation in a bootstrap pop up modal without page refresh, and how to login the user if the validation is successful.  It is little bit hard for new laracasts but the steps are easy if well understood.
I will take it step by step, as I illustrate with the following code snippets ;
  1. Create a new laravel project using the laravel new blog command
  2. Open resources/views/layouts/app.blade.php file and add this bootstrap model link on it.
<li> <a href="#" data-toggle="modal" data-target="#SignUp">Register</a> </li>

3.Create a form in a Modal as shown:




 <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">×</button>
                <h3 class="modal-title text-center primecolor">Sign Up</h3>
            </div>
            <div class="modal-body" style="overflow: hidden;">
                <div id="success-msg" class="hide">
                    <div class="alert alert-info alert-dismissible fade in" role="alert">
                      <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                        <span aria-hidden="true">×</span>
                      </button>
                      <strong>Success!</strong> Check your mail for login confirmation!!
                    </div>
                </div>
                <div class="col-md-offset-1 col-md-10">
                    <form method="POST" id="Register">
                        {{ csrf_field() }}
                        <div class="form-group has-feedback">
                            <input type="text" name="name" value="{{ old('name') }}" class="form-control" placeholder="Full name">
                            <span class="glyphicon glyphicon-user form-control-feedback"></span>
                            <span class="text-danger">
                                <strong id="name-error"></strong>
                            </span>
                        </div>
                        <div class="form-group has-feedback">
                            <input type="email" name="email" value="{{ old('email') }}" class="form-control" placeholder="Email">
                            <span class="glyphicon glyphicon-envelope form-control-feedback"></span>
                            <span class="text-danger">
                                <strong id="email-error"></strong>
                            </span>
                        </div>
                        <div class="form-group has-feedback">
                            <input type="password" name="password" class="form-control" placeholder="Password">
                            <span class="glyphicon glyphicon-lock form-control-feedback"></span>
                            <span class="text-danger">
                                <strong id="password-error"></strong>
                            </span>
                        </div>
                        <div class="form-group has-feedback">
                            <input type="password" name="password_confirmation" class="form-control" placeholder="Retype password">
                            <span class="glyphicon glyphicon-log-in form-control-feedback"></span>
                        </div>
                        <div class="row">
                            <div class="col-xs-12 text-center">
                              <button type="button" id="submitForm" class="btn btn-primary btn-prime white btn-flat">Register</button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
4.Open the Script tag <script></script> and write your Ajax Codes as follows:


    
$('body').on('click', '#submitForm', function () {
            var registerForm = $("#Register");
            var formData = registerForm.serialize();
     console.log(formData);
    //hide all the errors
    $('#email-error').html('');
    $('#name-error').html('');
    $('#password-error').html('');

    //make the ajax request
    $.ajax(
        {
            url:'/register',
            type:'post',
            data:formData,

            success:function(data){
                console.log(data);
                  if (data.errors) {
                      if (data.errors.name) {
                          $('#name-error').html(data.errors.name[0]);
                      }
                      if (data.errors.email) {
                          $('#email-error').html(data.errors.email[0]);
                      }
                      if (data.errors.password) {
                          $('#password-error').html(data.errors.password[0]);
                      }

                  }
                  if (data.success) {

                    console.log('user created');
                      $('#success-msg').removeClass('hide');
                      setInterval(function () {
                          $('#SignUp').modal('hide');
                          $('#success-msg').addClass('hide');
                      }, 3000);
                  }
            },

        });
});


5. Open your register controller,and overwrite the default laravel controller as follows:



Thanks for reading, share and comment on this tutorial.

<?php

namespace App\Http\Controllers\Auth;

use App\Models\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Http\Request;
use Response;
use Auth;

class RegisterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */

    use RegistersUsers;

    /**
     * Where to redirect users after registration.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
     public function register(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|max:255',
            'email' => 'required|email|max:255|unique:users',
            'password' => 'required|min:6|confirmed',
        ]);

        $input = $request->all();

        if ($validator->passes()) {

            // Store your user in database 
            $user = User::create([
            'name' => $request['name'],
            'email' => $request['email'],
            'phone' => 2,
            'usertype'=>45,
            'password' => bcrypt($request['password']),

        ]);
             Auth::login($user);

            return Response::json(['success' => '1']);

        }
        
        return Response::json(['errors' => $validator->errors()]);
    }

    // /**
    //  * Create a new user instance after a valid registration.
    //  *
    //  * @param  array  $data
    //  * @return \App\User
    //  */
    // protected function create(array $data)
    // {
    //     return User::create([
    //         'name' => $data['name'],
    //         'email' => $data['email'],
    //         'phone' => $data['phone'],
    //         'usertype'=>$data['usertype'],
    //         'password' => bcrypt($data['password']),
    //     ]);
    // }
}

Don't Miss
© all rights reserved
made with by xclusivefx