today I decided to learn how to make sliders (carousel) , I must point out that I am pretty much new to JavaScript.
First I tried to think how I should code that myself, I had no inspiration or ideas whatsoever. (Just pointless ideas) , so I went to watch youtube in hope of "enlightment" and there were solutions, but a bit too advanced for me to understand.(and long)
After that I googled "how to make sliders" and I found something simpler on w3schools. At first, I was a bit confused, but after a while I started to understand it bit by bit, of course, not totally.
So here comes the question, can someone explain me what each line does and how it affects the others? Or if there is a better and easier method, I would love to hear it.
Here is the javascript file(followed by CSS and HTML), I only modified a few variable names to understand them better and replaced var with let or const:
let index = 1;
showDivs(index);
function plusSlide(value) {
showDivs(index += value);
}
function showDivs(value) {
let i;
let slider = document.getElementsByClassName("slides");
if (value > slider.length) {
index = 1;
}
if (value < 1) {
index = slider.length;
}
for (i = 0; i < slider.length; i++) {
slider[i].style.display = "none";
}
slider[index - 1].style.display = "block";
}
.sliders {
display: flex;
width: 400px;
height: 200px;
}
input[type="button"] {
width: 100px;
}
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<link rel="stylesheet" href="css.css" type="text/css">
</head>
<body>
<input type="button" value="Back" onclick="plusSlide(-1)">
<input type="button" value="Forward" onclick="plusSlide(+1)">
<div class="sliders">
<img src="https://via.placeholder.com/150/0000FF/FFFFFF/?text=image1" width="400" height="200" class="slides">
<img src="https://via.placeholder.com/150/FF00FF/FFFFFF/?text=image2" width="400" height="200" class="slides">
<img src="https://via.placeholder.com/150/00FFFF/FFFFFF/?text=image3" width="400" height="200" class="slides">
</div>
<script src="scripts.js"></script>
</body>
</html>
This specific approach works like this:
(Explaining in comments)
let index = 1; // Initializes index variable to point to the first element
// of your slide array we'll see later
showDivs(index);
function plusSlide(value) {
showDivs(index += value); // This function just increments your index value
// and displays the next slide
}
function showDivs(value) {
let i;
/*
You get the array of slides from the dom using the class name slides
*/
let slider = document.getElementsByClassName("slides");
if (value > slider.length) { // in case we completed a full circle, we go
//from the start again
index = 1;
}
if (value < 1) { // in case we try to go left beyond number 1, we display
// the last one ( to achieve the circular ux experience )
index = slider.length;
}
for (i = 0; i < slider.length; i++) {
slider[i].style.display = "none"; // Hides every slider
}
slider[index - 1].style.display = "block"; // Shows only our index slider
}
I don't think this is the best approach. Because every time you want to change slide, every slide from the DOM element is retrieved, and its style is changed. You change the display state of every slide in every click. In my opinion you can
use the document.getElementsByClassName("slides"); only one time outside
of the function, in a greater scope and thus make your changes.
Also I wouldn't try to iterate through every slide and hide it. I would just
nitialize every slide to have their display equal to "none" and in every showDiv
I would just hide my current index ( before the incremention) and just show next one. Like this:
const slider = document.getElementsByClassName("slides");
function showDivs(value) {
slider[index-1].style.display = "none"; // hides our current slider before
// the incremention
if (value > slider.length) {
index = 1;
}
if (value < 1) {
index = slider.length;
}
slider[index - 1].style.display = "block"; // Shows only our index slider
}
.sliders {
display: none;
width: 400px;
height: 200px;
}
Related
I want to make a slot machine. I am taking random index from array and populating it inside my div. But the only issue is that I want to have a slot machine effect. I mean that the effect should be like numbers are dropping from top to bottom. This is my code so far.
var results = [
'PK12345',
'IN32983',
'IH87632',
'LK65858',
'ND82389',
'QE01233'
];
// Get a random symbol class
function getRandomIndex() {
return jQuery.rand(results);
}
(function($) {
$.rand = function(arg) {
if ($.isArray(arg)) {
return arg[$.rand(arg.length)];
} else if (typeof arg === "number") {
return Math.floor(Math.random() * arg);
} else {
return 4; // chosen by fair dice roll
}
};
})(jQuery);
// Listen for "hold"-button clicks
$(document).on("click", ".wheel button", function() {
var button = $(this);
button.toggleClass("active");
button.parent().toggleClass("hold");
button.blur(); // get rid of the focus
});
$(document).on("click", "#spin", function() {
// get a plain array of symbol elements
var symbols = $(".wheel").not(".hold").get();
if (symbols.length === 0) {
alert("All wheels are held; there's nothing to spin");
return; // stop here
}
var button = $(this);
// get rid of the focus, and disable the button
button.prop("disabled", true).blur();
// counter for the number of spins
var spins = 0;
// inner function to do the spinning
function update() {
for (var i = 0, l = symbols.length; i < l; i++) {
$('.wheel').html();
$('.wheel').append('<div style="display: none;" class="new-link" name="link[]"><input type="text" value="' + getRandomIndex() + '" /></div>');
$('.wheel').find(".new-link:last").slideDown("fast");
}
if (++spins < 50) {
// set a new, slightly longer interval for the next update. Makes it seem like the wheels are slowing down
setTimeout(update, 10 + spins * 2);
} else {
// re-enable the button
button.prop("disabled", false);
}
}
// Start spinning
setTimeout(update, 1);
});
// set the wheels to random symbols when the page loads
$(function() {
$(".wheel i").each(function() {
this.className = getRandomIndex(); // not using jQuery for this, since we don't need to
});
});
.wheel {
width: 25%;
float: left;
font-size: 20px;
text-align: center;
}
.wheel .fa {
display: block;
font-size: 4em;
margin-bottom: 0.5em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<div id="wheels">
<div class="wheel clearfix">
</div>
<!-- add more wheels if you want; just remember to update the width in the CSS -->
</div>
<p class="text-center">
<button id="spin" type="button" class="btn btn-default">Spin</button>
</p>
I managed to create a similar effect by using prepend() rather than append(), and adding a set height and hiding the overflow of the wheel.
CSS:
.wheel {
...
height: 34.4px;
overflow: hidden;
}
JS:
$('.wheel').prepend('<div style="display: none;" class="new-link" name="link[]"><input type="text" value="' + getRandomIndex() + '" /></div>');
//Using "first-of-type" rather than "last"
$('.wheel').find(".new-link:first-of-type").slideDown("fast");
See it working here.
Like so many animations it's a lot easier to fake this animation by reversing what appears to be happening, rather than making it work "correctly".
Use the code you have now to generate a result. Then create an animation for a "spinning wheel", you could shuffle divs, or you could make a 3d wheel in css. While the faces are spinning, do some calculations to decide where the wheel should stop to match your results. Then work backwards from there: You'll want to trigger your "stopping" animation so that the face is showing. Your stopping animation would be a predetermined amount of rotation and speed so that a face can be reliably shown. Depending on how fast your wheel spins, the user may lose track, if this is acceptable it may not matter when you trigger as no one could see the wheel jump.
A simulation on the other hand would use a physics model...
I am building a website, and I need to 'implement' a gallery on a group of photos. Since I'm using Spring MVC, my images are with 'img src..' tag and regular js and jquery addons don't work. Is there any plugin/library that can help me do this? If not, suggestions for making my way around it are also welcome. Here is the html, if it can somehow help.
<div id="img-slider">
<img class="slider-img" src="/LBProperties/img/bisc.jpg"/>
<img class="slider-img" src="/LBProperties/img/bisc1.jpg"/>
</div>
Thank you !
You can hide all of the images with CSS:
img {
width: 100px;
height: 100px;
display: none;
}
Get handlers to the images:
var slider = document.querySelector('#img-slider');
var images = slider.getElementsByTagName('img');
Set an index to 0:
var index = 0;
Then show the first image:
images[index].style.display = 'block';
Add a button to your HTML:
<div>
<button id="next">Next</button>
</div>
Get it with script and add a click handler:
var button = document.querySelector('#next');
button.addEventListener('click', function() {
for (var ix = 0; ix < images.length; ix++) {
images[ix].style.display = 'none';
}
index++;
if (index >= images.length) index = 0;
images[index].style.display = 'block';
});
The click handler loops through the images and hides them, increases the index, checks to make sure the index didn't go over the number of images (reset it to 0 if it does), then shows the next image.
Putting it all together:
https://jsfiddle.net/subterrane/osszqoLe/
I'm trying to create a simple slideshow effect. I have 10 images, and I've created a basic HTML page with 2 buttons to go to the right or left image. On clicking the button, the images change.
Now, I'm trying to add a basic fade functionality to the changing image. But the fade effect isn't getting displayed. When I put alerts, I notice that the fade is taking place, but without the alerts it is too fast to be visible. Also, it is happening on the previous image, instead of the next one.
<html>
<head>
<style>
.main {
text-align: center;
}
.centered {
display: inline-block;
}
#image {
border: solid 2px;
width: 500px;
height: 500px;
}
#number {
font-size: 30px;
}
</style>
<script>
function goLeft() {
var image = document.getElementById("image");
var pos = document.getElementById("number");
if(Number(pos.innerHTML)==1) {
image.src = "Images\\10.jpg"
pos.innerHTML = 10;
} else {
image.src = "Images\\" + (Number(pos.innerHTML)-1).toString() + ".jpg"
pos.innerHTML = (Number(pos.innerHTML)-1).toString();
}
for (var i=0; i<25; i++) {
setTimeout(changeOpacity(image, i), 1000);
}
}
function changeOpacity(image, i) {
alert(parseFloat(i*4/100).toString());
image.style.opacity = (parseFloat(i*4/100).toString()).toString();
}
function goRight() {
var image = document.getElementById("image");
var pos = document.getElementById("number");
if(Number(pos.innerHTML)==10) {
image.src = "Images\\1.jpg"
pos.innerHTML = 1;
} else {
image.src = "Images\\" + (Number(pos.innerHTML)+1).toString() + ".jpg"
pos.innerHTML = (Number(pos.innerHTML)+1).toString();
}
for (var i=0; i<25; i++) {
setTimeout(changeOpacity(image, i), 1000);
}
}
</script>
</head>
<body>
<div class="main">
<div class="centered">
<img id="image" src="Images\1.jpg">
</div>
</div>
<div class="main">
<div class="centered">
<span id="number">1</span>
</div>
</div>
<div class="main">
<div class="centered">
<button onclick="goLeft()" style="margin-right:50px;">Go Left</button>
<button onclick="goRight()" style="margin-left:50px;">Go Right</button>
</div>
</div>
</body>
The problem is this block of code that is in your goLeft method, and goRight method:
for (var i=0; i<25; i++) {
setTimeout(changeOpacity(image, i), 1000);
}
You are creating 25 timers that, and each timer will execute approximately 1 second later.
Creating animations is best left to the CSS.
In your CSS add:
#image {
transition: opacity 0.5s ease;
}
And then in your JavaScript, simply: image.style.opacity = 1.0;
When the opacity changes, CSS will automatically transition the opacity length at the speed defined in the css, e.g 0.5s. Feel free to experiment.
I also added a jsfiddle here: http://jsfiddle.net/dya7L8wq/
You misunderstood setTimeout and the for loop.
Norman's answer provides a good solution with CSS, but he doesn't talk too much about why your code is not working. So I'd like to explain.
for (var i=0; i<25; i++) {
setTimeout(changeOpacity(image, i), 1000);
}
You assumption is:
invoke changeOpacity(image, 0) after 1 second
invoke changeOpacity(image, 1) 1 second after step 1
invoke changeOpacity(image, 2) 1 second after step 2
invoke changeOpacity(image, 3) 1 second after step 3
....
And the last step is invoking changeOpacity(image, 24) 1 second after previous step.
What actually happens is:
The loop is finished almost immediately!
In each iteration, setTimeout queues an asynchronous function invocation, and it's done! That says, it will return right away, rather than wait until changeOpacity returns.
And then, after about 1 second, changeOpacity fires 25 times almost at the same time, because you queued it 25 times in the for loop.
Another problem here is: in changeOpacity invocations, passed-in parameter i are not 1, 2, 3...., they all have the same value that causes for loop to exit (1 second ago) - 25, because JS doesn't have a block scope prior to ES6 (in ES6 we have keyword let for it).
In a pure JS solution, to ensure the time sequence we'd usually queue next invocation at the end of every step:
function changeOpacity() {
// do something here
// before the function returns, set up a future invocation
setTimeout(changeOpacity, 1000)
}
Here's an example to print a list of numbers from 1 to 5:
var go = document.getElementById('go')
var op = document.getElementById('output')
var i = 0
function printNum() {
var p = document.createElement('p')
p.innerHTML = ++i
op.appendChild(p)
// next step
if(i < 5) {
setTimeout(printNum, 500)
}
}
go.onclick = printNum
<button id="go">GO</button>
<div id="output"></div>
Why use pure JavaScript?
Use jQuery.
It has a pretty neat fadeTo() function and a useful fadeIn() function.
Might wanna use that ;)
Ok so I've revised the markup/code to make it easier to understand. Using JavaScript I want to know how to create a text slider that changes a paragraph in html5 either "forwards" or "backwards" on click?
I only want one div to show at a time and the first div (div_1) needs to be visible at the beginning as a default setting. I also want to be able to add more text divs to it in the future. I'm new to JavaScript so I want to keep it as simple as possible.
I've had a go creating it in JavaScript which hasn't worked, I'm not sure if I'm going about this the right way.
<!DOCTYPE html>
<html lang="en">
<head>
<style type="text/css">
.showHide {
display: none;
}
</style>
<script type="text/javascript">
var sdivs = [document.getElementById("div_1"),
document.getElementById("div_2"),
document.getElementById("div_3"),
document.getElementById("div_4")];
function openDiv(x) {
//I need to keep div_1 open as a starting point
sdivs[0].style.display ="block";
var j;
for (var j = 0; j < sdivs.length; j++) {
if (j === x) {
continue;
}
else {
sdivs[j].style.display = "none";
}
}
}
</script>
<title>text</title>
</head>
<body>
forward
backwards
<div id="text_holder">
<div id="div_1" class="showHide">One</div>
<div id="div_2" class="showHide">Two</div>
<div id="div_3" class="showHide">Three</div>
<div id="div_4" class="showHide">Four</div>
</div>
</body>
</html>
When dealing with multiple elements like this, I've found CSS alone to be insufficient (though its brilliant for modifying simple hover states or whatever). This one method here is pretty simple and specific to this one set of markup (so modify as you see fit). More importantly - its to illustrate how to set up a simple javascript "class" to handle your logic.
http://jsfiddle.net/1z13qb58/
// use a module format to keep the DOM tidy
(function($){
// define vars
var _container;
var _blurbs;
var _blurbWidth;
var _index;
var _clicks;
// initialize app
function init(){
console.log('init');
// initialize vars
_container = $('#text_holder .inner');
_blurbs = $('.blurb');
_blurbWidth = $(_blurbs[0]).innerWidth();
_clicks = $('.clicks');
_index = 0;
// assign handlers and start
styles();
addEventHandlers();
}
// initialize styles
function styles(){
_container.width(_blurbs.length * _blurbWidth);
}
// catch user interaction
function addEventHandlers(){
_clicks.on({
'click': function(el, args){
captureClicks( $(this).attr('id') );
}
});
}
// iterate _index based on click term
function captureClicks(term){
switch(term){
case 'forwards':
_index++;
if(_index > _blurbs.length - 1){
_index = 0;
}
break;
case 'backwards':
_index--;
if(_index < 0){
_index = _blurbs.length - 1;
}
break;
}
updateView();
}
// update the _container elements left value
function updateView(){
//_container.animate({
//'left' : (_index * _blurbWidth) * -1
//}, 500);
_container.css('left', ((_index * _blurbWidth) * -1) + 'px');
}
init();
})(jQuery);
I'm using jQuery to handle event binding and animation, but, again - there are lots of options (including a combination of vanilla javascript and CSS3 transitions).
I'll note also that this is all html4 and css2 (save your doctype).
Hopefully that helps -
I am trying to get a sound file to play faster in order to keep up with the text reveal in the following code. The sound works (in Firefox, anyway), but it only seems to play one instance of the file at a time.
I'd like to have each letter pop onto the screen accompanied by the popping sound. Right now the popping sound is sort of random, and not timed to play with each letter.
I'm wondering if I need to have multiple instances of the sound object, and how to do that.
I already shortened the sound file as much as I could, and the length of the file is shorter than the setTimeout interval I'm using. It just won't overlap multiple copies of the same sound file, for some very good reason that I don't know, I'm sure.
Here is the whole code:
(I tried to JSFiddle it, but couldn't get that to work (I'll save that question for a later date))
<html>
<head>
<style>
#display {
color: white;
font-size: 150%;
padding: 2em 5em;
min-height: 600px;
max-width: 600px;
margin-left: auto;
margin-right: auto;
}
body {
background-color: black;
padding: 0;
margin:0;
}
</style>
<script>
var text = "Test String... 1, 2, 3; Everything seems to be working, but the sound is lagging.";
var charDelay = 40; // Sets the delay time for the character loop
function loadText() {
var i = 0; // Character counter
var myPud = new Audio("http://southernsolutions.us/audio/pud03.ogg");
var displayBox = document.getElementById("display");
displayBox.innerHTML = "<p>";
textLoop();
function textLoop() {
if (i == text.length){ // This condition terminates the loop
displayBox.innerHTML += "</p>";
return;
} else if (i < text.length) { // This condition appends the next character
displayBox.innerHTML += text[i];
i++;
myPud.play();
setTimeout(function(){return textLoop()}, charDelay);
}
}
}
window.onload = function(){loadText()};
</script>
</head>
<body>
<div id="display"></div>
</body>
</html>
I'd suggest that you make the sound loop a little longer, say 1 second. Then, control the sound playing through event listeners so that once the text has finished, you stop the sound playing.
Trying to do it as you're doing it now, you could speed up the sound with how its playing in the audio file. This should give better results. That, or slow down the time out.
Below is some code that I've tested which would let you do it through event listeners. The results are similar to what you had, but if you took your audio file, increased it to 1 second and changed it up to have 24 clicks in there, you'd get the exact effect you were looking for.
Edit: I've also updated the below to take into account the comments.
<script>
var text = "Test String... 1, 2, 3; Everything seems to be working, but the sound is lagging.";
var charDelay = 40; // Sets the delay time for the character loop
function loadText() {
var i = 0; // Character counter
var myPud = new Audio("http://southernsolutions.us/audio/pud03.ogg");
var displayBox = document.getElementById("display");
// Toggle for whether to loop
var stillPlay = true;
displayBox.innerHTML = "<p>";
// Listen for when it ends
myPud.addEventListener("ended", onAudioComplete);
// Begin playing
myPud.play();
// Start the loop
textLoop();
function textLoop() {
if (i == text.length){ // This condition terminates the loop
displayBox.innerHTML += "</p>";
// If we're at the end, we want to stop playing
stillPlay = false;
// Rather than duplicate code, jump straight into the complete function
onAudioComplete(null);
return;
} else if (i < text.length) { // This condition appends the next character
displayBox.innerHTML += text[i];
i++;
// Direct reference to the function to avoid more anony. functions
setTimeout(textLoop, charDelay);
}
}
// On audio complete
function onAudioComplete(e){
// Can we still play? If so, play
if(stillPlay){
myPud.play();
} else {
// Otherwise, remove the event listener, stop and null out.
myPud.removeEventListener("ended", onAudioComplete);
myPud.stop();
myPud = null;
}
}
}
window.onload = loadText;
</script>