Changing Iframes HTML - javascript

I need a script to change the iframes src every certain amount of seconds. The time between the change is different between each one.
Example:
Page Loads
Google.com is loaded.
15 seconds later
Yahoo.com is loaded.
37 seconds later
Ask.com is loaded.
12 seconds later
Dogpile.com is loaded.
and so on and so forth.
I've tried that:
<html>
<head>
<meta charset="utf-8" />
<title>Monitor Presidência</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/1.11.8/semantic.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/1.11.8/semantic.min.js"></script>
</head>
<body>
<div style="width: 100%; display: flex;">
<div class="ui teal progress" data-percent="0" id="example1" style="width: 90%;margin-bottom: 0px">
<div class="bar"></div>
</div>
<div class="ui icon buttons" style="width: 10%">
<button class="ui button" style="width: 25%" onclick="menos_um()">
<i class="left chevron icon"></i>
</button>
<button class="ui button " style="width: 25%" onclick="inicia()">
<i class="play icon"></i>
</button>
<button class="ui button" style="width: 25%" onclick="para_aplicacao()">
<i class="pause icon"></i>
</button>
<button class="ui button" style="width: 25%" onclick="mais_um()">
<i class="right chevron icon"></i>
</button>
</div>
</div>
<iframe id="envase" class="frame_mon" style="width: 100%;height: 100%;" src="www.google.com.br"></iframe>
<iframe id="frete_hl" class="frame_mon" style="width: 100%;height: 100%;display: none;" src="www.yahoo.com.br"></iframe>
<iframe id="frete_hl_acum" class="frame_mon" style="width: 100%;height: 100%;display: none;" src="www.terra.com.br"></iframe>
</body>
<script>
var arr_monitores = ["envase", "frete_hl", "frete_hl_acum"];
var num_monitor = 0;
var progresso = 0;
var myVar;
var setintervalatualizaframe;
function mais_um() {
/* if (num_monitor === 2) {
num_monitor = 0;
} else {
num_monitor++;
}
$('.frame_mon').css('display', 'none');
document.getElementById(arr_monitores[num_monitor]).style.display = "";*/
progresso = 100;
myStopFunction();
inicia();
/* if (num_monitor === 2) {
num_monitor = 0;
} else {
num_monitor++;
}*/
};
function menos_um() {
//progresso = 100;
if (num_monitor === 0) {
num_monitor = 2;
} else {
num_monitor--;
}
$('.frame_mon').css('display', 'none');
document.getElementById(arr_monitores[num_monitor]).style.display = "";
progresso = 0;
myStopFunction();
inicia();
};
function inicia() {
clearInterval(setintervalatualizaframe);
myStopFunction();
myVar = setInterval(function () {
if (progresso === 100) {
progresso = 0;
if (num_monitor === 2) {
location.reload();
//num_monitor = 0;
} else {
num_monitor++;
}
$('.frame_mon').css('display', 'none')
document.getElementById(arr_monitores[num_monitor]).style.display = "";
};
progresso++;
progresso++;
$('#example1').data('percent', progresso);
$('#example1').progress();
}, 3800);
}
function myStopFunction() {
clearInterval(myVar);
//atualiza_frame();
}
inicia();
function para_aplicacao(){
clearInterval(myVar);
atualiza_frame();
}
function atualiza_frame() {
clearInterval(setintervalatualizaframe);
setintervalatualizaframe = setInterval(function () {
document.getElementById(arr_monitores[num_monitor]).src=document.getElementById(arr_monitores[num_monitor]).src;
},1);
}
</script>
</html>

