I am trying to animate a show / div using javascript. The code works fine but i want it to open and close at 500 speed.
The code i have is this:
<a id="show-map" href="javascript:toggle();">Show Map</a>
<div id="top-map" style="display: none">
<h2>Hello</h2>
</div>
<script language="javascript">
function toggle() {
var ele = document.getElementById("top-map"),
text = document.getElementById("show-map");
if(ele.style.display == "block") {
ele.style.display = "none";
text.innerHTML = "Show Map";
} else {
ele.style.display = "block";
text.innerHTML = "Hide Map";
}
}
</script>
Based on an example posted by keypaul here I've adapted your code and shortened the example a bit for you:
<a id="show-map" href="javascript:toggle();">Show Map</a>
<div id="top-map" style="display: none">
<h2>Hello</h2>
</div>
<script language="javascript">
var ele = document.getElementById("top-map"),
text = document.getElementById("show-map");
function setTime(state) {
if (state === "out") {
for (var i = 1; i <= 100; i++) {
setTimeout("fadeOut(" + (100 - i) + ")", i * 5);
}
} else {
for (var i = 1; i <= 100; i++) {
setTimeout("fadeIn(" + (0 + i) + ")", i * 5);
}
}
}
function fadeOut(opacity) {
ele.style.opacity = opacity / 100;
if (opacity === 1) {
ele.style.display = "none";
}
}
function fadeIn(opacity) {
ele.style.opacity = opacity / 100;
if (opacity === 1) {
ele.style.display = "block";
}
}
function toggle() {
if(ele.style.display == "block") {
setTime("out");
text.innerHTML = "Show Map";
} else {
setTime("in");
text.innerHTML = "Hide Map";
}
}
</script>
you need to use time functions like setInterval or requestAnimationFrame
here is an example of setInterval
//to fade out
fadeout_interval = setInterval(function(el){
el.style.opacity -= 0.1;
if(el.style.opacity<=0) clearInterval(fadeout_interval);
}, 30, ele);
alternatively you can use css to do the same thing
Related
I have a JSFiddle that shows my code now:
https://jsfiddle.net/qtu1xgw3/2/
Basically there is an image button (pink flower) and then there are 4 images that change when the button is clicked.
Now the issue is that I want the button to hide when I get to the last image. Right now I need to click the button twice to get it to hide on the last image. But I want with the last click of the button to hide it at the same time that the last image in the gallery is shown.
One of the images is in the html part of the code, which might be what causes this issue, I think, but I'm not sure how to do this differently without breaking the code?
(random images from google used for the sake of testing)
HTML:
<div class="test">
<div class="desc">
<h2 id="title_text">test1</h2>
<p id="under_text">test2</p>
</div>
<div id="pink">
<img src="https://images.vexels.com/media/users/3/234325/isolated/lists/cba2167ec09abeeee327ffa0f994151b-detailed-flower-illustration.png" onclick="imagefun()"></div>
<div class="game">
<img src="https://images.vexels.com/media/users/3/143128/isolated/lists/2a84565e7c9642368346c7e6317fa1fa-flat-flower-illustration-doodle.png" id="getImage"></div>
</div>
CSS:
.game img {
width: 300px;
height: auto;
}
.test {
display: flex;
flex-direction: row;
}
JS:
var counter = 0,
gallery = ["https://cdn.cloudflare.steamstatic.com/steamcommunity/public/images/apps/914750/aab494aa7cde1991d0a86cc28ec6debdbee37d7f.jpg", "https://api.assistivecards.com/cards/gardening/flowers.png", "https://i.pinimg.com/474x/7d/10/75/7d1075cf259131c942037683d2243bb0.jpg"],
imagefun = function () {
if (counter >= gallery.length) {
document.getElementById("title_text").innerHTML = "test3"; document.getElementById("under_text").innerHTML = "test4"; document.getElementById("pink").style.display = "none";
}
else{
document.getElementById("getImage").src = gallery[counter];
counter++;
}
};
I have made some change to your code. It will help you.
var counter = 0,
gallery = ["https://cdn.cloudflare.steamstatic.com/steamcommunity/public/images/apps/914750/aab494aa7cde1991d0a86cc28ec6debdbee37d7f.jpg", "https://api.assistivecards.com/cards/gardening/flowers.png", "https://i.pinimg.com/474x/7d/10/75/7d1075cf259131c942037683d2243bb0.jpg"],
imagefun = function () {
if (counter == gallery.length -1) {
document.getElementById("getImage").src = gallery[counter];
document.getElementById("pink").style.display = "none";
}
else{
document.getElementById("getImage").src = gallery[counter];
counter++;
}
};
try this
Evaluate when the counter is equal to the size of your array if so then do the job you want
imagefun = function () {
if(counter==gallery.length)
{
document.getElementById("getImage").style.display = "none";
}
if (counter >= gallery.length) {
document.getElementById("title_text").innerHTML = "test3";
document.getElementById("under_text").innerHTML = "test4";
document.getElementById("pink").style.display = "none";
}
else{
document.getElementById("getImage").src = gallery[counter];
counter++;
}
};
The issue is that you increment your counter after the counter >= gallery.length check.
The correct solution is:
const gallery = [
"https://cdn.cloudflare.steamstatic.com/steamcommunity/public/images/apps/914750/aab494aa7cde1991d0a86cc28ec6debdbee37d7f.jpg",
"https://api.assistivecards.com/cards/gardening/flowers.png",
"https://i.pinimg.com/474x/7d/10/75/7d1075cf259131c942037683d2243bb0.jpg",
];
let counter = 0;
document.getElementById("getImage").src = gallery[counter];
function imagefun() {
counter += 1;
document.getElementById("getImage").src = gallery[counter];
if (counter >= gallery.length - 1) {
document.getElementById("title_text").innerHTML = "test3";
document.getElementById("under_text").innerHTML = "test4";
document.getElementById("pink").style.display = "none";
}
};
I am currently trying to enable a disabled button, once a certain action is complete. In this case, a progress bar reaching 100%. My button looks like this:
var i;
function move() {
if (i == 0) {
i = 1;
var elem = document.getElementById("myBar");
var width = 10;
var id = setInterval(frame, 100);
function frame() {
if (width >= 100) {
clearInterval(id);
i = 0;
} else {
width++;
elem.style.width = width + "%";
elem.innerHTML = width + "%";
}
}
}
}
<div id="myProgress">
<div id="myBar">0%</div>
</div>
<br><button onclick="move()">Run Experiment</button><br>
<button disabled id="btn1" onclick="location.href='https://google.com'" type="button">
Go to Google</button>
I'm thinking that there must be a possibility to have some sort of if else condition in the button itself. Ideally, I could do this in the body.
You already have a working conditional to stop the progress bar updates when 100% is reached. This is the place where you can activate the button. You can wrap that code to another function.
var i = 0;
function move() {
if (i == 0) {
i = 1;
var elem = document.getElementById("myBar");
var width = 10;
var id = setInterval(frame, 100);
function frame() {
if (width >= 100) {
// Enable the button when the progres is 100%
var button = document.getElementById("btn1");
button.disabled = false;
button.innerHTML = "enabled Button";
clearInterval(id);
i = 0;
} else {
width++;
elem.style.width = width + "%";
elem.innerHTML = width + "%";
}
}
}
}
<button disabled id="btn1" type="button">disabled Button</button>
<div id="myProgress">
<div id="myBar">0%</div>
</div>
<br><button onclick="move()">Run Experiment</button><br>
I reduced timer to 10 ms to make snippet more representative
function move() {
var i=0;
if (i == 0) {
i = 1;
var elem = document.getElementById("myBar");
var width = 10;
var id = setInterval(frame, 10);
function frame() {
if (width >= 100) {
clearInterval(id);
i = 0;
document.getElementById("btn1").disabled = false;
} else {
width++;
elem.style.width = width + "%";
elem.innerHTML = width + "%";
}
}
}
}
<div id="myProgress">
<div id="myBar">0%</div>
</div>
<br><button onclick="move()">Run Experiment</button><br>
<button disabled="enabled" id="btn1" onclick="location.href='https://google.com'" type="button">
Go to Google</button>
var progressContainer=document.getElementById("myProgress");
var progress = document.getElementById("myBar");
var googleBtn =document.getElementById("btn1");
var loading = false;
function move() {
if(loading)return;
loading =true;
var id = setInterval(frame, 50);
var width =parseInt(progress.offsetWidth /progressContainer.offsetWidth);
function frame() {
if (width >= 100) {
clearInterval(id);
googleBtn.disabled = false;
loading = false;
return;
}
width++;
progress.style.width = width + "%";
progress.innerHTML = width + "%";
}
}
#myProgress{
width:200px;
height:20px;
border:1px solid black;
background-color:#bbb;
}
#myBar{
width:0px;
background-color:green;
}
<div id="myProgress">
<div id="myBar">0%</div>
</div>
<br><button onclick="move()">Run Experiment</button><br>
<button disabled="enabled" id="btn1" onclick="location.href='https://google.com'" type="button">
Go to Google</button>
I am making a small game where in I have 50 buttons and when I click on any one of the button, its color changes and amongst them, I have one button which is blue in color. If the player clicks on that blue button, he is a winner. He will be given only three chances. I have used a button eventhandler that takes the color id and accordingly changes the color. But the colorId from the count is 51 and not amongst the 1 - 50 buttons. What is wrong?
<html>
<head>
<title>Blue-Box</title>
</head>
<body>
<script>
var colorId;
var button;
var noOfTries = 3;
function createButtons() {
colorId = 0;
for (var index = 0; index <= 50; index++) {
button = document.createElement("button");
button.innerHTML = "box " + index;
button.id = colorId;
button.setAttribute("value", colorId);
button.setAttribute("text", colorId);
button.style.fontFamily = "Times New Roman";
button.style.backgroundColor = "#C0C0C0";
button.style.fontSize = "15px";
document.body.appendChild(button);
colorId++;
button.addEventListener("click", selectColor);
}
}
function selectColor() {
console.log((colorId));
console.log("button click");
if (noOfTries > 0) {
noOfTries = noOfTries - 1;
if ((colorId) <= 24) {
console.log("red color")
document.getElementById(colorId).style.backgroundColor = "#BC8F8F";
}
else if (colorId == 25) {
console.log("blue color")
document.getElementById(colorId).style.backgroundColor = "#0099CC";
document.write("You Won the game");
noOfTries = 3;
}
else if (colorId > 25 && colorId < 51) {
document.getElementById(colorId).style.backgroundColor = "#008080";
}
}
else {
document.write("Your attempts have finished");
}
}
</script>
<div id="divbox">
<button id="buttonbox" onclick="createButtons()">Click to start the Game</button>
</div>
</body>
</html>
Hope this helps you.
<html>
<head>
<title>Blue-Box</title>
</head>
<body>
<script>
var colorId = 1;
var button;
var lives = 0;
function createButtons(){
colorId=0;
for(var index=1;index<=50;index++){
button=document.createElement("button");
button.innerHTML="box "+index;
button.id=colorId;
button.setAttribute("value",colorId);
button.setAttribute("text",colorId);
button.style.fontFamily="Times New Roman";
button.style.backgroundColor="#C0C0C0";
button.style.fontSize="15px";
button.addEventListener("click", function(){
selectColor(this.id);
})
document.getElementById("btnbox").appendChild(button);
colorId++;
}
}
function selectColor(colorId){
lives++;
if(lives < 4){
if (colorId<=24){
document.getElementById(colorId).style.backgroundColor="#BC8F8F";
}
else if (colorId==25){
document.getElementById(colorId).style.backgroundColor="#0099CC";
alert("Winner");
location.reload();
}
else{
document.getElementById(colorId).style.backgroundColor="limegreen";
}
}
else if(lives == 4){
alert("Game over!");
location.reload();
}
}
</script>
<div id="divbox">
<button id="buttonbox" onclick="createButtons()">Click to start the Game</button>
</div>
<div id="btnbox">
</div>
</body>
// first add a global variable
var noOfTries = 3;
function selectColor() {
// check if greater than 3
if(noOfTries > 0) {
// if yes, then decrement
noOfTries = noOfTries - 1;
// continue with the color change
if (colorId<=24) {
document.getElementById(colorId).style.backgroundColor="#BC8F8F";
}
else if (colorId==25) {
document.getElementById(colorId).style.backgroundColor="#0099CC";
}
else {
document.getElementById(colorId).style.backgroundColor="limegreen";
}
}
}
Use:
button.addEventListner("click",function() {
button.style.backgroundColor=nextColor;
})
I'm trying to make a little game. Kinda stupid, but I want there to be this random event that pops up and does a little CSS Keyframe animation. The end goal is to get it to pop up when the random event triggers, and then go away when the animation is over. When running the code, I can get it to work the first time, but the second time the animation doesn't trigger and only the text shows up. Any ideas?
var myFood = document.getElementById("myFood");
var myWood = document.getElementById("myWood");
var myGold = document.getElementById("myGold");
var myButton = document.getElementById("myButton");
var output = document.getElementById("output");
var randomFoodEvent = document.getElementById("event");
var foodCount = 0;
var woodCount = 0;
var goldCount = 0;
myButton.addEventListener("click", buttonClick, false);
window.addEventListener("keydown", keydownHandler, false);
function keydownHandler(event) {
console.log("keyCode = " + event.keyCode);
if (event.keyCode === 13) {
buttonClick();
} else if (event.keyCode === 70) {
foodCount++;
myFood.innerHTML = "<strong>F</strong>ood: " + foodCount;
var randomFoodNum = Math.floor(Math.random() * 100) + 1;
if (randomFoodNum === 50) {
randomFoodEvent.className = "playEvent";
randomFoodEvent.innerHTML = "Some villagers stole your food!";
foodCount = foodCount - 25;
}
} else if (event.keyCode === 87) {
woodCount++;
myWood.innerHTML = "<strong>W</strong>ood: " + woodCount;
} else if (event.keyCode === 71) {
goldCount++;
myGold.innerHTML = "<strong>G</strong>old: " + goldCount;
}
}
randomFoodEvent.addEventListener("animationend", function() {
randomFoodEvent.classList.remove = "playEvent";
randomFoodEvent.innerHTML = "";
});
function buttonClick() {
console.log("Button Clicked!");
if ((foodCount >= 100) && (woodCount >= 100) && (goldCount >= 100)) {
output.textContent = "You win!";
}
}
/* The animation code */
#keyframes example {
from {
background-color: red;
}
to {
background-color: yellow;
}
}
/* The element to apply the animation to */
.playEvent {
animation-name: example;
animation-duration: 4s;
}
<h1>Buttons and Keyboard Events</h1>
<p id="output">
Get 100 Food, 100 Wood, and 100 Gold to Win the Game!
</p>
<p id="myFood"><strong>F</strong>ood: 0</p>
<p id="myWood"><strong>W</strong>ood: 0</p>
<p id="myGold"><strong>G</strong>old: 0</p>
<p id="event">
</p>
<button id="myButton">Click Me to Win</button>
Sorry that there's a lot of code, I couldn't think of a better way to show what I'm trying to do without showing the whole thing.
Thanks!
EDIT: Heres a JSFiddle
Syntax error randomFoodEvent.classList.remove("playEvent");
var myFood = document.getElementById("myFood");
var myWood = document.getElementById("myWood");
var myGold = document.getElementById("myGold");
var myButton = document.getElementById("myButton");
var output = document.getElementById("output");
var randomFoodEvent = document.getElementById("event");
var foodCount = 0;
var woodCount = 0;
var goldCount = 0;
myButton.addEventListener("click", buttonClick, false);
window.addEventListener("keydown", keydownHandler, false);
function keydownHandler(event) {
console.log("keyCode = " + event.keyCode);
if (event.keyCode === 13) {
buttonClick();
} else if (event.keyCode === 70) {
foodCount++;
myFood.innerHTML = "<strong>F</strong>ood: " + foodCount;
var randomFoodNum = Math.floor(Math.random() * 100) + 1;
if (randomFoodNum === 50) {
randomFoodEvent.className = "playEvent";
randomFoodEvent.innerHTML = "Some villagers stole your food!";
foodCount = foodCount - 25;
}
} else if (event.keyCode === 87) {
woodCount++;
myWood.innerHTML = "<strong>W</strong>ood: " + woodCount;
} else if (event.keyCode === 71) {
goldCount++;
myGold.innerHTML = "<strong>G</strong>old: " + goldCount;
}
}
randomFoodEvent.addEventListener("animationend", function() {
randomFoodEvent.classList.remove("playEvent");
randomFoodEvent.innerHTML = "";
});
function buttonClick() {
console.log("Button Clicked!");
if ((foodCount >= 100) && (woodCount >= 100) && (goldCount >= 100)) {
output.textContent = "You win!";
}
}
/* The animation code */
#keyframes example {
from {
background-color: red;
}
to {
background-color: yellow;
}
}
/* The element to apply the animation to */
.playEvent {
animation: example 4s 1;
}
<!doctype.html>
<html>
<head>
<title>
Keyboards and Buttons
</title>
</head>
<body>
<h1>Buttons and Keyboard Events</h1>
<p id="output">
Get 100 Food, 100 Wood, and 100 Gold to Win the Game!
</p>
<p id="myFood"><strong>F</strong>ood: 0</p>
<p id="myWood"><strong>W</strong>ood: 0</p>
<p id="myGold"><strong>G</strong>old: 0</p>
<p id="event">
</p>
<button id="myButton">Click Me to Win</button>
</body>
</html>
After following two YouTube lessons, I now have a nice arrow widget that fades in, rotates to 180 degrees and fades out controlled from one button. I do not know how to make the arrow rotate back to 0 on the second click of this button.
Probably not the most elegant of code, but here we are:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Fade In and Out</title>
<style type="text/css">
div.contentbox {
width: 50px;
height: 50px;
padding: 20px;
opacity: 0;
}
</style>
<script type="text/javascript">
var fade_in_from = 0;
var fade_out_from = 10;
function fadeIn(element) {
var target = document.getElementById(element)
target.style.display = "block";
var newSetting = fade_in_from / 10;
target.style.opacity = newSetting;
fade_in_from++;
if(fade_in_from == 10) {
target.style.opacity = 1;
clearTimeout(loopTimer);
fade_in_from = 0;
return false;
}
var loopTimer = setTimeout('fadeIn(\''+element+'\')', 50);
}
function fadeOut(element) {
var target = document.getElementById(element)
var newSetting = fade_out_from / 10;
target.style.opacity = newSetting;
fade_out_from--;
if(fade_out_from == 0) {
target.style.opacity = 0;
clearTimeout(loopTimer);
fade_out_from = 10;
return false;
}
var loopTimer = setTimeout('fadeOut(\''+element+'\')', 50);
}
var looper;
var degrees = 0;
function rotateAnimation(el,speed)
{
var elem = document.getElementById(el);
if(navigator.userAgent.match("Chrome")){
elem.style.WebkitTransform = "rotate("+degrees+"deg)";
} else if(navigator.userAgent.match("Firefox")){
elem.style.MozTransform = "rotate("+degrees+"deg)";
} else if(navigator.userAgent.match("MSIE")){
elem.style.msTransform = "rotate("+degrees+"deg)";
} else if(navigator.userAgent.match("Opera")){
elem.style.OTransform = "rotate("+degrees+"deg)";
} else {
elem.style.transform = "rotate("+degrees+"deg)";
}
looper = setTimeout ('rotateAnimation(\''+el+'\','+speed+')',speed);
degrees++;
if(degrees > 179){
clearTimeout(looper)
}
}
</script>
</head>
<body>
<button onmouseover="fadeIn('arrow_box')": onmouseout="fadeOut('arrow_box')": onclick="rotateAnimation('arrow',5)">fade in/out</button>
<div id="arrow_box" class="contentbox"><img id="arrow" img src="images/Arrow.png" width="50" height="50" alt="Arrow" /></div>
</body>
</html>
Please help.
Create a new variable to remember the direction and then increment or decrement the degrees depending on which direction you want to go.
Here is a JSfiddle link of a working solution.
var looper;
var degrees = 0;
var direction = 0;
function rotateAnimation(el,speed){
var elem = document.getElementById(el);
if(navigator.userAgent.match("Chrome")){
elem.style.WebkitTransform = "rotate("+degrees+"deg)";
}else if(navigator.userAgent.match("Firefox")){
elem.style.MozTransform = "rotate("+degrees+"deg)";
}else if(navigator.userAgent.match("MSIE")){
elem.style.msTransform = "rotate("+degrees+"deg)";
}else if(navigator.userAgent.match("Opera")){
elem.style.OTransform = "rotate("+degrees+"deg)";
}else {
elem.style.transform = "rotate("+degrees+"deg)";
}
looper = setTimeout
('rotateAnimation(\''+el+'\','+speed+')',speed);
if(direction === 0){
degrees++;
if(degrees > 179){
direction = 1;
clearTimeout(looper);
}
}else {
degrees--;
if(degrees < 1){
direction = 0;
clearTimeout(looper);
}
}
}