how to add fade in and fade out - javascript

I am stuck with my project.
I need to add to the code below fade-in and fade-out effect by using javascript and css only. please help me.
I created this function to store all the data in the local storage and when I am clicking on the save button I want the note to be added with fade in effect. when I am deleting the note I want it to be deleted in fade out. only the note I am adding or deleting will be added or removed with the effect
this is the function to add the note:
function saveIt() {
var content = document.getElementById("content").value;
var date = document.getElementById("date").value;
var time = document.getElementById("time").value;
var id = Math.floor(Math.random() * 100000); //creating random id number.
var note = { id: id, content: content, date: date, time: time };
notesArray.push(note);
localStorage.myList = JSON.stringify(notesArray);
notesNewArray = JSON.parse(localStorage.myList);
for (var i = 0; i < notesNewArray.length; i++) {
theId = notesArray[i].id;
var output = "<div id='justFade'>" + "<div class='main col-xm-12 col-sm-6 col-md-4 col-lg-3'>" + "<div class='note-bg'>" + "<div id='" + theId + "'" + "onclick='deleteNote(this.id)'>" + "<p id='hide-delete' class='glyphicon glyphicon-remove-circle'></p>" + "</div>" + "<div class='noteContent'>" + notesNewArray[i].content + "</div>" + "<div class='noteDate'>" + notesNewArray[i].date + "</div>" + "<div>" + notesNewArray[i].time + "</div>" + "</div>" + "</div>" + "</div>";
}
document.getElementById("results").innerHTML += output;
document.getElementById("msg").innerHTML = ""; //to hide the message for the empty note.
document.getElementById("msgDate").innerHTML = ""; //to hide the message for the empty or wrong date.
document.getElementById("msgTime").innerHTML = ""; //to hide the message for the empty or wrong date.
document.forms['myNotes'].reset(); //reseting the form on saving.
function deleteNote(clickedId) {
var myList = localStorage.myList;
notesArray = JSON.parse(myList);
for (var i = 0; i < notesArray.length; i++) {
if (notesArray[i].id == clickedId) {
notesArray.splice(i, 1); // searching for the same ID number that the user clicked on and deleting it.
}
localStorage.myList = JSON.stringify(notesArray);
notesNewArray = JSON.parse(localStorage.myList);
document.getElementById("results").innerHTML = "";
getIt(); // calling again to the notes from the local storage.
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>My Project</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="css/styles.css">
<link href="https://fonts.googleapis.com/css?family=Indie+Flower" rel="stylesheet">
</head>
<body id="init">
<div class="center">
<img src="img/title.png" class="img-center" alt="My Task Board" width="876" height="225">
</div>
<div class="container-fluid">
<div class="row">
<div class="col-sm-4"></div>
<div class="col-sm-4">
<form id="myNotes" name="myNotes">
<div class="form-group">
<textarea rows="8" name="myContent" cols="100" class="form-control" id="content" placeholder="type your note here..." required></textarea><br>
<div><input type="date" class="form-control" id="date" required></div>
<div><input type="time" class="form-control" id="time" required></div>
<input type="submit" class="btn btn-primary" id="save" value="save">
<div id="msg"></div>
<div id="msgDate"></div>
<div id="msgTime"></div>
</div>
</form>
</div>
<div class="col-sm-4"></div>
</div>
</div>
<div id="results" class="singleNote"></div>
<script src="js/myscript.js"></script>
</body>
</html>
thank you.

You can use jquery to solve this problem. For any element that requires to fade in or out you can do this...
$("#div1").fadeIn();
$("#div1").fadeOut();
Here is a link that explains...
Jquery fade in and out

You need to make two async functions fadeIn() and fadeOut() and a function to return a promise.
With async you are solving the function asynchronously meaning other code can continue executing and doesn't have to wait for the return of a priorly called function to start it's execution. Because of this they appear to fade in and out at the same time even though they are called by 4 different lines of code.
Here is a quick example of fade in and fade out done in plain javascript:
(Run the snippet at the bottom of the code)
function sleep(ms)
{
return new Promise(resolve => setTimeout(resolve, ms));
}
async function fadeIn(elmnt)
{
for(var i=0; i<101; i++)
{
document.getElementById(elmnt).style.opacity = i/100;
await sleep(20); // Play with the sleep time to suit your needs, in miliseconds
}
}
async function fadeOut(elmnt)
{
for(var i=100; i > -1; i--)
{
document.getElementById(elmnt).style.opacity = i/100;
await sleep(20);
}
}
// Simply call the functions anywhere you want like this
fadeIn('fade_1');
fadeIn('fade_2');
fadeOut('fade_3');
fadeOut('fade_4');
.opacityZero
{
opacity:0;
}
.opacityOne
{
opacity:1;
}
.firstDiv
{
position:relative;
float:left;
width:97%;
border:1px solid #000;
padding:5px;
}
.secondDiv
{
position:relative;
float:left;
width:98%;
border:1px solid #000;
padding:5px;
}
.container
{
position:relative;
float:left;
width:95%;
margin-top:20px;
border:1px solid #09f;
padding:10px;
}
h3
{
font-family:calibri;
position:relative;
float:left;
}
<h3>Fade in effect</h3>
<div id="fade_1" class="firstDiv opacityZero">hi</div>
<div class="container">
<span id="fade_2" class="secondDiv opacityZero">hi</span>
</div>
<h3 style="margin:20px 0 0;">Fade out effect</h3>
<div id="fade_3" class="firstDiv opacityOne">hi</div>
<div class="container">
<span id="fade_4" class="secondDiv opacityOne">hi</span>
</div>

Related

Why are my float right elements coming in left more and more

I'm working my way through a todo list tutorial. It was working properly until I was trying to style it up a little bit. I have a Font Awesome trash can icon inside of a button with the Class "remove". Basically I took all the styles off the button so its just the trash icon. Users click it and there todo list item deletes, as it should. I wanted to right align the trash can from the task that pops up. It does that but everytime I add a new task the trash can floats right less and less.
Ill try to just post the relevant code but I'm not sure why this is happening. I'm using bootstrap to help style and that and the plus sign circular button don't seem to be interfering with the tasks as they are created. Any ideas would be awesome, thanks everyone!
Here is a pic
function get_todos() {
var todos = new Array;
var todos_str = localStorage.getItem('todo');
if (todos_str !== null) {
todos = JSON.parse(todos_str);
}
return todos;
}
function add() {
var task = document.getElementById('task').value;
var todos = get_todos();
todos.push(task);
localStorage.setItem('todo', JSON.stringify(todos));
show();
return false;
}
//This is mostly where the remove button takes place
function remove() {
var id = this.getAttribute('id');
var todos = get_todos();
todos.splice(id, 1);
localStorage.setItem('todo', JSON.stringify(todos));
show();
return false;
}
function show() {
var todos = get_todos();
var html = '<ul>';
for(var i=0; i < todos.length; i++) {
html += '<li>' + todos[i] + '<button class="remove" id="' + i + '"><i class="fa fa-trash" aria-hidden="true"></i></button></li>';
};
html += '</ul>';
document.getElementById('todos').innerHTML = html;
var buttons = document.getElementsByClassName('remove');
for (var i=0; i < buttons.length; i++) {
buttons[i].addEventListener('click', remove);
};
}
document.getElementById('add').addEventListener('click', add);
show();
.remove { /*Trash can button*/
color:#C0C0C0;
font-size:24px;
border:0;
padding:0;
background-color:transparent;
float:right;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.5/css/bootstrap.min.css" integrity="sha384-AysaV+vQoT3kOAXZkl02PThvDr8HYKPZhNT5h/CXfBThSRXQ6jW5DO2ekP5ViFdi" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js" integrity="sha384-3ceskX3iaEnIogmQchP8opvBy3Mi7Ce34nWjpBIwVTHfGYWQS9jwHDVRnpKKHJg7" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.3.7/js/tether.min.js" integrity="sha384-XTs3FgkjiBgo8qjEjBk0tGmf3wPrWtA6coPfQDfFEY8AnYJwjalXCiosYRBIBZX8" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.5/js/bootstrap.min.js" integrity="sha384-BLiI7JTZm+JWlgKa0M0kGRpJbF2J8q+qreVrKBC47e3K6BW78kGLrCkeRX6I9RoK" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<div class="container" style="margin-top:200px;">
<div class="row justify-content-center">
<div class="col-sm-12 col-lg-8">
<h1 style="padding-bottom:20px;">Test</h1>
<div class="form-group">
<input type="text" class="form-control" id="task">
</div>
</div>
</div>
<div class="row justify-content-center" style="margin-top:20px;">
<div class="col-sm-12 col-sm-8">
<div id="todos"></div>
</div>
</div>
<div class="row">
<div class="col"></div>
<div class="col-xs-2" style="margin-right:15px; margin-top:30px;">
<button id="add" style="border-radius:50%; font-size:35px; width:65px;" class="btn btn-danger">+</button>
</div>
</div>
</div>
here is the fiddle
It's because the floated element above it is in the way. One way to avoid this is to add clear: right or clear: both to the styles for the floated element.
.remove { /*Trash can button*/
color:#C0C0C0;
font-size:24px;
border:0;
padding:0;
background-color:transparent;
float:right;
clear:right;
}
I played around the CSS and found the following CSS styles work. Correction, see below changes. It will make the list look nicer.
on <ul> element
add
font-size: 20px;
on .remove class
remove
font-size: 24px;
float:right;
add
position: absolute;
right: 20px;

Append a text in container

I have created a container which displays the texts each time i click on a button. My code works fine but each time i click on a button the previous entry which is displayed in the container erases. I want to keep the previous entry and make the next text appear in the next line each time i click on a new button. Below is my code.Thank you
function appChangeFunction() {
holdtext.innerText = appchange.innerText;
}
function sharedChangeFunction() {
holdtext.innerText = sharedchange.innerText;
}
<div id="container">
<TEXTAREA ID="holdtext" rows="15" cols="70"></TEXTAREA><br><br>
</div>
<style>#container {width:100%; text-align:center;}</style>
<link rel="stylesheet" type="text/css" href="css.css" />
<button onclick="appChangeFunction()" style="background-color:white" >App Change</button>&nbsp
<button onclick="sharedChangeFunction()" style="background-color:white" >Shared Change</button>&nbsp
<SPAN ID="appchange" STYLE="display:none"> Text Under App Change
</SPAN>
<SPAN ID="sharedchange" STYLE="display:none"> Text Under Shared Change
</SPAN>
Just add the old text to the new using + sign :
<script>
function appChangeFunction() {
holdtext.innerText = holdtext.innerText + '\n' + appchange.innerText;
}
function sharedChangeFunction() {
holdtext.innerText = holdtext.innerText + '\n' + sharedchange.innerText;
}
</script>
Or using += sign and \n for new lines :
<script>
function appChangeFunction() {
holdtext.innerText += '\n'+appchange.innerText;
}
function sharedChangeFunction() {
holdtext.innerText += '\n'+sharedchange.innerText;
}
</script>
Hope this helps.
Replace your script tag with:
<script>
function appChangeFunction() {
holdtext.innerText += "\n"+appchange.innerText;
}
function sharedChangeFunction() {
holdtext.innerText += "\n"+sharedchange.innerText;
}
</script>
If first get the container data then it will be added the text
<html>
<body>
<div id="container">
<TEXTAREA ID="holdtext" rows="30" cols="70">
</TEXTAREA><br><br>
</div>
<style>#container {width:100%; text-align:center;}</style>
<link rel="stylesheet" type="text/css" href="css.css" />
<button onclick="appChangeFunction()" style="background-color:white" >App Change</button>&nbsp
<button onclick="sharedChangeFunction()" style="background-color:white" >Shared Change</button>&nbsp
<SPAN ID="appchange" STYLE="display:none"> Text Under App Change
</span>
<SPAN ID="sharedchange" STYLE="display:none"> Text Under Shared Change
</SPAN>
</body>
</html>
<script>
function appChangeFunction() {
var x = document.getElementById("holdtext").innerHTML;
holdtext.innerText = x + appchange.innerText;
}
function sharedChangeFunction() {
var x = document.getElementById("holdtext").innerHTML;
holdtext.innerText = x + sharedchange.innerText;
}
</script>

Use variable from another method

I am making a slot machine with JavaScript and have run into an issue when I need to compare variables at the end of a scroll to see if user won or not.
Is it possible to somehow store the variable "randomArrayItem" from the method moveSlots() and use it in the go() method?
I use the moveSlots() method to move each slot separately, but I need to know the randomArrayItem it used to move it so I can compare each slots value to eachother. If they match up, the user is supposed to win.
NOTE THIS WONT RUN BECAUSE I DON"T KNOW HOW TO INSERT MY IMAGES FROM slot1,2,3. But I posted because I am only asking how to carry the randomArrayItem over to GetLucky(); ? Thanks!
var slot1 = [
'<img class="coffee" src="imgs/temp-coffee-1.jpg" alt="coffee pot icon">',
'<img class="tea" src="imgs/temp-tea-1.jpg" alt="coffee pot icon">',
'<img class="espresso" src="imgs/temp-espresso-1.jpg" alt="coffee pot icon">'
];
var slot2 = [
'<img class="coffee" src="imgs/temp-coffee-1.jpg" alt="coffee pot icon">',
'<img class="tea" src="imgs/temp-tea-1.jpg" alt="coffee pot icon">',
'<img class="espresso" src="imgs/temp-espresso-1.jpg" alt="coffee pot icon">'
];
var slot3 = [
'<img class="coffee" src="imgs/temp-coffee-1.jpg" alt="coffee pot icon">',
'<img class="tea" src="imgs/temp-tea-1.jpg" alt="coffee pot icon">',
'<img class="espresso" src="imgs/temp-espresso-1.jpg" alt="coffee pot icon">'
];
function GetLucky(){
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function go(){
addSlots();
moveSlots($('#slot_a'));
moveSlots($('#slot_b'));
moveSlots($('#slot_c'));
// NEED TO COMPARE var randomArrayItem from _a, _b, _c to see if they match... ideas???
}
function moveSlots(el){
var time = 500;
time += Math.round(Math.random()*2000);
el.stop(true,true);
var randomArrayItem = getRandomInt(0, 2);
var marginTop = (-7 * (100)) - (randomArrayItem * 100 ); //change 100 to height placeholder
el.animate(
{"margin-top":marginTop+"px"},
{'duration' : time, 'easing' : "easeInOutQuint"}
);
}
function addSlots(){
for(i=0; i<20; i++){
$('#slot_a').append("<div class='content'>" + slot1[getRandomInt(0,2)] + "</div>");
$('#slot_b').append("<div class='content'>" + slot2[getRandomInt(0,2)] + "</div>");
$('#slot_c').append("<div class='content'>" + slot3[getRandomInt(0,2)] + "</div>");
}
}
}
body{
background-color:white;
padding:50px;
margin:50px;
}
.slots {
font-size:10px;
font-family:arial,helvetica,sans-serif;
overflow:hidden;
width:100px;
height:100px;
border:1px solid black;
float:left;
}
.slots .wrapper{
width:100px;
}
.slots .slot{
width:100px;
height:100px;
text-align:center;
}
.slot .content {
width:100px;
height:100px;
color:#000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
</html>
<body>
<script src="js/jQuery_v1.12.3.js" type="text/javascript"></script>
<script src="js/jquery.easing.1.3.js" type="text/javascript"></script>
<script src="js/scripts.js" type="text/javascript"></script>
<link href="css/style.css" rel="stylesheet" type="text/css" />
<div style="width:310px">
<div class="slots" id="slots_a">
<div class="wrapper" >
<div id="slot_a" class='slot'><!-- <img src="imgs/temp-tea-1.jpg" alt="coffee pot icon"> --></div>
</div>
</div>
<div class="slots" id="slots_b">
<div class="wrapper" >
<div id="slot_b" class='slot'><!-- <img src="imgs/temp-coffee-1.jpg" alt="coffee pot icon"> --></div>
</div>
</div>
<div class="slots" id="slots_c">
<div class="wrapper" >
<div id="slot_c" class='slot'><!-- <img src="imgs/temp-espresso-1.jpg" alt="coffee pot icon"> --></div>
</div>
</div>
<div style="text-align:center">
<input type="button" value="spin!" onClick="GetLucky();" style="margin-top:4px;">
</div>
</div>
</body>
Hard to explain but you will see below.
Try to return the randomArrayItem from move slots and trigger the execution of go by calling it go();
function GetLucky(){
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function go(){
addSlots();
randomArrayItem1 = moveSlots($('#slot_a'));
randomArrayItem2 = moveSlots($('#slot_b'));
randomArrayItem3 = moveSlots($('#slot_c'));
if (randomArrayItem1 == randomArrayItem2 && randomArrayItem2 == randomArrayItem3) console.log('win');
}
function moveSlots(el){
var time = 500;
time += Math.round(Math.random()*2000);
el.stop(true,true);
var randomArrayItem = getRandomInt(0, 2);
var marginTop = (-7 * (100)) - (randomArrayItem * 100 ); //change 100 to height placeholder
el.animate(
{"margin-top":marginTop+"px"},
{'duration' : time, 'easing' : "easeInOutQuint"}
);
return randomArrayItem;
}
function addSlots(){
for(i=0; i<20; i++){
$('#slot_a').append("<div class='content'>" + slot1[getRandomInt(0,2)] + "</div>");
$('#slot_b').append("<div class='content'>" + slot2[getRandomInt(0,2)] + "</div>");
$('#slot_c').append("<div class='content'>" + slot3[getRandomInt(0,2)] + "</div>");
}
}
go();
}
You can store variables by having a function return a value and have that function on the right hand of an assignment operation.
For instance:
var randomInt = getRandomInt();
EDIT: That said, if randomInt is inside a function, another function will not be able to access it. Example:
function i() { var x = 7; }
var a = x+x;
Var a in the above code will be undefined since the variable is not defined globally (only within its function)
Just a general note too...your code never seems to actually executes go(). It only defines it via function go() etc.

how do I make margins work on divs created dynamically in my JS?

HTML:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous"/>
<link rel="stylesheet" type="text/css" media="all" href="css/animate.min.css"/>
<link href="http://fonts.googleapis.com/css?family=Lobster" rel="stylesheet" type="text/css"/>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css"/>
<link rel="stylesheet" href="css/thisProject.css"/>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<h1 class="text-primary">Wiki Article Search</h1>
<div>
<input type="text" id="input"/>
<button id="search">Search</button>
<a id="random" class="btn btn-primary" target="_blank" href="http://en.wikipedia.org/wiki/Special:Random">Press For Random</a>
</div>
</br>
<div id="bodyDiv">
</div>
<script src="wikiViewer.js"></script>
</body>
</html>
JavaScript:
(function(){
var searchBtn = document.getElementById('search');
//var body = document.getElementsByTagName('body')[0];
var input = document.getElementById("input");
var bodyDiv = document.getElementById('bodyDiv')
$(document).ready(function(){
searchBtn.addEventListener('click', searchWiki);
function searchWiki(){
bodyDiv.innerHTML = "";
var url = 'https://en.wikipedia.org/w/api.php?format=json&action=query&generator=search&gsrnamespace=0&gsrlimit=10&prop=pageimages|extracts&pilimit=max&exintro&explaintext&exsentences=1&exlimit=max&gsrsearch='
if (input.value === ""){
return;
}
var searchTerm = input.value.replace(/\s/g, '%20');
url = url + searchTerm + '&callback=?';
$.getJSON(url, domMod); //change fileName to be whatever we wish to search
function domMod(json){ //what to do with dom based on json file NOTE WE NEED TO FIRST CHECK ANDREMOVE PREVIOUS SEARCH CONTENT
var entry;
if (!json.hasOwnProperty('query')){
return;
}
if (!json.query.hasOwnProperty('pages')){
return;
}
json = json.query.pages;
var keys = Object.keys(json);
var keysLength = keys.length;
for (var i = 0; i < keysLength; i++){
entry = json[keys[i]];
var outterDiv = document.createElement('div');
outterDiv.className = "entry";
var imageDiv = document.createElement('div');
imageDiv.className = "entryImg";
var entryDiv = document.createElement('div');
entryDiv.className = "entryTxt";
outterDiv.appendChild(imageDiv);
outterDiv.appendChild(entryDiv);
entryDiv.innerHTML = '<h2>' + entry.title + '</h2>' + '<p>' + entry.extract + '</p>'
if (entry.hasOwnProperty('thumbnail')){ //add image to our imageDiv child of entryDiv
imageDiv.style.backgroundImage = "url('" + entry.thumbnail.source + "')"
}
var br = document.createElement('br');
bodyDiv.appendChild(outterDiv); //appendChild to the Body
bodyDiv.appendChild(br);
}
}
}
});
}())
CSS:
input{
width:180px;
}
.entry{
width:90%;
margin-left:auto;
margin-right:auto;
height: 140px;
}
.entryTxt{
margin-left: 5px;
}
.entryImg{
width:125px;
height:125px;
margin-right: 5px;
background-repeat: no-repeat;
background-size: contain;
background-position: center;
float:left;
}
#bodyDiv{
width: 100%;
height: 1600px;
}
The javascript code runs through each return object that a wikipedia API returns based on a user's search term. It then puts the image in a div with class "entryImg" and the entry text in a div called "entryTxt". It then puts each of these in a div labeled outterDiv which is appended to the div already in my HTML with id "bodyDiv." My question is, in each outterDiv why are the picture and the text divs so close to each other regardless of how much I change the margins. I put 5px on the texts left margin and 5 px on the picture divs right margin as can be seen and the change isn't appearing in the browser. Why is this and how can I fix it?
based on your javascript code the generated html would be
<div id="bodyDiv">
<div class="entry">
<div class="entryImg"></div>
<div class="entryTxt">
<h2>lorem ipsum</h2>
<p>lorem ipsum</p>
</div>
</div>
</div>
and, with your css, you ca increase the space between image and text by
increasing margin-right on .entryImg
.entryImg {
margin-right: 10px;
}
or, by increasing margin-left on .entryTxt after adding overflow: hidden; on it.
.entryTxt {
margin-left: 10px;
overflow: hidden;
}
check this fiddle

How to remove old div out to the left and add a new div from the right by sliding effect using jquery?

So after trying different things for 3 hours or so, I finally decided to post a question on StackOverFlow. Here is the problem:
On click of the "next" button, I want to remove the old div by sliding it to the left and add a dynamically created div by sliding it from the right.
So far, I can only create the remove effect by sliding it to the left while fading it. But I can't add a new div sliding in from the right. How would I accomplish this?
Here is the html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Website Google Project</title>
<script src="js/jquery-1.11.3.min.js"></script>
<script src="js/jquery-ui.min.js"></script>
<script src="bootstrap-2.3.6-dist/js/bootstrap.min.js"></script>
<script type="text/javascript" src="js/scripts.js"></script>
<script type="text/javascript" src="js/secret_api.js"></script>
<link rel="stylesheet" href="bootstrap-3.3.6-dist/css/bootstrap.min.css">
<link rel="stylesheet" href="css/styles.css">
<link rel="shortcut icon" type="image/ico" href="photos/favIcon.png">
</head>
<body>
<h1 class="text-center">All Your Directions In One Spot</h1>
<div class="container">
<div class="row row-content" id="tempDiv">
<div class="col-xs-12 col-sm-6 col-sm-offset-3">
<div class="text-center">
<h2>From:</h2>
</div>
</div>
<div style="padding: 20px 20px"></div>
<div class="col-xs-12 col-sm-6 col-sm-offset-3">
<div>
<input id="origin" type="text" class="form-control input-lg" placeholder="Origin" value="8844 N Wisner St">
</div>
</div>
<div style="padding: 40px 40px"></div>
<div class="col-xs-12 col-sm-6 col-sm-offset-3">
<div class="row row-content">
<div class="text-center">
<div class="col-xs-12 col-sm-3 col-sm-offset-3">
<button class ="btn btn-lg" id="next">Next</button>
</div>
<div class="col-xs-12 col-sm-3">
<button class="btn btn-lg" id="done">Done</button>
</div>
</div>
</div>
</div>
</div>
<div style="padding: 40px 40px"></div>
<div id="listDirections">
</div>
</div>
<script src="js/scripts.js"></script>
</body>
</html>
Here is the Css:
body {
background-color: #2b669a;
}
h1 {
color: white;
font-size: 3em;
}
button {
background-color: #204056;
color: white;
font-weight: bold;
}
button:hover,
button:focus {
color: lightgray !important;
}
.directions {
background-color: whitesmoke;
color: #5A5A5A;
padding: 20px 20px;
font-size: 1.5em;
-webkit-border-radius: 8px;
-moz-border-radius: 8px;
border-radius: 8px;
margin-bottom: 20px;
}
.glyphicon-plus {
font-size: 2em;
color: white;
padding: 5px 5px;
}
.glyphicon-plus:hover {
color: coral;
cursor: pointer;
}
Here is the javascript:
function getDirections(json) {
"use strict";
var steps = json.routes[0].legs[0].steps;
var directions = [];
var counter = 1;
steps.forEach(function (step) {
directions.push(counter + ". " + step.html_instructions);
counter += 1;
});
// Separates the 2 conjoint words in the last line.
// so "Ave Destination" instead of "AveDestination"
directions[directions.length - 1] = directions[directions.length - 1].replace(/([a-z])([A-Z])/g, "$1 $2");
return directions;
}
/**
* Takes in the Google Maps API JSON object as input and returns the ETA as a string.
* #param {Object} json
* #return {string}
*/
function getEta(json) {
"use strict";
return json.routes[0].legs[0].duration.text;
}
function showDirections(json) {
"use strict";
// creates div, adds class, and appends the div
var div = document.createElement("div");
$(div).addClass("directions col-xs-12 col-sm-8 col-sm-offset-2");
$(div).append("<b>FROM: </b> " + $("#origin").val() + "<br>");
$(div).append("<b>TO: </b>" + $("#destination").val() + "<br>");
$(div).append("<em>It will take you " + getEta(json) + " to get there.</em> <p></p>");
getDirections(json).forEach(function (item) {
$(div).append("<p>" + item + "</p>");
});
$("#listDirections").append(div);
}
$('#next').click(function() {
$('#tempDiv').animate({
opacity: 0, // animate slideUp
marginLeft: '-100%',
marginRight: '100%'
}, 'fast', 'linear', function() {
$(this).remove();
});
$('.container').append($("#origin"));
});
/*
$("#next").click(function() {
// $('#tempDiv').hide('slide', {direction: 'left'}, 500).fadeOut('fast');
$('#next').show('slide', {direction: 'left'}, 500);
});
*/
$(document).ready(function () {
"use strict";
$("#getButton").click(function () {
// Get the user input
var origin = $('#origin').val().replace(/ /g, "%20");
var destination = $('#destination').val().replace(/ /g, "%20");
// Create the URL
var URL = "https://maps.googleapis.com/maps/api/directions/json?origin=" +
"" + origin + "&destination=" + destination + "&key=" + APIKEY;
// Obtain json object through GET request
$.getJSON(URL, function (json) {
console.log(getEta(json));
console.log(getDirections(json));
showDirections(json);
});
});
});
If I've understood well your question, you want to remove an "old div" animating it to the left, and then you want to create a "new div" animating it from the right. This code will helps you with that task (The comments in the code will help you to understand it):
HTML Code:
<button id="btn">Create</button>
<div id="container"></div>
JavaScript Code:
var sum = 1;
//---Function to create divs to animate
function createDiv() {
//---Disable button
active(false);
//---Access to the slide div
var slide = $("#container .slide");
//---If slide exists
if (slide.length > 0) {
//---Dissapear the slide to the left
slide.animate({
"opacity": 0,
"right": "100%"
}, function() {
//---Delete slide
$(this).remove();
//---Create new slide
var slide = create();
//---Appear slide from the right
appearSlide(slide);
});
//---If the slide no exists
} else {
//---Create slide
var slide = create();
//---Appear slide from the right
appearSlide(slide);
}
}
//---Create slide function
function create() {
var slide = $("<div/>");
slide.addClass("slide");
slide.text("div " + sum);
$("#container").append(slide);
sum++;
return slide;
}
//---Appear slide from the right function
function appearSlide(slide) {
slide.animate({
"opacity": 1,
"right": "0"
}, function() {
//---Enable button
active(true);
});
}
//---Enable / disable button function
function active(state) {
$("#btn").prop("disabled", !state);
}
//---Create a div by default
createDiv();
//---Create a alide when press the button
$("#btn").on("click", createDiv);
jsfiddle

Categories