The way you are using setInterval and setTimeout is not properly
handled, as it creates a timer id to schedule execution. 0
A much more efficient way is to use the Promises async library, which is displayed below. 1
For websites that won't work, they are using a response header that won't allow their pages to be framed. You can work around this with some back-end program, where the server loads the web files then forwards them. 2
<!DOCTYPE html>
<html>
<head>
<title> Hello </title>
<style>
iframe {
display: block;
width: 1000px;
height: 500px;
margin-left: auto;
margin-right: auto;
}
iframe:focus {
outline: none;
}
button {
display: block;
margin: auto auto;
}
label {
display: block;
margin-left: auto;
margin-right: auto;
}
input {
display: block;
margin: auto auto;
}
</style>
</head>
<body>
<div id='main'>
<button id='wait' onclick='wait()'>Wait</button>
<label>Seconds</label>
<input type='number' id='seconds' placeholder='milliseconds'>
<button id='switching' onclick='webSwitch()'>Switch sites</button>
<iframe id='switchMe' src='https://codepen.io'></iframe>
</div>
<script>
//Array of webpages
var webList = ["https://www.bing.com", "https://www.walmart.com","https://www.codepen.io"];
//For tracking position in array
var count = 0;
//Function to be ran by event
function webSwitch() {
console.log('I have been called');
if (count >= webList.length) {
count = 0;
}
//Setting new URL
document.getElementById('switchMe').src = webList[count];
//Make sure to use next URL
count++;
}
function wait() {
console.log('Click!');
var numMS = document.getElementById('seconds').value;
sleep(numMS).then(() => {
webSwitch();
})
}
function sleep (time) {
return new Promise((resolve) => setTimeout(resolve, time));
}
</script>
</body>
</html>

Related

How to allow user to change font size

