why is the opacity not returning to 0 in function resetImg() ?
it returns the position correctly when function is called.
I'm trying to do this without jquery at the moment...
i'm trying to get the animation part down before implementing into my full game.
Animation = https://codepen.io/hamisakim/pen/oNzyKeR
Full game = https://codepen.io/hamisakim/pen/ExgLrKV?editors=1011
HTML
<h1 id='Main Header'> Rock Paper Scissors </h1>
<h2> Choose below to test your luck </h2>
<div class='buttons'>
<button id='rock'> ROCK </button>
<button id='paper'>PAPER </button>
<button id='scissors'> SCISSORS</button>
</div>
<h1 id='result'> </h1>
<div id='choiceImages'>
<image id='playerImg' src='https://www.rock-paper-scissors-game.com/i/rock.png'>
<image id='computerImg' src='https://www.rock-paper-scissors-game.com/i/scissors.png'>
</div>
CSS
body{text-align: center;}
.buttons {
position:relative;
}
#computerImg{
max-width: 30%;
display: inline-block;
padding: 0px 0px 0px 35px;
position:relative;
z-index: -1;
}
#playerImg {
max-width: 30%;
display: inline-block;
padding: 0px 35px 0px 0px;
position:relative;
z-index: 1;
}
JAVASCRIPT
function playerWinAnimate() {
document.getElementById('playerImg').animate([
//keyframes
{transform : 'translateX(0px)'},
{transform : 'translateX(250px)'}
],
{
duration: 1000,
iterations: 1,
fill: 'forwards',
},)
document.getElementById('computerImg').animate([
{opacity:1},
{opacity:0}, ],
{duration:1000,
delay: 1000,
iterations: 1,
fill: 'forwards'
}, )
}
playerWinAnimate();
function resetImg(){
document.getElementById('computerImg').style.opacity = 'initial';
document.getElementById('playerImg').style.left = '-200px';
}
document.getElementById("rock").addEventListener("click", resetImg);
document.getElementById("paper").addEventListener("click", resetImg);
document.getElementById("scissors").addEventListener("click", resetImg);
Related
I am trying to build a page:
Like This
When a div gets into the view on the screen, then a class gets added to the right side of the "table of contents", then when it's scrolled off the screen and another div shows up the class gets moved to the next "title" of the content.
So far I have a list of divs stacked on the top of each other and some basic JS but it does not work. I am not even sure if this is a good approach to get this done?
$(window).scroll(function(){
if ( $('#field-wrap1').offset().top <= 100 ) {
$('#slide-li1').addClass("active");
}else{
$('#slide-li1').removeClass("active");
}
});
JSFiddle
<!---
With this code it doesn't require editing the JavaScript
at all, only the HTML/CSS, it will apply the class .qqq_menu_active
to the active menu item and .qqq_section_active to the active section.
--->
<style>
* {
font-family: Arial;
margin: 0;
padding: 0;
}
body {
font-size: 10pt;
}
.qqq_container {
padding: 50px;
}
.qqq_menu {
position: fixed;
width: 200px;
left: 750px;
top: 50px;
}
.qqq_menu_item {
color: #333;
}
.qqq_menu_active {
font-size: 14pt;
font-weight: bold;
color: #000;
}
.qqq_section {
width: 600px;
padding: 25px;
color: #676767;
background-color: #fff;
}
.qqq_section_active {
color: #281c96;
background-color: #bdb6ff;
}
h1 {
padding-bottom: 20px;
}
</style>
<div class="qqq_menu">
<div class='qqq_menu_item'>section_1</div>
<div class='qqq_menu_item'>section_2</div>
<div class='qqq_menu_item'>section_3</div>
<div class='qqq_menu_item'>section_4</div>
<div class='qqq_menu_item'>section_5</div>
</div>
<div class='qqq_container'>
<div class='qqq_section'>
<h1>section_1</h1>
<p class='text_fill'></p>
</div>
<div class='qqq_section'>
<h1>section_2</h1>
<p class='text_fill'></p>
</div>
<div class='qqq_section'>
<h1>section_3</h1>
<p class='text_fill'></p>
</div>
<div class='qqq_section'>
<h1>section_4</h1>
<p class='text_fill'></p>
</div>
<div class='qqq_section'>
<h1>section_5</h1>
<p class='text_fill'></p>
</div>
</div>
<script>
// note: have tried editing .repeat to 3000 to make it a lot of text and 150 to make it a little text and still works right. also added a bunch of space with <br /> above and below the .qqq_container element and still works right.
asdf_text = "asdf ".repeat(750);
document.querySelectorAll(".text_fill").forEach(function (element) {
element.innerHTML = asdf_text;
});
container = document.querySelectorAll(".qqq_container")[0];
sections = document.querySelectorAll(".qqq_section");
menu = document.querySelectorAll(".qqq_menu_item");
percentage = 0;
function qqq_menu_highlight() {
active = 0;
ttt = window.innerHeight / 100;
lll = ttt * percentage;
zzz = window.scrollY + lll;
sections.forEach(function (v, k, l) {
if (zzz > v.offsetTop) {
active = k;
}
});
menu.forEach(function (v, k, l) {
if (active === k) {
v.classList.add('qqq_menu_active');
} else {
v.classList.remove('qqq_menu_active');
}
});
sections.forEach(function (v, k, l) {
if (active === k) {
v.classList.add('qqq_section_active');
} else {
v.classList.remove('qqq_section_active');
}
});
}
function element_scroll_percentage(element) {
//inc = (document.body.scrollHeight - window.innerHeight) / 100;
//console.log(active);
rect = element.getBoundingClientRect();
if (Math.sign(rect.top) == -1) {
value = Math.abs(rect.top);
inc = (rect.height - window.innerHeight) / 100;
percentage = value / inc;
if (percentage > 100) {
percentage = 100;
}
} else {
percentage = 0;
}
return percentage;
}
document.onscroll = function() {
percentage = element_scroll_percentage(container);
qqq_menu_highlight();
//console.log(percentage);
}
document.onscroll();
</script>
In the solution below, I divided the value of this.scrollY by 200, since the height of the containers is 200px. I added the result of this action to the end of the slide-li statement to use as the id of the targeted item.
function removeClass() {
for(let i = 0 ; i < 6 ; i++)
$(`#slide-li${i + 1}`).removeClass("active");
}
$(window).scroll(function(){
console.clear();
console.log(`Scroll: ${this.scrollY}`);
removeClass();
let visibleElement = Math.floor(this.scrollY / 200);
$(`#slide-li${visibleElement + 1}`).addClass("active");
});
#container {
width: 800px;
margin: auto;
text-align: left;
display: inline-flex;
margin: 0;
margin: 100px 0;
}
#field {
width: 500px;
float: left;
font-weight: 500;
color: #001737;
}
.field-wrap {
padding: 0;
border-bottom: 1px solid #8392A5;
height: 200px;
background-color: #FF000030;
}
#slidecart {
position: fixed;
top: 10px;
right: 0px;
width: 300px;
display: inline-block;
padding: 20px;
border-left: 1px solid #8392A5;
}
#slide-ul {
list-style-type: none;
margin: 0;
padding: 5px 0 0 5px;
}
.slide-li {
margin: 0;
padding: 0 0 0 10px;
cursor: pointer;
}
.active {
padding: 0 0 0 5px;
border-left: 5px solid #0168FA;
color: #0168FA;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
<div id="field">
<div id="field-wrap1" class="field-wrap">
1.) - Hello World!
</div>
<div id="field-wrap2" class="field-wrap">
2.) - Hello World!
</div>
<div id="field-wrap3" class="field-wrap">
3.) - Hello World!
</div>
<div id="field-wrap4" class="field-wrap">
4.) - Hello World!
</div>
<div id="field-wrap5" class="field-wrap">
5.) - Hello World!
</div>
<div id="field-wrap6" class="field-wrap">
6.) - Hello World!
</div>
</div>
<div id="slidecart">
TABLE OF CONTENTS
<ul id="slide-ul">LIST
<li id="slide-li1" class="slide-li">1.) - Hello World!</li>
<li id="slide-li2" class="slide-li">2.) - Hello World!</li>
<li id="slide-li3" class="slide-li">3.) - Hello World!</li>
<li id="slide-li4" class="slide-li">4.) - Hello World!</li>
<li id="slide-li5" class="slide-li">5.) - Hello World!</li>
<li id="slide-li6" class="slide-li">6.) - Hello World!</li>
</ul>
</div>
</div>
I'm trying to make a game of little rabbit's farm. My level of programming is a beginner.
Why is addRabbit() code starts to work after the page is loaded? I wrote it to work after click to "Buy Rabbit" button
Why rabbits are not shown at the page near the "Sell Rabbit" and "Buy Rabbit" buttons?
I know that I have a lot of issues here as far as I'm a beginner. Could I ask you to mention any of them?
// VARIABLES
// variables for modal of chosing rabbits
const chooseModal = document.querySelector(".choose-modal");
const selectRabbitBtn = document.querySelector(".choose-rabbit-btn");
const rabbitSelects = document.querySelectorAll("input[type=radio]");
let chosenRabbitUrl = "img/rabbit1.png";
// start screen
const startScreenDiv = document.querySelector(".story-modal");
const rabbit = document.querySelector("img.rabbit");
const buyRabbitBtn = document.querySelector(".buy-btn");
// EVENT LISTENERS
selectRabbitBtn.addEventListener("click", chooseTheRabbit);
// FUNCTIONS
function chooseTheRabbit(e){
e.preventDefault();
for (let rabbit of rabbitSelects) {
if (rabbit.checked) {
chosenRabbitUrl = `img/${rabbit.id}.png`;
break;
}
}
chooseModal.style.display = "none";
startScreen();
}
function startScreen() {
startScreenDiv.style.display = "block";
rabbit.src = chosenRabbitUrl;
}
class RabbitGame {
constructor() {
this.rabbitsCount = parseInt(document.querySelector(".rabbits-count").innerText, 10);
this.rabbitsCountSpan = document.querySelector(".rabbits-count");
this.rabbitsShowDiv = document.querySelector(".rabbits-count-show");
this.coinsCount = parseInt(document.querySelector(".coins-count").innerText, 10);
this.coinsCountSpan = document.querySelector(".coins-count");
this.sellRabbitBtn = document.querySelector(".sell-btn");
this.myRabbits = [{age: 0, src: chosenRabbitUrl, width: 50}];
};
// function, that shows rabbits on the page, that the owner have
// adult rabbits should be bigger, little rabbits smaller
showRabbits() {
// rabbit.src = chosenRabbitUrl
this.myRabbits.forEach((rabbit) => {
this.rabbitsShowDiv.innerHTML += `<img src="${rabbit.src}" width="${rabbit.width}">`});
};
// function that adds a rabbit, if the owner doesn't have any coin, rabbits eat him
addRabbit() {
console.log("Hello");
if (this.coinsCount > 1) {
// remove 1 coin
this.coinsCount -= 1
console.log(this.coinsCount);
// show 1 coin less
this.coinsCountSpan.innerText = this.coinsCount
// add 1 for rabbits age
// if the rabbit is older than 4, make him bigger on screen
this.myRabbits.forEach((rabbit) => {
rabbit.age +=1;
if (rabbit.age > 3) {
rabbit.width = 70
}
})
// add 1 more rabbit to array
this.myRabbits.push({age: 0, src: chosenRabbitUrl, width: 50});
// show 1 more rabbit
this.rabbitsShowDiv.innerHTML += `<img src="${rabbit.src}" width="${rabbit.width}">`
}
};
// функция, которая продает кролика, если он взрослый
// если нет взрослых кроликов, выводит предупреждение, что нет взрослых кроликов
}
const rabbitGame = new RabbitGame();
rabbitGame.showRabbits;
buyRabbitBtn.addEventListener("click", rabbitGame.addRabbit());
/* GENERAL */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: sans-serif;
}
h3 {
background-color: rgb(108, 165, 55);
width: 400px;
height: 30px;
padding: 5px;
color: white;
text-align: center;
}
button {
padding: 5px 20px;
background-color: rgb(194, 89, 89);
color: white;
text-transform: uppercase;
border: none;
font-weight: bold;
}
button:hover {
background-color: rgb(172, 79, 84);
}
/* END OF GENERAL */
/* CHOOSE RABBIT MODAL & RULES MODAL */
.choose-modal,
.rules-modal {
display: flex;
justify-content: center;
margin-top: 20px;
}
.choose-modal > div {
display: flex;
flex-direction: column;
}
input[type="radio"] {
opacity: 0;
}
label > img:hover {
border-bottom: 1px solid rgb(199, 199, 199);
}
ul {
list-style: none;
margin: 10px;
}
li {
margin-bottom: 5px;
}
.button-div {
display: flex;
justify-content: center;
}
/* END OF CHOOSE RABBIT MODAL & RULES MODAL */
/* START SCREEN */
/* .story-modal {
display: none;
} */
.story-modal {
background-image: url("img/neighbour.jpg");
background-size: cover;
height: 100vh;
position: relative;
}
img.rabbit {
position: absolute;
height: 40%;
top: 60%;
left: 50%;
overflow: hidden;
}
.story-modal > h3 {
position: absolute;
margin-left: auto;
margin-right: auto;
left: 0;
right: 0;
top: 5%;
}
.img-overlay {
width: 100%;
height: 100%;
background: rgba(61, 61, 61, 0.3);
}
.story-modal > button {
position: absolute;
margin-left: auto;
margin-right: auto;
left: 0;
right: 0;
top: 13%;
}
/* END OF START SCREEN */
/* MAIN GAME */
.main-game {
display: flex;
}
/* END OF MAIN GAME */
<div class="choose-modal">
<div>
<div class="choose-modal-header">
<h3>Please, choose the rabbit</h3>
</div>
<div>
<label for="rabbit1"><input type="radio" id="rabbit1" name="rabbits" value="rabbit1"><img src="img/rabbit1.png" width="100" alt="rabbit1"></label>
<label for="rabbit2"><input type="radio" id="rabbit2" name="rabbits" value="rabbit2"><img src="img/rabbit2.png" width="100" alt="rabbit2"></label>
<label for="rabbit3"><input type="radio" id="rabbit3" name="rabbits" value="rabbit3"><img src="img/rabbit3.png" width="80" alt="rabbit3"></label>
</div>
<div class="button-div">
<button type="submit" value="Choose" class="choose-rabbit-btn">Choose</button>
</div>
</div>
</div>
<div class="story-modal">
<div class="img-overlay"></div>
<h3>Your pretty neighbour gave you a rabbit</h3>
<img alt="rabbit" src="#" class="rabbit">
<button>Rules</button>
</div>
<div class="rules-modal">
<div>
<h3>Rules of game</h3>
<div>
<ul>
<li>Buy grass to feed the rabbits</li>
<li>Sell adult rabbits</li>
<li>Buy new little rabbits</li>
</ul>
</div>
<div class="button-div">
<button>Play</button>
</div>
</div>
</div>
<div class="main-game">
<div class=" navbar">
<p><img src="img/coin.png" height="20"> Coins <span class="coins-count">10</span></p>
<p class="name-of-gamer">Anonymous</p>
<p><img src="img/rabbit.png" height="20"> Rabbits <span class="rabbits-count">3</span></p>
</div>
<div class="rabbits-count-show"></div>
<div>
<button class="sell-btn">Sell Rabbit</button>
<button class="buy-btn">Buy Rabbit</button>
</div>
</div>
Changing the line
buyRabbitBtn.addEventListener("click", rabbitGame.addRabbit());
to
buyRabbitBtn.addEventListener("click", rabbitGame.addRabbit);
(simply removing those parenthesis) should work. When you add the parenthesis, a function gets called, and that's not what you want. When the button is clicked the eventlistener call the your function itself. as of your second problem you have to add parenthesis to the function to get called thus executing the code inside it.
NOTE: Do not post unnecessary files to a question. Try find the location that error could possibly occur. BTW, CSS has no contributing factor to a error in js code. sometimes html does. I know as a beginner it's hard to find the areas causing the error but it gets easier over time.
Here is my current setup.
2 radio button to select either year or month
2 sliders, one for year and another one for month
Textbox which will display value of the slider
using onclick radio function, I am displaying only one slider depends upon the year\month selection.
when I change option between year and month, I would like to update the slider and textbox value accordingly. For example, if the year slider is on year 15 and when I change radio button to month, the slider should move to 180 (15*12) and textbox should update as 180.
As of now, I am able to display\hide the slider depends on the radio selection and update the textbox with slider value. But this value is not getting converted between year and month.
How can I achieve this ?
Fiddle : https://jsfiddle.net/anoopcr/vvemxcL3/
Below is my current code:
HTML:
<div class="inputQ">
<div class="InputQuest">Loan Tenure</div>
<div><input id="tentext" class="textbox"></div>
<div class="switch-field">
<div class="switch-title"></div>
<input type="radio" id="switch_left" name="switch_2" value="yes" onclick="javascript:yesnoCheck();" checked/>
<label for="switch_left">Yr</label>
<input type="radio" id="switch_right" name="switch_2" value="no" onclick="javascript:yesnoCheck();" />
<label for="switch_right">Mo</label>
</div>
</div>
<div class="MarkWrap1" id="MarkWrap1">
<div id="tenslidery" class="tenslidery"></div>
<div class="T">0</div>
<div class="T">5</div>
<div class="T">10</div>
<div class="T">15</div>
<div class="T">20</div>
<div class="T">25</div>
<div class="T">30</div>
</div>
<div class="MarkWrap2" id="MarkWrap2">
<div id="tensliderm" class="tensliderm"></div>
<div class="Tm">0</div>
<div class="Tm">60</div>
<div class="Tm">120</div>
<div class="Tm">180</div>
<div class="Tm">240</div>
<div class="Tm">300</div>
<div class="Tm">360</div>
</div>
Jquery:
$( "#tentext" ).val( "20");
$("#tenslidery").slider({
orientation: "horizontal",
range: false,
min: 0,
max: 30 ,
value: 20,
step: .1,
animate: true,
range:'min',
slide: function( event, ui ) {
$( "#tentext" ).val( ui.value );
}
});
$("#tentext").on("keyup",function(e){
$("#tenslidery").slider("value",this.value);
});
$("#tensliderm").slider({
orientation: "horizontal",
range: false,
min: 0,
max: 360,
value: 240,
step: 1,
animate: true,
range:'min',
slide: function( event, ui ) {
$( "#tentext" ).val( ui.value );
}
});
$("#tentext").on("keyup",function(e){
$("#tensliderm").slider("value",this.value);
});
function yesnoCheck() {
if (document.getElementById('switch_left').checked) {
document.getElementById('MarkWrap1').style.display = 'flex';
document.getElementById('MarkWrap2').style.display = 'none';
}
else if (document.getElementById('switch_right').checked) {
document.getElementById('MarkWrap2').style.display = 'flex';
document.getElementById('MarkWrap1').style.display = 'none';
}
}
CSS:
.tenslidery {
height:8px;
flex-basis:100%;
margin:0 calc((100% / 7) / 2);
}
.T {
font-size: 11px;
font-family:verdana;
margin-top:15px;
flex:1;
text-align:center;
position:relative;
}
.T:before {
content:"";
position:absolute;
height:15px;
bottom:100%;
width:1px;
left:calc(50% - 1px);
background:#c5c5c5;
}
.MarkWrap1 {
width:83%; /*Adjust this to adjust the width*/
margin: auto;
display:flex;
flex-wrap:wrap;
}
.Tm {
font-size: 11px;
font-family:verdana;
margin-top:15px;
flex:1;
text-align:center;
position:relative;
}
.Tm:before {
content:"";
position:absolute;
height:15px;
bottom:100%;
width:1px;
left:calc(50% - 1px);
background:#c5c5c5;
}
.MarkWrap2 {
width:83%; /*Adjust this to adjust the width*/
margin: auto;
display:none;
flex-wrap:wrap;
}
.tensliderm {
height:8px;
flex-basis:100%;
margin:0 calc((100% / 7) / 2);
}
.switch-field {
font-family: "Lucida Grande", Tahoma, Verdana, sans-serif;
overflow: hidden;
width:auto;
}
.switch-field input {
position: absolute !important;
clip: rect(0, 0, 0, 0);
height: 1px;
width: 1px;
border: 0;
overflow: hidden;
}
.switch-field label {
float: left;
}
label[for=switch_right]
{
border:1px solid #ccc;
border-radius:4px;
border-top-left-radius:0px;
border-bottom-left-radius:0px;
}
label[for=switch_left]
{
border-top:1px solid #ccc;
border-bottom:1px solid #ccc;
}
.switch-field label {
display: inline-block;
width: 35px;
background-color: #eee;
color: black;
font-size: 18px;
font-weight: normal;
text-align: center;
text-shadow: none;
height:25.4px;
line-height:1.4;
padding:2px;
cursor: pointer;
}
.switch-field label switch-right ( background:red;)
.switch-field label:hover {
cursor: pointer;
}
.switch-field input:checked + label {
background-color: deeppink;
-webkit-box-shadow: none;
box-shadow: none;
}
I simply explicitly calculate the the values and submit to both slider and input box, should solve your problem
function yesnoCheck() {
var markWrap1 = $('#MarkWrap1');
var markWrap2 = $('#MarkWrap2');
var text = $('#tentext');
var value;
if ($('#switch_left').is(':checked')) {
markWrap1.css('display', 'flex');
markWrap2.css('display', 'none');
value = +$('#tensliderm').slider("option", "value") / 12;
text.val(String(value));
$('#tenslidery').slider('value', value);
} else if ($('#switch_right').is(':checked')) {
markWrap2.css('display', 'flex');
markWrap1.css('display', 'none');
value = +$('#tenslidery').slider("option", "value") * 12;
text.val(String(value));
$('#tensliderm').slider('value', value);
}
}
see https://jsfiddle.net/kevinkassimo/ayhenhL5/8/
Just as a tidy up and to add readability...
This will keep both sliders and the input in sync at all times, so if you need to get any current value elsewhere, it will be correct.
var yearVal;
var monthVal;
var yearSelected;
configure();
function updateVal(val) {
yearVal = yearSelected ? val : val / 12;
monthVal = yearSelected ? val * 12 : val;
}
function switchSliders() {
document.getElementById('MarkWrap1').style.display = yearSelected ? 'flex' : 'none';
document.getElementById('MarkWrap2').style.display = yearSelected ? 'none' : 'flex';
}
function updateSliders() {
$("#tenslidery").slider("value", yearVal);
$("#tensliderm").slider("value", monthVal);
}
function updateTenure() {
$("#tentext").val(yearSelected ? yearVal : monthVal);
}
function yesnoCheck() {
yearSelected = document.getElementById('switch_left').checked;
updateTenure();
switchSliders();
updateSliders();
}
function configure() {
$("#tenslidery").slider({
orientation: "horizontal",
range: false,
min: 0,
max: 30,
value: 0,
step: .1,
animate: true,
range: 'min',
slide: function (event, ui) {
updateVal(ui.value);
$("#tentext").val(ui.value);
}
});
$("#tensliderm").slider({
orientation: "horizontal",
range: false,
min: 0,
max: 360,
value: 0,
step: 1,
animate: true,
range: 'min',
slide: function (event, ui) {
updateVal(ui.value);
$("#tentext").val(ui.value);
}
});
$("#tentext").on("keyup", function (e) {
updateVal(Number(this.value));
updateSliders();
});
yearVal = 20;
monthVal = yearVal * 12;
yearSelected = true;
$("#tentext").val(yearVal);
updateSliders();
}
i am new learner of jquery and javaScript.
i want to create a slider with a big image section and a section of thumbs.
slider should slide automatically i have coded so far is working on click or hover but i dont know how to set it on auto please help me how to modify my code. code and slider screen shoot is given below.
slider image
$("document").ready(function()
{
$("#thumbs a").mouseenter(function()
{
var smallimgpath = $(this).attr("href");
$("#bigimage img").fadeOut(function()
{
$("#bigimage img").attr("src",smallimgpath);
$("#bigimage img").fadeIn();
});
return false;
});
});
</script>
#imagereplacement{
border: 1px solid red;
width:98%;
height:400px;
margin:auto;
padding-top:8px;
padding-left:10px;
}
#imagereplacement p{
text-align:inline;
}
#bigimage{
/* border: 1px solid green; */
margin:auto;
text-align:center;
float: left;
}
#thumbs{
/*border: 1px solid yellow;*/
margin: 110px 10px;
text-align:center;
width:29%;
float: right;
}
#thumbs img{
height:100px;
width:100px;
}
//This is where all the JQuery code will go
</head>
<body>
<div id="imagereplacement">
<p id="bigimage">
<img src="images/slider1.jpg">
</p>
<p id="thumbs">
<img src="images/slider1.jpg">
<img src="images/slider2.jpg">
<img src="images/slider3.jpg">
</p>
try with this example, please let me know in case of any more question from you :
$("document").ready(function(){
var pages = $('#container li'),
current = 0;
var currentPage, nextPage;
var timeoutID;
var buttonClicked = 0;
var handler1 = function() {
buttonClicked = 1;
$('#container .button').unbind('click');
currentPage = pages.eq(current);
if ($(this).hasClass('prevButton')) {
if (current <= 0)
current = pages.length - 1;
else
current = current - 1;
nextPage = pages.eq(current);
nextPage.css("marginLeft", -604);
nextPage.show();
nextPage.animate({
marginLeft: 0
}, 800, function() {
currentPage.hide();
});
currentPage.animate({
marginLeft: 604
}, 800, function() {
$('#container .button').bind('click', handler1);
});
} else {
if (current >= pages.length - 1)
current = 0;
else
current = current + 1;
nextPage = pages.eq(current);
nextPage.css("marginLeft", 604);
nextPage.show();
nextPage.animate({
marginLeft: 0
}, 800, function() {});
currentPage.animate({
marginLeft: -604
}, 800, function() {
currentPage.hide();
$('#container .button').bind('click', handler1);
});
}
}
var handler2 = function() {
if (buttonClicked == 0) {
$('#container .button').unbind('click');
currentPage = pages.eq(current);
if (current >= pages.length - 1)
current = 0;
else
current = current + 1;
nextPage = pages.eq(current);
nextPage.css("marginLeft", 604);
nextPage.show();
nextPage.animate({
marginLeft: 0
}, 800, function() {});
currentPage.animate({
marginLeft: -604
}, 800, function() {
currentPage.hide();
$('#container .button').bind('click', handler1);
});
timeoutID = setTimeout(function() {
handler2();
}, 4000);
}
}
$('#container .button').click(function() {
clearTimeout(timeoutID);
handler1();
});
timeoutID = setTimeout(function() {
handler2();
}, 4000);
});
* {
margin: 0;
padding: 0;
}
#container {
width: 604px;
height: 453px;
position: relative;
}
#container .prevButton {
height: 72px;
width: 68px;
position: absolute;
background: url('http://vietlandsoft.com/images/buttons.png') no-repeat;
top: 50%;
margin-top: -36px;
cursor: pointer;
z-index: 2000;
background-position: left top;
left: 0
}
#container .prevButton:hover {
background-position: left bottom;
left: 0;
}
#container .nextButton {
height: 72px;
width: 68px;
position: absolute;
background: url('http://vietlandsoft.com/images/buttons.png') no-repeat;
top: 50%;
margin-top: -36px;
cursor: pointer;
z-index: 2000;
background-position: right top;
right: 0
}
#container .nextButton:hover {
background-position: right bottom;
right: 0;
}
#container ul {
width: 604px;
height: 453px;
list-style: none outside none;
position: relative;
overflow: hidden;
}
#container li:first-child {
display: list-item;
position: absolute;
}
#container li {
position: absolute;
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<center>
<h1>HTML Slideshow AutoPlay (Slide Left/Slide Right)</h1>
<br />
<br />
<div id="container">
<ul>
<li><img src="http://vietlandsoft.com/images/picture1.jpg" width="604" height="453" /></li>
<li><img src="http://vietlandsoft.com/images/picture2.jpg" width="604" height="453" /></li>
<li><img src="http://vietlandsoft.com/images/picture3.jpg" width="604" height="453" /></li>
</ul>
<span class="button prevButton"></span>
<span class="button nextButton"></span>
</div>
</center>
Here an example i've created that create an auto slider CodePen Demo and JSFiddle Demo
I've used an object literal pattern to create slide variable just to avoid creating many global function and variable. Inside document.ready i've initialised my slider just by calling slide.init({....}) this way it makes it easy to reuse and work like plugin.
$.extend(slide.config,option)
this code in simple words override you're default configuration defined in config key
as i mentioned in my above comment make a function slider() and place seTimeout(slide,1000) at bottom of your function before closing
Here in this code its done in animate key of slide object it is passed with two parameter cnt and all image array, If cnt is greater then image array length then cnt is set to 0 i.e if at first when cnt keeps on increment i fadeout all image so when i make it 0 the next time the fadeToggle acts as switch
if On then Off
if Off the On
and calling function slider after a delay makes it a recursive call its just one way for continuously looping there are many other ways i guess for looping continuous you can try
well i haven't check if all images Loaded or not which is most important in slider well that you could try on your own.
var slide = {
'config': {
'container': $('#slideX'),
'delay': 3000,
'fade': 'fast',
'easing': 'linear'
},
init: function(option) {
$.extend(slide.config, option);
var imag = slide.getImages();
slide.animate(0, imag);
},
animate: function(cnt, imag) {
if (cnt >= imag.length) {
cnt = 0;
}
imag.eq(cnt).fadeToggle(slide.config.fade, slide.config.easing);
setTimeout(function() {
slide.animate(++cnt, imag);
}, slide.config.delay);
},
getImages: function() {
return slide.config.container.find('img');
}
};
$(document).ready(function() {
slide.init({
'contianer': $('#slideX'),
'delay': 3000,
'fade': 'fast',
'easing': 'swing'
});
})
body {
margin: 0;
padding: 0;
}
.contianer {
width: 100%;
height: 100%;
position: relative;
}
.container > div,
.container > div >img {
width: 100%;
height: 100%;
position: absolute;
z-index: 1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container" id="slideX">
<div id="img1">
<img src="http://imgs.abduzeedo.com/files/articles/magical-animal-photography-gregory-colbert/5.jpg" />
</div>
<div id="img2">
<img src="http://cdn-5.webdesignmash.com/trial/wp-content/uploads/2010/10/great-dog-photography-016.jpg" />
</div>
<div id="img3">
<img src="http://onlybackground.com/wp-content/uploads/2014/01/marble-beautiful-photography-1920x1200.jpg" />
</div>
</div>
I want to add two arrows to the sides of the "boxes" divs (below) to cycle through the 3 divs.
Working JSFiddle: https://jsfiddle.net/HBHcC/11/
Can someone help me with this?
HTML:
<div class="container">
<div class="boxes">
<div class="one box">
</div>
<div class="two box">
</div>
<div class="three box">
</div>
</div>
</div>
CSS:
.container{
width:100px;
height:100px;
overflow:hidden;
position:relative;
}
.box {
display:inline-block;
float: left;
width: 100px;
height: 100px;
}
.one{
background-color:green;
}
.two{
background-color:red;
}
.three{
background-color:blue;
}
.boxes{
width:400px;
}
JS:
$(document).ready(function(){
$('.box').on("click", function() {
// Is this the last div, or is there a next one?
if ($(this).next().length) {
var animSpeed = 200; // Make this 0 for an instant change
$('.boxes').animate({marginLeft : "-=100"}, animSpeed);
}
});
});
After adding arrows to the div, here is a new fiddle that should get you started:
$('.rightarrow').on("click", function() {
// Is this the last div, or is there a next one?
var animSpeed = 200; // Make this 0 for an instant change
$('.boxes').animate({marginLeft : "-=100"}, animSpeed);
});
$('.leftarrow').on("click", function() {
// Is this the last div, or is there a next one?
var animSpeed = 200; // Make this 0 for an instant change
$('.boxes').animate({marginLeft : "+=100"}, animSpeed);
});
https://jsfiddle.net/tx2yg06w/1/
Updated w/arrows moved out of divs:
$(document).ready(function(){
var animSpeed = 200;
$('.rightarrow').on("click", function() {
if(parseInt($("#boxes").css("marginLeft")) == -200){ return;}
$('.boxes').animate({marginLeft : "-=100"}, animSpeed);
});
$('.leftarrow').on("click", function() {
if(parseInt($("#boxes").css("marginLeft")) == 0){ return;}
$('.boxes').animate({marginLeft : "+=100"}, animSpeed);
});
});
https://jsfiddle.net/b56r0d72/
Errata has given you a good solution. Just wire up his code to the arrows in the snippet below.
Run snippet to view:
<html>
<body>
<style type="text/css">
.leftarrow, .rightarrow {
font-size: 48px;
color: blue;
text-decoration: none;
}
.rightarrow {
color: red;
float: right;
}
.content {
width: 200px;
padding: 4px;
border: 1px gray solid;
}
.box {
height: 200px;
border: 1px green solid;
}
</style>
<div class="content">
<div>
◀
▶
</div>
<div class="box">slide</div>
</div>
</body>
</html>