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.
Related
So guys, I am playing with device orientation.
Here is it https://sublime.glitch.me/
Everything went well except the if condition.
If you could please look at the webpage on mobile device, you will see the png moves according to the device orientation.
But I dont want it to go off the screen, this is where I need if condition. I tried to make the evt.gamma not greater than 35 or smaller than -35 with if condition.
But apparently, what I have is not working. Sorry for my poor coding knowledge, I am a designer not a developer, can someone please help me not?
(function(b,o,i,l,e,r){b.GoogleAnalyticsObject=l;b[l]||(b[l]=
function(){(b[l].q=b[l].q||[]).push(arguments)});b[l].l=+new Date;
e=o.createElement(i);r=o.getElementsByTagName(i)[0];
e.src='//www.google-analytics.com/analytics.js';
r.parentNode.insertBefore(e,r)}(window,document,'script','ga'));
ga('create','UA-52746336-1');ga('send','pageview');
var isCompleted = {};
function sampleCompleted(sampleName){
if (ga && !isCompleted.hasOwnProperty(sampleName)) {
ga('send', 'event', 'WebCentralSample', sampleName, 'completed');
isCompleted[sampleName] = true;
}
}
var fixed = 2;
var h5logo = document.getElementById("h5logo");
var timestamp = document.getElementById("timestamp");
var alpha = document.getElementById("alpha");
var beta = document.getElementById("beta");
var gamma = document.getElementById("gamma");
/* // [START devori] */
if (window.DeviceOrientationEvent) {
window.addEventListener('deviceorientation', deviceOrientationHandler, false);
document.getElementById("doeSupported").innerText = "";
}
/* // [END devori] */
var deviceOrientationData;
function deviceOrientationHandler(evt) {
deviceOrientationData = evt;
try {
timestamp.innerText = new Date(evt.timeStamp);
alpha.innerText = evt.alpha.toFixed(fixed);
beta.innerText = evt.beta.toFixed(fixed);
gamma.innerText = evt.gamma.toFixed(fixed);
if(evt.gamma<-35){evt.gamma=-35}
if(evt.gamma>35){evt.gamma=35}
var trans = " translate("+ ((evt.gamma+20) * 2)+"px, "+ ((evt.beta-90) * -3)+"px) " ;
h5logo.style.webkitTransform = trans;
h5logo.style.transform = trans;
} catch (ex) {
document.getElementById("doeSupported").innerText = "NOT";
}
}
.h5logo {
width: 40vh;
display: block;
margin-left: auto;
margin-right: auto;
position:absolute;
z=index:10;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="style.css">
<script defer src="https://code.getmdl.io/1.2.1/material.min.js"> .
</script>
<style>
body {
margin: 2em;
}
</style>
<title>👌</title>
</head>
<body>
<div role="main" class="container">
<img src="https://cdn.glitch.com/8da575e7-c6aa-48cb-bb49-3a708f8c28fc%2Fpreview.png?1535142774062" style="display: block; position: absolute; margin-left:auto; margin-right:auto; z-index:-2">
<img id="h5logo" src="https://cdn.glitch.com/8da575e7-c6aa-48cb-bb49-3a708f8c28fc%2Fhand.png?1535129311138" class="h5logo">
<h1 style="position:absolute; z-index:-1; transform: rotate(90deg) translate(20%,-60%);">
sublime
</h1>
<p>
<b>alpha:</b> <span id="alpha"></span><br>
<b>beta:</b> <span id="beta"></span><br>
<b>gamma:</b> <span id="gamma"></span><br>
</p>
<p>
<span id="timestamp" ></span>
</p>
</div>
</body>
</html>
The lines not working are here, the translation works fine, just the if condition. Thanks so much guys.
if(evt.gamma<-35){evt.gamma=-35}
if(evt.gamma>35){evt.gamma=35}
var trans = " translate("+ ((evt.gamma+20) * 2)+"px, "+
((evt.beta-90) * -3)+"px) " ;
All event properties, including gamma are read-only, so you need to assign -35 and 35 to a new variable. See the documentation.
Example:
let newGamma = evt.gamma;
if(evt.gamma < -35){
newGamma = -35;
}
else if(evt.gamma > 35){
newGamma = 35;
}
var trans = " translate(" + ((newGamma + 20) * 2) + "px, " + ((evt.beta - 90) * -3) + "px) ";
Simpler example, using Math methods:
var trans = " translate(" + ((Math.min(Math.max(evt.gamma, -35), 35) + 20) * 2) + "px, " + ((evt.beta - 90) * -3) + "px) ";
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>
I am trying to use a counter in my complete function to make sure the animation of margin-top is completed before moving on. Right now, I have the counter in my MakeList(), and in my Spin() function, I console.log the counter and it doesn't recognize the counter++ because it fires before the animation finishes. Nobody I ask can figure out why.
** Note: I can't use timeOut's because the time is set to random (supposed to look like a slot machine ** Also, I can't find what this test platform is saying is an error, but the code runs on my machine. really the script-2.js is all i need to show to get point across though :)
// ********************************************************
// SLOT MACHINE ICONS. Each array has 3 icons for each slot
// ********************************************************
var array1 = [
'<div data-id="0" style="width:100%; background:#fff; height:150px;"></div>',
'<div data-id="1" style="width:100%; background:#ccc; height:150px;"></div>',
'<div data-id="0" style="width:100%; background:#666; height:150px;"></div>'
]
var array2 = [
'<div data-id="0" style="width:100%; background:#fff; height:150px;"></div>',
'<div data-id="1" style="width:100%; background:#ccc; height:150px;"></div>',
'<div data-id="0" style="width:100%; background:#666; height:150px;"></div>'
]
var array3 = [
'<div data-id="0" style="width:100%; background:#fff; height:150px;"></div>',
'<div data-id="1" style="width:100%; background:#ccc; height:150px;"></div>',
'<div data-id="0" style="width:100%; background:#666; height:150px;"></div>'
]
// Generates random # between 0 and 2. Used for choosing winner and creating random slots
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// Generates winning array item between coffee, tea and espresso
function win(whatArray){
var arrayItem = getRandomInt(0,2);
var winItem = whatArray[arrayItem];
return winItem;
}
// Populates each slot with random icons to spin through
var makeList = function(whatArray, whatSlot){
var slotArray = [];
for(i=0; i < 100; i++){
var randNum = getRandomInt(0,2); // Generate random number
var findItem = whatArray[randNum]; // Use random number to find associated array item
var slot = whatSlot; // Set which slot to append array item to (first, second or third)
$('#' + slot).append('<div>'+findItem+'</div>'); // Append icon to HTML
}
var winItem = win(whatArray); // Generate winning icon for slot
console.log("winner " + winItem);
$('#' + slot).append('<div>'+winItem+'</div>'); // Append winning icon to end of list
}
// Spin the slot and win some caffeine!
function Spin(){
window.counter = 0;
// Generate lists for each slot
makeList(array1, 'slot-1');
makeList(array2, 'slot-2');
makeList(array3, 'slot-3');
MoveSlots($('#slot1-wrapper'), 2500);
MoveSlots($('#slot2-wrapper'), 5200);
MoveSlots($('#slot3-wrapper'), 500);
//var running = true;
// console.log(running);
var slot1attr = $('#slot1-wrapper div').children().last().attr('data-id');
var slot2attr = $('#slot2-wrapper div').children().last().attr('data-id');
var slot3attr = $('#slot3-wrapper div').children().last().attr('data-id');
console.log('counter = ' + counter);
if(counter > 0){
if(slot1attr == slot2attr && slot1attr == slot3attr ){
console.log("WIN");
} else {
console.log("LOSE");
}
}
function MoveSlots(el, speed){
var time = speed;
time += Math.round(Math.random()*10000);
el.stop(true,true);
var marginTop = -(100 * 150 ); //change 100 to height placeholder
var running = true;
el.animate({
'margin-top':'+='+marginTop+'px'
}, {
'duration' : time,
'easing' : 'easeInOutQuint',
complete: function(){
console.log('yolo');
//$(this).on('animationend webkitAnimationEnd oAnimationEnd MSAnimationEnd', function(){
counter++;
console.log(counter);
//})
}
});
} // end MoveSlots
} // end Spin
body{
/*background-color:white;*/
padding:50px;
margin:50px;
background: #505f77 !important;
}
#slotWrapper {
width:410px;
height:150px;
margin:50px auto;
overflow: hidden;
position:relative;
border:1px solid #f00;
}
#slot1-wrapper, #slot2-wrapper, #slot3-wrapper {
margin-top:0;
position: relative;
}
.slot {
width:120px;
height:150px;
margin-right:25px;
text-align:center;
float:left;
position: absolute;
}
#slot-3 {
margin-right:0;
}
#slot-1 {
top:0;
left:0;
}
#slot-2 {
top:0;
left:145px;
}
#slot-3 {
top:0;
left:290px;
}
.slot div {
width:120px;
height:150px;
}
.slot div img {
width:100%;
}
<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>
<body>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<!-- <link rel="stylesheet" type="text/css" href="css/default.css" />
<link rel="stylesheet" type="text/css" href="css/component.css" /> -->
<div style="text-align:center">
<input type="button" value="spin!" onClick="Spin();" style="margin-top:4px;">
</div>
<div id="slotWrapper">
<div id="slot1-wrapper">
<div id="slot-1" class="slot"></div>
</div>
<div id="slot2-wrapper">
<div id="slot-2" class="slot"></div>
</div>
<div id="slot3-wrapper">
<div id="slot-3" class="slot"></div>
</div>
</div>
</body>
</html>
The problem is complete is executed asynchronously, ie the counter condition is executed is before the animations are completed.
You can use the animation promise to solve it
// ********************************************************
// SLOT MACHINE ICONS. Each array has 3 icons for each slot
// ********************************************************
var array1 = [
'<div data-id="0" style="width:100%; background:#fff; height:150px;"></div>',
'<div data-id="1" style="width:100%; background:#ccc; height:150px;"></div>',
'<div data-id="0" style="width:100%; background:#666; height:150px;"></div>'
]
var array2 = [
'<div data-id="0" style="width:100%; background:#fff; height:150px;"></div>',
'<div data-id="1" style="width:100%; background:#ccc; height:150px;"></div>',
'<div data-id="0" style="width:100%; background:#666; height:150px;"></div>'
]
var array3 = [
'<div data-id="0" style="width:100%; background:#fff; height:150px;"></div>',
'<div data-id="1" style="width:100%; background:#ccc; height:150px;"></div>',
'<div data-id="0" style="width:100%; background:#666; height:150px;"></div>'
]
// Generates random # between 0 and 2. Used for choosing winner and creating random slots
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// Generates winning array item between coffee, tea and espresso
function win(whatArray) {
var arrayItem = getRandomInt(0, 2);
var winItem = whatArray[arrayItem];
return winItem;
}
// Populates each slot with random icons to spin through
var makeList = function(whatArray, whatSlot) {
var slotArray = [];
for (i = 0; i < 100; i++) {
var randNum = getRandomInt(0, 2); // Generate random number
var findItem = whatArray[randNum]; // Use random number to find associated array item
var slot = whatSlot; // Set which slot to append array item to (first, second or third)
$('#' + slot).append('<div>' + findItem + '</div>'); // Append icon to HTML
}
var winItem = win(whatArray); // Generate winning icon for slot
console.log("winner " + winItem);
$('#' + slot).append('<div>' + winItem + '</div>'); // Append winning icon to end of list
}
// Spin the slot and win some caffeine!
function Spin() {
var counter = 0;
// Generate lists for each slot
makeList(array1, 'slot-1');
makeList(array2, 'slot-2');
makeList(array3, 'slot-3');
var p1 = MoveSlots($('#slot1-wrapper'), 2500);
var p2 = MoveSlots($('#slot2-wrapper'), 5200);
var p3 = MoveSlots($('#slot3-wrapper'), 500);
$.when(p1, p2, p3).then(function() {
//var running = true;
// console.log(running);
var slot1attr = $('#slot1-wrapper div').children().last().attr('data-id');
var slot2attr = $('#slot2-wrapper div').children().last().attr('data-id');
var slot3attr = $('#slot3-wrapper div').children().last().attr('data-id');
console.log('counter = ' + counter);
if (counter > 0) {
if (slot1attr == slot2attr && slot1attr == slot3attr) {
console.log("WIN");
} else {
console.log("LOSE");
}
}
});
function MoveSlots(el, speed) {
var time = speed;
time += Math.round(Math.random() * 10000);
el.stop(true, true);
var marginTop = -(100 * 150); //change 100 to height placeholder
var running = true;
el.animate({
'margin-top': '+=' + marginTop + 'px'
}, {
'duration': time,
'easing': 'easeInOutQuint',
complete: function() {
console.log('yolo');
counter++;
console.log(counter);
}
});
return el.promise();
} // end MoveSlots
} // end Spin
body {
/*background-color:white;*/
padding: 50px;
margin: 50px;
background: #505f77 !important;
}
#slotWrapper {
width: 410px;
height: 150px;
margin: 50px auto;
overflow: hidden;
position: relative;
border: 1px solid #f00;
}
#slot1-wrapper,
#slot2-wrapper,
#slot3-wrapper {
margin-top: 0;
position: relative;
}
.slot {
width: 120px;
height: 150px;
margin-right: 25px;
text-align: center;
float: left;
position: absolute;
}
#slot-3 {
margin-right: 0;
}
#slot-1 {
top: 0;
left: 0;
}
#slot-2 {
top: 0;
left: 145px;
}
#slot-3 {
top: 0;
left: 290px;
}
.slot div {
width: 120px;
height: 150px;
}
.slot div img {
width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.js"></script>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/redmond/jquery-ui.css" rel="stylesheet" />
<div style="text-align:center">
<input type="button" value="spin!" onClick="Spin();" style="margin-top:4px;">
</div>
<div id="slotWrapper">
<div id="slot1-wrapper">
<div id="slot-1" class="slot"></div>
</div>
<div id="slot2-wrapper">
<div id="slot-2" class="slot"></div>
</div>
<div id="slot3-wrapper">
<div id="slot-3" class="slot"></div>
</div>
</div>
im trying to make nav bar with sub menus but i keeping getting dropMenu is not defined and when i hover over the two paris links i get Uncaught TypeError: Cannot read property 'style' of null any idea what is causing this
here is my code
html
<html>
<link type="text/css" rel="stylesheet" href="vacation.css"/>
<head>
<title>Paris</title>
</head>
<body>
<div id="menus">
<div id ="parismenu">
Paris
<div id="dropmenu1" class="dropmenus">
apple
</div>
</div>
<div id ="disneymenu">
Paris
<div id="dropmenu2" class="dropmenus">
apple
</div>
</div>
</div>
</body>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
<script type="text/javascript" src="vacation.js"></script>
</html>
css
div#menus{
margin-left:16px;
}
div#menus> div{
float:left;
margin:0px 20px;
}
div.dropmenus{
display:none;
position:absolute;
top:100px;
width:120px;
background:teal;
z-index:2;
padding:4px;
border: blue 3px solid;
border-top:none;
border-radius:5px 5px 5px 5px;
}
div.dropmenus>a{
display:block;
margin:4px;
padding:7px;
font-size:14px;
text-decoration:none;
background:blue;
border-radius:3px;
color:red;
}
div#dropmenu1{
left:24px;
}
div#dropmenu2{
left:116px;
}
javascript
var fade=function(){
return{
init:function(id,flag,target){
this.elem=document.ElementById(id);
clearInterval(this.elem.si);
this.target=target ? target : flag ? 100 : 0;
this.flag = flag||1;
this.alpha = this.elem.stle.opacity ? parseFloat(this.elem.style.opacity) * 100 : 0;
this.elem.si=setIntterval(function(){fade.fadep()},20);
},
fadep:function(){
if(this.alpha==this.target){
clearInterval(this.elem.si);
}
else{
var value=Math.round(this.alpha + ((this.target - this.alpha) * .05)) +(-1 * this.flag);
this.elem.style.opacity=value/100;
this.elem.style.filter='alpha(opacity=' + value + ')';
this.alpha=value
}}}}();
var menu= ["dropmenu1","dropmenu2","dropmenu3"];
function dropMenu(x){
for(var m in menu){
if(menu[m] != x){
document.getElementById(menu[m]).style.display="none";
}}
if(document.getElementById(x).style.diplay=="block"){
fade.init(x,1);
}
else{
fade.init(x,0)}}
Your array contains three ids and your html only has the first two - so
document.getElementById(menu[m])
will be undefined if m === 2
So you need to remove "dropmenu3" from the menu array.
Also, this line:
this.elem=document.ElementById(id);
should probably be
this.elem=document.getElementById(id);
If you want to do this without jquery heres the code you will need. There were several typos in your original javascript. I also changed if so that all elements not being hovered were instantly hidden.
HTML
<div id="menus">
<div id="parismenu">
Paris
<div id="dropmenu1" class="dropmenus">
apple
</div>
</div>
<div id="disneymenu">
Paris
<div id="dropmenu2" class="dropmenus">
apple
</div>
</div>
</div>
JAVASCRIPT
var menu = ["dropmenu1", "dropmenu2"];
function dropMenu(x) {
for (var m in menu) {
if(menu[m] != x){
document.getElementById(menu[m]).style.opacity = 0;
document.getElementById(menu[m]).style.filter = 'alpha(opacity=0)';
}
}
fade.init(x, 1);
}
var fade=function(){
return{
init:function(id, flag, target){
this.elem = document.getElementById(id);
clearInterval(this.elem.si);
this.target = target ? target : flag ? 100 : 0;
this.flag = flag || -1;
this.alpha = this.elem.style.opacity ? parseFloat(this.elem.style.opacity) * 100 : 0;
this.elem.si = setInterval(function(){fade.tween()}, 20);
},
tween:function(){
if(this.alpha == this.target){
clearInterval(this.elem.si);
}else{
var value = Math.round(this.alpha + ((this.target - this.alpha) * .05)) + (1 * this.flag);
this.elem.style.opacity = value / 100;
this.elem.style.filter = 'alpha(opacity=' + value + ')';
this.alpha = value
}
}
}
}();
I left your CSS unchanged. For a working jsfiddle check this out:
http://jsfiddle.net/XfyKZ/
Why dont you just use the jquery fader? I have cleaned up your javascript and html a little bit. Instead of using the element onMouseover event Im adding a listener to that element for that event after the document is loaded.
<!-- HTML -->
<div id="menus">
<div id="parismenu">
Paris
<div id="dropmenu1" class="dropmenus">
apple
</div>
</div>
<div id="disneymenu">
Disney
<div id="dropmenu2" class="dropmenus">
apple
</div>
</div>
</div>
Then JavaScript:
$(function () {
$('.dropmenu').on('mouseover', function (event) {
$($(this).attr('data-menu-id')).fadeIn();
});
$('.dropmenu').on('mouseout', function (event) {
$($(this).attr('data-menu-id')).fadeOut();
});
});
Then Your CSS is unchanged.
Heres a JSFIDDLE showing a working example.
i have a website which have random images each time the home page is loaded. But the problem of the random images is it still loaded when i click back to home page BUTTON again. Precisely i want the random images will display ONLY when i refresh the home page not the home page button,how would i do it?
Here is the following code:
JAVASCRIPT<Head>
<script type="text/javascript">
var y1 = 20;
(document.getElementById) ? dom = true : dom = false;
var gallery = new Array();
gallery[0] = new Array("earlywork001.jpg","earlywork002.jpg","earlywork003.jpg","earlywork004.jpg","earlywor k005.jpg");
function pickImageFrom(whichGallery)
{
var idx = Math.floor(Math.random() * gallery[whichGallery].length);
document.write('<img src="images/earlywork/' + gallery[whichGallery][idx] + '" width="402" height="180">');
}
function hideIt() {
if (dom) {document.getElementById("popup").style.visibility='hidden';}
}
function showIt() {
if (dom) {document.getElementById("popup").style.visibility='visible';}
}
function placeIt() {
if (dom && !document.all) {document.getElementById("popup").style.top = window.pageYOffset + (window.innerHeight - (window.innerHeight-y1)) + "px";}
if (document.all) {document.all["layer1"].style.top = document.documentElement.scrollTop + (document.documentElement.clientHeight - (document.documentElement.clientHeight-y1)) + "px";}
window.setTimeout("placeIt()", 10); }
</script>
</head>
HTML<Body>
<body onLoad="placeIt(); showIt()">
/*code*/
<div id="content"><!--Start content-->
<div id="popup" style="position:absolute; left:140px; width:410px; height:20px; visibility:hidden">
<div style="background-color:white; padding:3px; border:1px solid black">
<span style="float:right; background-color:gray; color:white; font-weight:bold; width='20px'; text-align:center; cursor:pointer" onclick="javascript:hideIt()"> X </span>
<script language="javascript">pickImageFrom(0);</script></div>
</div>
<img src="images/home.png" width="644" height="363" alt="home" class="content" />
</div><!--End content-->
</div><!--End body content-->
/*code*/
I ran into some trouble searching for a similar solution sometime ago so I wrote this and I'm pasting it here in case somebody else comes to search this again.
window.onload = choosePic;
var images = new Array("https://randomuser.me/api/portraits/men/2.jpg", "https://randomuser.me/api/portraits/women/2.jpg", "https://randomuser.me/api/portraits/men/52.jpg", "https://randomuser.me/api/portraits/women/12.jpg", "https://randomuser.me/api/portraits/women/7.jpg", "https://randomuser.me/api/portraits/men/27.jpg", "https://randomuser.me/api/portraits/women/13.jpg", "https://randomuser.me/api/portraits/women/4.jpg", "https://randomuser.me/api/portraits/men/52.jpg", "https://randomuser.me/api/portraits/men/6.jpg", "https://randomuser.me/api/portraits/men/23.jpg", "https://randomuser.me/api/portraits/women/41.jpg", "https://randomuser.me/api/portraits/women/28.jpg");
function choosePic(){
var randomNum = Math.floor(Math.random() * images.length);
document.getElementById("random-image").src = images[randomNum];
}
<img src="" alt="me" id="random-image">
Wrap your code in an if:
if (document.URL == document.referrer) {
// your code here
}
The document.referrer will get you the url of the previous page. Match it to the current url in document.URL. If both do not match, then your page was navigated to from another page.