I am making a google docs like app, and I want the user to be able to select the text, and then change the size to whatever they want. I tried to use variables but it didn't work so I am not sure what to do. Is there any way to allow the user to change the font size and if so how?
Here is the code for the app:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Editor</title>
<link rel="stylesheet" href="index.css" />
</head>
<body>
<button class="bold" onclick="document.execCommand('bold',false,null);">
𝗕
</button>
<button class="italic" onclick="document.execCommand('italic',false,null);">
𝘐
</button>
<button
class="underline"
onclick="document.execCommand('underline',false,null);"
>
U̲
</button>
<input
type="color"
class="color-picker"
id="colorPicker"
oninput="changeColorText(this.value);"
/>
<label>Select color</label>
<button id="highlight"><mark>Highlight</mark></button>
<fieldset class="userInput" contenteditable="true"></fieldset>
<script>
var boldBtn = document.querySelector(".bold");
var italicBtn = document.querySelector(".italic");
var underlineBtn = document.querySelector(".underline");
var colorPicker = document.querySelector(".color-picker");
var highlightBtn = document.querySelector("#highlight");
boldBtn.addEventListener("click", function () {
boldBtn.classList.toggle("inUse");
});
italicBtn.addEventListener("click", function () {
italicBtn.classList.toggle("inUse");
});
underlineBtn.addEventListener("click", function () {
underlineBtn.classList.toggle("inUse");
});
highlightBtn.addEventListener("click", function () {
highlightBtn.classList.toggle("inUse");
});
const changeColorText = (color) => {
document.execCommand("styleWithCSS", false, true);
document.execCommand("foreColor", false, color);
};
document
.getElementById("highlight")
.addEventListener("click", function () {
var range = window.getSelection().getRangeAt(0),
span = document.createElement("span");
span.className = "highlight";
span.appendChild(range.extractContents());
range.insertNode(span);
});
</script>
</body>
</html>
I think this is the output you want. Also, don't use document.execCommand, it has been deprecated
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Editor</title>
<link rel="stylesheet" href="index.css" />
</head>
<body>
<button class="bold" onclick="document.execCommand('bold',false,null);">
𝗕
</button>
<button class="italic" onclick="document.execCommand('italic',false,null);">
𝘐
</button>
<button
class="underline"
onclick="document.execCommand('underline',false,null);"
>
U̲
</button>
<input
type="color"
class="color-picker"
id="colorPicker"
oninput="changeColorText(this.value);"
/>
<label>Select color</label>
<button id="highlight"><mark>Highlight</mark></button>
<input
type="number"
class="font-size"
id="fontSize"
/>
<label>Select Font Size</label>
<fieldset class="userInput" contenteditable="true"></fieldset>
<script>
var boldBtn = document.querySelector(".bold");
var italicBtn = document.querySelector(".italic");
var underlineBtn = document.querySelector(".underline");
var colorPicker = document.querySelector(".color-picker");
var fontSize = document.querySelector("#fontSize");
var highlightBtn = document.querySelector("#highlight");
var userInput = document.querySelector('.userInput');
boldBtn.addEventListener("click", function () {
boldBtn.classList.toggle("inUse");
});
italicBtn.addEventListener("click", function () {
italicBtn.classList.toggle("inUse");
});
underlineBtn.addEventListener("click", function () {
underlineBtn.classList.toggle("inUse");
});
highlightBtn.addEventListener("click", function () {
highlightBtn.classList.toggle("inUse");
});
const changeColorText = (color) => {
document.execCommand("styleWithCSS", false, true);
document.execCommand("foreColor", false, color);
};
fontSize.addEventListener('input', updateValue);
function updateValue(e) {
userInput.style.fontSize = `${e.target.value}px`;
}
document
.getElementById("highlight")
.addEventListener("click", function () {
var range = window.getSelection().getRangeAt(0),
span = document.createElement("span");
span.className = "highlight";
span.appendChild(range.extractContents());
range.insertNode(span);
});
</script>
</body>
</html>
Add this to your HTML:
<button class="font-smaller">-</button>
<button class="font-bigger">+</button>
Add this to your JS:
const fontSmaller = document.querySelector(".font-smaller");
const fontBigger = document.querySelector(".font-bigger");
let fontSize = 15.5; // play with this number if needed
fontSmaller.addEventListener("click", () => {
document.querySelector(".userInput").style.fontSize = `${fontSize--}px`;
});
fontBigger.addEventListener("click", () => {
document.querySelector(".userInput").style.fontSize = `${fontSize++}px`;
});
Change as needed. This will change the size of the whole text.
You can implement it like this.
// Increase/descrease font size
$('#increasetext').click(function() {
curSize = parseInt($('#content').css('font-size')) + 2;
if (curSize <= 32)
$('#content').css('font-size', curSize);
});
$('#resettext').click(function() {
if (curSize != 18)
$('#content').css('font-size', 18);
});
$('#decreasetext').click(function() {
curSize = parseInt($('#content').css('font-size')) - 2;
if (curSize >= 14)
$('#content').css('font-size', curSize);
});
header {
text-align: center;
}
/* text-controls */
button {
vertical-align: bottom;
margin: 0 0.3125em;
padding: 0 0.3125em;
border: 1px solid #000;
background-color: #fff;
font-weight: bold;
}
button#increasetext {
font-size: 1.50em;
}
button#resettext {
font-size: 1.25em;
}
button#decreasetext {
font-size: 1.125em;
}
.textcontrols {
padding: 0.625em 0;
background: #ccc;
}
/* content */
#content {
margin: 3em 0;
text-align: left;
}
/* demo container */
#container {
width: 90%;
margin: 0 auto;
padding: 2%;
}
#description {
margin-bottom: 1.25em;
text-align: left;
}
#media all and (min-width: 700px) {
#container {
width: 700px;
}
button {
margin: 0 0.625em;
padding: 0 0.625em;
}
}
<div id="container">
<header>
<h1 id="title">
Allow Users to Change Font Size
</h1>
<p>Click the buttons to see it in action</p>
<div class="textcontrols">
<button role="button" id="decreasetext" <span>smaller</span>
</button>
<button role="button" id="resettext">
<span>normal</span>
</button>
<button role="button" id="increasetext">
<span>bigger</span>
</button>
</div>
<!--/.textcontrols-->
</header>
<main id="content" role="main">
<div id="description">
<h2>Allow users to resize text on the page via button controls.</h2>
<p>In this instance, users can decrease text, increase text, or reset it back to normal.</p>
<h2>Set default text size with CSS</h2>
<p>The default text size must be set using an internal stylesheet in the header of your page. In this case: <code>font-size: 1.125em</code> (aka, 18px).</p>
<h2>Set the controls with JavaScript</h2>
<p>Then we set the resize controls with JavaScript. In this example, we're resizing all text within the div with an id of "content".</p>
<p>The controls check the current text size, and then changes it (or not) accordingly.</p>
</div>
<!--/#description-->
</main>
<!--/#content-->
</div>
<!--/#container-->

Dynamic PageNumbers for Flipbook using turn.js

