slideshow with page numbers javascript - javascript

I have created slideshow. I want to add some description with page numbers.
I was trying to add function sliderText() to get result - "Image 1 of 7" etc.
I don't know what is wrong here. Can somebody give me some hints?
Thank you in advance,
Megi
var img_index = 0;
var imgs = [
"assets/1.jpg",
"assets/2.jpg",
"assets/3.jpg",
"assets/4.jpg",
"assets/5.jpg",
"assets/6.jpg",
"assets/7.jpg"
];
function findNextImage(isPrev) {
switch (true) {
case !!(isPrev && imgs[img_index + 1]):
img_index += 1
return imgs[img_index]
case !!imgs[img_index + 1]:
img_index += 1
return imgs[img_index]
default:
img_index = 0
return imgs[img_index]
}
sliderText()
}
function checkKey(event) {
if (event.keyCode == '39') {
document.getElementById("images").src = findNextImage();
} else if (event.keyCode == '37') {
document.getElementById("images").src = findNextImage(true);
}
}
document.onkeydown = checkKey;
function sliderText() {
var text = document.getElementsByClassName("slideshow_text");
var imageNumber = img_index + 1;
text.innerHTML = "image " + imageNumber + " of " + imgs.length;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>test</title>
</head>
<h1 class="slideshow_text">Image 1 of 7</h1>
<img id="images" src="assets/1.jpg" />
<body>
</body>
<script src="test.js"></script>
</html>

Some modifications to improve code quality
I removed findNextImage which was not a pure function and introduced findNextImageIndex instead: findNextImageIndex neither accesses nor modifies any external variables and is thus easier to read. sliderText takes imgIndex as an argument so that you can easily see what parameters it needs to set the text.
Further suggestions
Consider moving the pre-set values Image 1 of 7 and "assets/1.jpg" from HTML to JavaScript as well. Initialize the slider with "assets/1.jpg" taken from the array and call sliderText(state.imgIndex); once initially.
Please notice that I moved the slide show HTML inside the <body> to make it valid HTML.
Modified code
var state = {
imgIndex: 0
};
var imgs = [
"assets/1.jpg",
"assets/2.jpg",
"assets/3.jpg",
"assets/4.jpg",
"assets/5.jpg",
"assets/6.jpg",
"assets/7.jpg"
];
function findNextImageIndex(imgIndex, isPrev) {
if(isPrev) {
if(imgIndex <= 0) {
return imgs.length - 1;
} else {
return imgIndex - 1;
}
} else {
if(imgIndex >= imgs.length - 1) {
return 0;
} else {
return imgIndex + 1;
}
}
}
function sliderText(imgIndex) {
var text = document.getElementsByClassName("slideshow_text")[0];
var imageNumber = imgIndex + 1;
text.innerHTML = "image " + imageNumber + " of " + imgs.length;
}
function goToNextImage(isPrev) {
state.imgIndex = findNextImageIndex(state.imgIndex, isPrev);
document.getElementById("images").src = imgs[state.imgIndex];
sliderText(state.imgIndex);
}
function checkKey(event) {
switch(event.keyCode) {
case 37: goToNextImage(true); break;
case 39: goToNextImage(false); break;
}
}
document.onkeydown = checkKey;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>test</title>
</head>
<body>
<h1 class="slideshow_text">Image 1 of 7</h1>
<img id="images" src="assets/1.jpg" />
<script src="test.js"></script>
</body>
</html>

Related

Why is the default running even though the num is set to 1?

let spans = document.querySelector(`#spans`);
let hrs = document.querySelector(`#hrs`);
let mins = document.querySelector(`#mins`);
let secs = document.querySelector(`#secs`);
let start = document.querySelector(`#start`);
let stop = document.querySelector(`#stop`);
spans.style.fontSize = "10em";
let preFix = 0;
let num = 1;
let secspreNum= 0;
let minspreNum = 0;
let hrspreNum = 0;
let myFunc = ()=> {
setInterval(()=>{
switch (num){
case num===1:
mins.innerHTML = `0` + num;
num ===0;
secs.innerHTML =`0`+ num++;
default:
console.log(`default test`)
}
} , 1000);
};
start.addEventListener(`click`,myFunc)
<!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.0">
<title>Document</title>
</head>
<body>
<div id="spans">
<span id="hrs">00</span>:<span id="mins">00</span>:<span id="secs">00</span><br></div>
<button id="start">Start</button>
<button id="stop">Stop</button>
<script src="go2.js"></script>
</body>
</html>
Hello, I'm trying to make a stopwatch atm but I got stuck into a problem. Trying to use the switch statement to set the mins to add up a number if the secs reach 10. But before doing that I've been testing this switch statement and for some reason it runs default statement instead of case . Why is it like that? I set the num variable to 1 and it still runs the default one instead of num===1 . Did I missunderstood something? Thanks !
Here is a working version
I changed your querySelector and unnecessary template literals
let spans = document.getElementById('spans');
let hrs = document.getElementById('hrs');
let mins = document.getElementById('mins');
let secs = document.getElementById('secs');
let start = document.getElementById('start');
let stop = document.getElementById('stop');
let tId;
let num = 0;
let myFunc = () => {
clearInterval(tId);
tId = setInterval(function() {
const date = new Date(null); // alternatively calculate hh,mm,ss using %60
date.setSeconds(++num);
const [hh, mm, ss] = date.toISOString().substr(11, 8).split(":");
hrs.textContent = hh;
mins.textContent = mm;
secs.textContent = ss;
}, 1000)
};
start.addEventListener('click', myFunc)
stop.addEventListener('click', function() {
clearInterval(tId)
})
#spans {
font-size: 10em
}
<!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.0">
<title>Document</title>
</head>
<body>
<div id="spans">
<span id="hrs">00</span>:<span id="mins">00</span>:<span id="secs">00</span><br></div>
<button id="start">Start</button>
<button id="stop">Stop</button>
<script src="go2.js"></script>
</body>
</html>
try this:
let myFunc = ()=> {
setInterval(()=> {
switch (num) {
case 1:
console.log(num)
mins.innerHTML = `0` + num;
secs.innerHTML =`0`+ (num++);
break;
default:
console.log(`default test`)
}
} , 1000);
};
case takes constants and not expressions afaik. You also have to break or the code will "fall through" to the next condition.