So, I was given a task of creating a Custom Flipbook, where using images in div tags, I was successful in creating one. Users could turn pages using prev/next buttons or flipping through them by the corners like shown for other Flipbooks.
My concern is Displaying PageNumbers. Changing pages through the buttons, pages change dynamically but when flipping through turn.js the page number does not update.
I am providing the snippet of the code that I have used. Any kind of help and guidance is appreciated !!
<!DOCTYPE html>
<head>
<title>Flipbook Demo</title>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script type="text/javascript" src="turn.min.js"></script>
</head>
<style>
body{
background-color: #313131;
}
#flipbook {
margin-top: 1.5%;
margin-left: 6%;
width: 1130px;
height: 800px;
position: relative;
overflow: hidden;
}
#nav_controls{
margin: 1.5%;
margin-left: 44%;
}
</style>
<body>
<h1 style="color: white; margin-left: 43%">FITI5 WHITEPAPER</h1>
<div id="flipbook">
<!-- Include Pages into div that you want to include -->
</div>
<div id="nav_controls">
<button id="startdoc"><-</button>
<button id="prev_page"> PREV </button>
<span id="pgnos" style="margin-left: 2%; color: white;">1</span>
<button id="next_page" style="margin-left: 2%;"> NEXT </button>
<button id="enddoc">-></button>
<!--
<button id="zoom-in">+</button>
<buton id="zoom-out">-</button>-->
</div>
<script type="text/javascript">
const startButton = document.querySelector("#startdoc");
const endButton = document.querySelector("#enddoc");
const prevButton = document.querySelector("#prev_page");
const nextButton = document.querySelector("#next_page");
const showPG = document.querySelector("#pgnos");
//magnify = document.querySelector("#zoom-in");
//minify = document.querySelector("#zoom-out");
/*
magnify.addEventListener('click', function() {
$("#flipbook").turn("zoom", 1.1, 1);
});
minify.addEventListener('click', function() {
$("#flipbook").turn("zoom", 1, 1.1);
})
*/
$("#flipbook").turn({
gradients: true,
page: 1,
duration: 2000
});
const first_page = $("#flipbook").turn("page");
const last_page = $("#flipbook").turn("pages");
startButton.addEventListener('click', function() {
$("#flipbook").turn("page", first_page);
showPG.innerHTML = first_page;
});
endButton.addEventListener('click', function() {
$('#flipbook').turn("page", last_page);
showPG.innerHTML = last_page;
});
nextButton.addEventListener('click', function() {
$("#flipbook").turn("next");
showPG.innerHTML = $("#flipbook").turn("page");
});
prevButton.addEventListener('click', function() {
$("#flipbook").turn("previous");
showPG.innerHTML = $("#flipbook").turn("page");
});
if ( (($("#flipbook").turn("page") == first_page)) ) {
$(nextButton).click(function() {
$("#flipbook").animate({left: "275"});
});
$(endButton).click(function() {
$("#flipbook").animate({left: "565"});
});
$(prevButton).click(function() {
$("#flipbook").animate({left: "275"});
});
$(startButton).click(function() {
$("#flipbook").animate({left: "0"});
});
}
if ( (($("#flipbook").turn("page") == last_page)) ) {
$(prevButton).click(function() {
$("#flipbook").animate({left: "300"});
});
}
</script>
</body>
</html>

Problem with image 'rotations' within a div element

I'm using the code below to create a 'rotation' of images for display on a website. I wish for the images to display within a 'div' element...and i'm having trouble accomplishing that. It seems the problem is when I attempt to set each image as the 'background image' for the element (the line that reads "document.getElementById("rotation").style.backgroundImage = "url(toString(ImgName[number]))";). Only the initial image displays, without any 'rotation' of other images. Any help appreciated, this is becoming very frustrating.
<!DOCTYPE html>
<html>
<title>test page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<head>
<style>
div.rotation {
height: 256px;
width: 100%;
padding: 0px;
background-color: powderblue;
border-style: solid;
border-width: 5px;
border-radius: 25px;
}
</style>
</head>
<body>
<div class="w3-quarter">
<div class="w3-padding-small">
<div class="w3-center">
<div class="rotation">
<p>
<img src='images/rotation/LA_Panel.png' id='rotateImg0' alt='image rotation' />
<img src='images/rotation/McCulloch_256.png' id='rotateImg1' style='display:none;' alt='image rotation' />
<img src='images/rotation/MO_Panel.png' id='rotateImg2' style='display:none;' alt='image rotation' />
<img src='images/rotation/Rommel.png' id='rotateImg3' style='display:none;' alt='image rotation' />
</p>
</div>
</div>
</div>
</div>
</body>
</html>
<script type='text/javascript'>
var rotation = function () {
var currentImage,
images = [],
ImgName = [],
count,
hideImages,
showImage,
fn;
count = (function () {
// Figure out how many images we have on the rotation
var x = 0;
while (document.getElementById('rotateImg' + (x + 1).toString())) {
images[x] = document.getElementById('rotateImg' + x.toString());
ImgName[x] = document.getElementById('rotateImg' + x.toString()).src;
x++;
}
return images.length;
})();
hideImages = function () {
// Hide all the images
for (var i = 0; i < count; i++) {
images[i].style.display = 'none';
}
};
showImage = function (number) {
document.getElementById("rotation").style.backgroundImage = "url(toString(ImgName[number]))";
images[number].style.display = 'block';
};
fn = {};
fn.setupRotation = function () {
// Show the first image
currentImage = 0;
showImage(currentImage);
// Start the rotation
var interval = setInterval(rotation.advanceRotation, 4000);
};
fn.advanceRotation = function () {
if (currentImage + 1 == count)
currentImage = 0;
else
currentImage++;
hideImages();
showImage(currentImage);
};
return fn;
} ();
rotation.setupRotation();
</script>
One thought might be to pluck off the first child and slam him to the end of the line.
let images = document.querySelector('#images');
setInterval(() => {
let el = images.removeChild(images.childNodes[0]);
images.appendChild(el);
}, 1000);
#images {
font-size: 0;
}
.img {
display: inline-block;
width: 30px;
height: 30px;
}
<div id="images">
<div class="img" style="background-color: red"></div>
<div class="img" style="background-color: orange"></div>
<div class="img" style="background-color: yellow"></div>
<div class="img" style="background-color: green"></div>
<div class="img" style="background-color: blue"></div>
</div>

Fruit ninja type game in javascript