How can I reset time in a simple game?

I've tried make simple clicking game (if time count is higher than 5, the game is over, but you can reset time if you click generated element).
Unfortunately time is still counting. How can I fix this?
Why do I get this error?
Uncaught TypeError: Cannot set property 'textContent' of null
at js.js:8
at js.js:49
(function() {
const startGame = document.querySelector('button')
let time = 0;
let roll = true;
let h2 = document.querySelector('h2')
h2.textContent = time;
const timeFlow = () => {
time++
}
const resetTime = () => {
time = 0;
console.log(time)
}
const rollBall = () => {
if (roll == true) {
let divCreator = document.createElement('div')
document.body.appendChild(divCreator)
divCreator.classList.add('square')
divCreator.style.backgroundColor = 'red'
divCreator.style.top = Math.floor(Math.random() * 99) + '%'
divCreator.style.left = Math.floor(Math.random() * 99) + '%'
divCreator.addEventListener('click', letsPlay)
divCreator.addEventListener('click', resetTime)
setInterval(timeFlow, 1000)
} else if (roll == false) {
roll = true;
}
}
const letsPlay = (e) => {
let start = document.body.removeChild(e.target)
roll = false;
if (time >= 5) {
alert('U lost')
} else {
rollBall()
}
}
startGame.addEventListener('click', rollBall)
})();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<button>Generate</button>
<script src='js.js'></script>
<h2>Time</h2>
</body>
</html>
You can use the load event instead of an IIFE before the elements exist.
Also your div needs dimensions
Also I assume you want the time in the H2?
Also you need position absolute to move the div
Lastly I clear the interval before a new one
window.addEventListener("load", function() {
const startGame = document.querySelector('button')
const h2 = document.querySelector('h2')
let tId;
let time = 0;
let roll = true;
h2.textContent = time;
const timeFlow = () => {
time++
h2.textContent = time;
}
const resetTime = () => {
time = 0;
}
const rollBall = () => {
if (roll == true) {
let divCreator = document.createElement('div')
document.body.appendChild(divCreator)
divCreator.classList.add('square');
divCreator.style.height = '50px'
divCreator.style.width = '50px'
divCreator.style.backgroundColor = 'red'
divCreator.style.position = 'absolute'
divCreator.style.top = Math.floor(Math.random() * 99) + '%'
divCreator.style.left = Math.floor(Math.random() * 99) + '%'
divCreator.addEventListener('click', letsPlay)
divCreator.addEventListener('click', resetTime)
clearInterval(tId); // remove any running interval
tId = setInterval(timeFlow, 1000)
}
roll = !roll;
}
const letsPlay = (e) => {
let start = document.body.removeChild(e.target)
roll = false;
if (time >= 5) {
alert('U lost')
} else {
roll = true; // right?
rollBall()
}
}
startGame.addEventListener('click', rollBall)
})
body {
height: 100%;
background-color: yellow;
}
<button>Generate</button>
<h2>Time</h2>
Your HTML code is in the wrong order: the <h2> element and the <script> element should be switched.
You should change it like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<button>Generate</button>
<h2>Time</h2>
<script src='js.js'></script>
</body>
</html>