I'm trying to make a ninja fruit style game in javascript but problems are happening. I have this if statements that compare the variable "fruit" with the index of the "fruits" array. The problem is when I "eliminate" a fruit the other if statements doenst work.
That's how the game needs to work:
1 You start the game, a random name of a fruit appears for you to click on.
2 You click in the image of the fruit and it disappears, in this click another random fruit is generated.
3 An then you finish the game, that's prety much this.
So it's kind hard to explain, but its the same logic as the ninja fruit game. And I dont know if I need to use the shift function to eliminate the fruits in the array as well.
var fruits = ['Banana', 'Apple', 'Pineapple'];
var fruit = fruits[Math.floor(Math.random() * fruits.length)];
document.getElementById("frut").innerHTML = fruit;
if (fruit == fruits[0]) {
bana.onclick = function() {
var fruit = fruits[Math.floor(Math.random() * fruits.length)];
document.getElementById("frut").innerHTML = fruit;
bana.style.display = "none";
}
}
if (fruit == fruits[1]) {
app.onclick = function() {
var fruit = fruits[Math.floor(Math.random() * fruits.length)];
document.getElementById("frut").innerHTML = fruit;
app.style.display = "none";
}
}
if (fruit == fruits[2]) {
pin.onclick = function() {
var fruit = fruits[Math.floor(Math.random() * fruits.length)];
document.getElementById("frut").innerHTML = fruit;
pin.style.display = "none";
}
}
function movFruit() {
document.getElementById("info").style.display = "table";
document.getElementById("fruitAnimation").style.display = "table";
document.getElementById("insructions").style.display = "none";
var elem = document.getElementById("fruitAnimation");
var pos = 0;
var id = setInterval(frame, 10);
function frame() {
if (pos == 350) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + 'px';
}
}
}
#fruitAnimation {
position: relative;
display: none;
margin: 0 auto;
}
.fr {
float: left;
padding: 80px;
}
#info {
display: none;
margin: 0 auto;
}
#insructions {
display: table;
margin: 0 auto;
margin-top: 200px;
border: 1px solid black;
padding: 10px;
}
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">
<title>JSfruit</title>
</head>
<body>
<div id="info">
<h1>Fruit: <span id="frut"></span></h1>
</div>
<button onclick="movFruit() " style="display: table; margin: 0 auto;"><h4>Start the game</h4></button>
<div id="fruitAnimation">
<div class="fr" id="bana">
<img src="https://orig00.deviantart.net/5c87/f/2016/322/8/9/banana_pixel_art_by_fireprouf-daosk9z.png" width="60" height="60">
</div>
<div class="fr" id="app">
<img src="https://art.ngfiles.com/images/404000/404664_thexxxreaper_pixel-apple.png?f1454891997" width="60" height="60">
</div>
<div class="fr" id="pin">
<img src="https://i.pinimg.com/originals/c2/f9/e9/c2f9e9f8d332da97a836513de98f7b29.jpg" width="60" height="60">
</div>
</div>
<span id="insructions">Click in the fruits and erase them!</span>
</body>
</html>
Right now, you're only attaching handlers to the fruit images at the top level, in your if statements - but once those statements run and the main block finishes, it doesn't get run again.
You should attach handlers to all fruit images at once in the beginning, and then in the handlers, check to see the clicked fruit was valid.
If you're assigning text to an element, assign to textContent, not innerHTML; textContent is quicker, safer, and more predictable.
const fruits = ['Banana', 'Apple', 'Pineapple'];
const getRandomFruit = () => {
const randomIndex = Math.floor(Math.random() * fruits.length);
const fruit = fruits[randomIndex];
document.getElementById("frut").textContent = fruit;
fruits.splice(randomIndex, 1);
return fruit;
};
let fruitToClickOn = getRandomFruit();
bana.onclick = function() {
if (fruitToClickOn !== 'Banana') return;
bana.style.display = "none";
fruitToClickOn = getRandomFruit();
}
app.onclick = function() {
if (fruitToClickOn !== 'Apple') return;
app.style.display = "none";
fruitToClickOn = getRandomFruit();
}
pin.onclick = function() {
if (fruitToClickOn !== 'Pineapple') return;
pin.style.display = "none";
fruitToClickOn = getRandomFruit();
}
function movFruit() {
document.getElementById("info").style.display = "table";
document.getElementById("fruitAnimation").style.display = "table";
document.getElementById("insructions").style.display = "none";
var elem = document.getElementById("fruitAnimation");
var pos = 0;
var id = setInterval(frame, 10);
function frame() {
if (pos == 350) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + 'px';
}
}
}
#fruitAnimation {
position: relative;
display: none;
margin: 0 auto;
}
.fr {
float: left;
padding: 80px;
}
#info {
display: none;
margin: 0 auto;
}
#insructions {
display: table;
margin: 0 auto;
margin-top: 200px;
border: 1px solid black;
padding: 10px;
}
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">
<title>JSfruit</title>
</head>
<body>
<div id="info">
<h1>Fruit: <span id="frut"></span></h1>
</div>
<button onclick="movFruit() " style="display: table; margin: 0 auto;"><h4>Start the game</h4></button>
<div id="fruitAnimation">
<div class="fr" id="bana">
<img src="https://orig00.deviantart.net/5c87/f/2016/322/8/9/banana_pixel_art_by_fireprouf-daosk9z.png" width="60" height="60">
</div>
<div class="fr" id="app">
<img src="https://art.ngfiles.com/images/404000/404664_thexxxreaper_pixel-apple.png?f1454891997" width="60" height="60">
</div>
<div class="fr" id="pin">
<img src="https://i.pinimg.com/originals/c2/f9/e9/c2f9e9f8d332da97a836513de98f7b29.jpg" width="60" height="60">
</div>
</div>
<span id="insructions">Click in the fruits and erase them!</span>
</body>
</html>

How to pause and start gif using jQuery AJAX

I am a student and I am trying to start, pause and start a gif when a user clicks the gif, however I am stuck on how to add in this click function. I know that the the gif version of the object is .images.fixed_height.url and the still image is .images.fixed_height_still.url . If I try to append like below $(this) I get that images is undefined. How would I go by doing this? Currently 10 gifs show when you click the category. Thank you for any help in advance.
Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Giphy</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<style>
body {
background-image: url('http://www.efoza.com/postpic/2011/04/elegant-blue-wallpaper-designs_154158.jpg');
width: 100%;
}
button {
padding: 0 2%;
margin: 0 2%;
}
h4 {
font-size: 165%;
font-weight: bold;
color: white;
}
.container {
background-color: rgba(0, 0, 0, 0.2);
max-width: 1000px;
width: 100%;
}
.btn {
margin-top: 2%;
margin-bottom: 2%;
font-size: 125%;
font-weight: bold;
}
.guide {
padding: 3% 0 0 0;
}
.tag-row {
padding: 3% 0 0 0;
}
.category-row {
padding: 3% 0 ;
}
#photo {
padding-bottom: 3%;
}
</style>
</head>
<body>
<div class="container">
<div class="row text-center guide"><h4>Click a category and see the current top 10 most popular giphy's of that category!</h4></div>
<div class="row text-center tag-row" id="tags"></div>
<div class="row text-center category-row">
<input type="" name="" id="category"><button class="btn btn-secondary" id="addTag">Add Category</button>
</div>
</div>
<div class="container">
<div id="photo"></div>
</div>
<script src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
<script type="text/javascript">
var tags = ["dog", "dolphin", "whale", "cat", "elephant", "otter"];
// Function for displaying movie data
function renderButtons() {
$("#tags").empty();
for (var i = 0; i < tags.length; i++) {
$("#tags").append('<button class="tag-buttons btn btn-primary">' + tags[i] + '</button>');
}
}
// Add tags function //
$(document).on('click', '#addTag', function(event) {
event.preventDefault();
var newTag = $("#category").val().trim();
tags.push(newTag);
$("#tags").append('<button class="tag-buttons btn btn-primary">' + newTag + '</button>');
});
// Tag button function //
$(document).on('click', '.tag-buttons', function(event) {
// Keeps page from reloading //
event.preventDefault();
var type = this.innerText;
console.log(this.innerText);
var queryURL = "http://api.giphy.com/v1/gifs/search?q=" + window.encodeURI(type) + "&limit=10&api_key=dc6zaTOxFJmzC";
$.ajax({
url: queryURL,
method: "GET"
}).done(function(response) {
for (var i = 0; i < response.data.length; i++) {
$("#photo").append('<img src="' + response.data[i].images.fixed_height_still.url + '" class="animate">');
$('.animate').on('click', function() {
$(this).remove().append('<img src="' + response.data[i].images.fixed_height.url + '" class="animate">');
console.log($(this));
});
}
});
$("#photo").empty();
});
renderButtons();
</script>
</body>
</html>
The difference between fixed_height and fixed_height_still will solve the problem. if you look closely the urls differ only by name_s.gif and name.gif.
So you can simply swap the two images to create a player. This will act like a play and stop. Not play and pause. But in a small gif I don't think pause really matter, stop and pause will look similar.
adding class name to the #photo
$("#photo").append('<img class="gif" src="' + response.data[i].images.fixed_height_still.url + '">');
event handler which will control play and stop
$('body').on('click', '.gif', function() {
var src = $(this).attr("src");
if($(this).hasClass('playing')){
//stop
$(this).attr('src', src.replace(/\.gif/i, "_s.gif"))
$(this).removeClass('playing');
} else {
//play
$(this).addClass('playing');
$(this).attr('src', src.replace(/\_s.gif/i, ".gif"))
}
});
jsfiddle demo
https://jsfiddle.net/karthick6891/L9t0t1r2/
you can use this jquery plugin http://rubentd.com/gifplayer/
<img class="gifplayer" src="media/banana.png" />
<script>
$('.gifplayer').gifplayer();
</script>
you can control like this
Use these methods to play and stop the player programatically
$('#banana').gifplayer('play');
$('#banana').gifplayer('stop');
youll find more details here https://github.com/rubentd/gifplayer

Categories