Javascript settimeout () not working [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 5 years ago.
I am a javascript learner
Hear is my javascript
I have a javascript function named get();
which i call it onload.
function get() {
for (var i = 1; i <= 5; i++) {
setTimeout(function() {
console.log('Value of i : ' + i);
}, 100);
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
</head>
<body onload="get();">
</body>
</html>
The expected output is
Value of i : 1
Value of i : 2
Value of i : 3
Value of i : 4
Value of i : 5
where as i am getting
Value of i : 6
Not able to figure out what is exactly is wrong .
The correct approach to to do this is :
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
</head>
<script>
function get() {
for (var i = 1; i <= 5; i++) {
setTimeout(function(x) {
console.log('Value of i : ' + x);
}(i), 100);
}
}
</script>
<body onload="get();">
</body>
</html>
Notice the (i) in :
setTimeout(function(x) {
console.log('Value of i : ' + x);
}(i), 100);
}
this is how you pass values to a settimeout function.
You can use let that has its own scope or you can create a closure there.
Using let
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
</head>
<script>
function get() {
for (let i = 1; i <= 5; i++) {
setTimeout(function() {
console.log('Value of i : ' + i);
}, 100);
}
}
</script>
<body onload="get();">
</body>
</html>
Closure snippet
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
</head>
<script>
function get() {
for (let i = 1; i <= 5; i++) {
setTimeout(((function(i) {
return function() {
console.log('Value of i : ' + i);
}
})(i)), 100);
}
}
</script>
<body onload="get();">
</body>
</html>

Dynamic video Quiz in Javascript

I have 10 YouTube links and I want to be able to move to the next video by pressing the next button.
My code:
var videoLinks = ["https://www.youtube.com/embed/QIMo0jFbfQs", "http://www.youtube.com/v/L8NGOUrw8UU"];
var v = 0;
$("#next").on('click', function(){
next() + 1;
function next(){
if(v == videoLinks.length){
//v = 0;
}
$(".content").html(" <iframe src= ' " + videoLinks[v] + "'> "+ "</iframe>");
}
});
Note: I only included 2 links for testing.
You basically need a way to keep track of the vid count. Local Storage would be good for this. The button would increment the video counter and reset the value if you reached the end. The counter would be a reference to the video source value.
Use a simple replace to change the video source, embed the video, and then increment the counter.
It can be seen here: https://jsbin.com/dehoxo/edit?html,js,console,output
$(document).ready(function(){
$('#nextBtn').click(function(e){
e.preventDefault();
alert();
var vidIndex = parseInt(localStorage.getItem("vidIndex"));
var vids = ['https://www.youtube.com/embed/VT4gri_n0iM',
'https://www.youtube.com/embed/DWooSca2rCw',
'https://www.youtube.com/embed/MukFRbS_5Gw'];
var vidToken = '<iframe width="420" height="315" src="{{SRC}}" frameborder="0" allowfullscreen></iframe>';
if (vidIndex) {
if (vidIndex >= vids.length) {
vidIndex = 0;
}
}
else {
if (!vidIndex && vidIndex !==0) {
vidIndex = 0;
}
}
var currentVid = vidToken.replace('{{SRC}}', vids[vidIndex]);
$('#vidBox').html(currentVid);
$('#vidIndex').val(vidIndex);
vidIndex++;
localStorage.setItem('vidIndex', vidIndex);
});
});
The HTML
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div id="vidBox">
NO VID
</div>
<button id="nextBtn">Next Vid</button>
<input id="vidIndex"/>
</body>
</html>
var videoLinks = [link1, link2, link3, ...];
var v = 0;
var iframe = $('iframe');
iframe.attr('src', videoLinks[0]);
$("#next").on('click', function(){
v++;
if(v >= videoLinks.length){
v = 0;
}
iframe.attr('src', videoLinks[v]);
});
Try this, it's a little more concise and easier to read:
var videoLinks = ["https://www.youtube.com/embed/QIMo0jFbfQs", "https://www.youtube.com/embed/L8NGOUrw8UU"];
var v = 0;
$("#next").on('click', function() {
$(".content").html(" <iframe src= ' " + videoLinks[v] + "'> " + "</iframe>");
v == videoLinks.length - 1 ? v = 0 : v++;
});
JSFiddle

Failure to use accelerometer with HTML and JavaScript

I wonder why things go wrong is the application that I'm doing?
He did not start playing when I shake the phone.
I followed the instructions on this site, http://software.intel.com/pt-br/articles/create-handbell-using-html5-and-phonegap, but I do not quite understand how it works.
Here is the code:
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=320; user-scalable=no" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>BellShapes</title>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8">
function onLoad(){
// Aguardar o carregamento do Cordova
document.addEventListener("deviceready", onDeviceReady, false);
// inicialização
bellrightring = document.getElementById("bellrightring");
bellleftring = document.getElementById("bellleftring");
bellleft = document.getElementById("bellleft");
bellright = document.getElementById("bellright");
bellcenter = document.getElementById("bellcenter");
// inicialização da mídia
bellsound = new Media("/android_asset/www/resources/bell.mp3",
onRingSuccess(bellsound), onRingError);
bellend = new Media("/android_asset/www/resources/bell-end.mp3",
onRingSuccess(bellend), onRingError);
}
function sign(val, delta) {
if (typeof delta == undefined) delta=0
if (val > 0 && Math.abs(val)-delta > 0) return 1;
else if (val<0 && Math.abs(val)-delta > 0) return -1;
else return 0;
}
function isShaking(last, current, threshold) {
var deltaX = Math.abs(last.x - current.x),
deltaY = Math.abs(last.y - current.y),
deltaZ = Math.abs(last.z - current.z);
return ((deltaX > threshold && deltaY > threshold) ||
(deltaX > threshold && deltaZ > threshold) ||
(deltaY > threshold && deltaZ > threshold) || deltaX > threshold);
}
accelID = navigator.accelerometer.watchAcceleration(onSuccess, onError, options);
function onSuccess(acceleration) {
var x = acceleration.x;
var y = acceleration.y;
var z = acceleration.z;
var t = false;
if (previous){
if (isShaking(previous, acceleration, 10)){
moveBell(sign(x));
bellsound.play();
accelerated = true;
}
else {
stopBell(acceleration);
if (accelerated == true){
bellend.play();
}
accelerated = false;
}
}
previous = acceleration;
}
</script>
</head>
<body id="onLoad">
<div id="handbell">
<div id="bellcenter" class="position"></div>
<div id="bellright" class="position"></div>
<div id="bellleft" class="position"></div>
<div id="bellrightring" class="ring"></div>
<div id="bellleftring" class="ring"></div>
</div>
</body>
</html>
I do not know much about javascript, so I would appreciate if you could explain in a simpler way.
In your body tag you have written
<body id="onLoad">
This should be
<body onLoad="onLoad()">
You need to have the function onLoad called when the page loads.
Alternatively, you could remove the id and forget about the onload in the body tag.
Then add this one line to the Javascript.
window.addEventListener("load", onLoad);

Categories