New coder - 1st question here. I'm doing first free code camp project, but question is about a unrequired flourish I just want to add and learn about, it's not needed for project. I want the album covers I've linked in HTML to change every x seconds. But nothing happens yet. Images just stay static. Thanks
<h2> Discography </h2>
<div class="row">
<div id="album" class="col-lg-8">
<div class="albums" id="album 0"> <span><img src="https://upload.wikimedia.org/wikipedia/en/b/b6/Elliottsmithromancandle.jpeg" alt="1994" class="img-responsive"></span></div>
<div class="albums" id="album 1"> <span><img src="https://upload.wikimedia.org/wikipedia/en/e/e3/Elliott_Smith_%28album%29.jpg" alt="1995" class="img-responsive"></span></div>
<div class="albums" id="album 2"> <span><img src="https://upload.wikimedia.org/wikipedia/en/f/fd/Elliottsmitheitheror55.jpg" alt="1997" class="img-responsive"></span></div>
<div class="albums" id="album 3"> <span><img src="https://upload.wikimedia.org/wikipedia/en/thumb/3/…albumcover.jpg/330px-ElliottsmithXOalbumcover.jpg" alt="1998" class="img-responsive"></span></div>
<div class="albums" id="album 4"> <span><img src="https://upload.wikimedia.org/wikipedia/en/thumb/a/…_cover.jpg/330px-Elliott_smith_figure_8_cover.jpg" alt="2000" class="img-responsive"></span></div>
<div class="albums" id="album 5"> <span><img src="https://upload.wikimedia.org/wikipedia/en/8/8c/Elliott_smith_from_a_basement_on_the_hill_cover.jpg" alt="2004" class="img-responsive"></span></div>
<div class="albums" id="album 6"> <span><img src="https://upload.wikimedia.org/wikipedia/en/4/4e/New_Moon_%28Elliott_Smith_album%29_cover.jpg" alt="2007" class="img-responsive"></span></div>
</div>
and the javascript code
//Change album cover after 5 seconds - continous loop//
var Discography = document.getElementById("album");
var disc = ["album 0", "album 1", "album 2", "album 3", "album 4", "album 5", "album 6"];
var counter = 0;
function changeDisc() {
if (counter >= disc.length) {
counter = 0;
}
Discography.setAttribute =disc[counter];
counter++;
}
var myCounter = setInterval(changeDisc, 6000);
Discography.onClick = function() {
clearInterval(Disography);
Discography.innerHTML = "Counter stopped";
};
You aren't actually setting the attribute. You are actually removing the setAttribute method and replacing it with the url. I think you want this:
function changeDisc() {
if (counter >= disc.length) {
counter = 0;
}
Discography.setAttribute('src', disc[counter]);
counter++;
}
I managed to get your code working. I don't know if this is what you wanted, but I hope it helped you.
Assign Attributes
Discography.setAttribute = disc[counter];
Should be
Discography.setAttribute("src", discs[counter]);
Bind EventHandlers
Discography.onClick = function() {
Should be
Discography.addEventListener("click", function () {
Wrong Element
You tried to assign the src attribute to the <div id="album" class="col-lg-8"> which is a div and it does not have that attribute.
To fix this I added all possible album images to a Array and this will be assigned to a single <img /> to get this working.
Note that I modified some naming conventions, which I do prefer.
My Solution
var discs = [
"https://upload.wikimedia.org/wikipedia/en/b/b6/Elliottsmithromancandle.jpeg",
"https://upload.wikimedia.org/wikipedia/en/e/e3/Elliott_Smith_%28album%29.jpg",
"https://upload.wikimedia.org/wikipedia/en/f/fd/Elliottsmitheitheror55.jpg",
"https://upload.wikimedia.org/wikipedia/en/thumb/3/…albumcover.jpg/330px-ElliottsmithXOalbumcover.jpg",
"https://upload.wikimedia.org/wikipedia/en/thumb/a/…_cover.jpg/330px-Elliott_smith_figure_8_cover.jpg",
"https://upload.wikimedia.org/wikipedia/en/8/8c/Elliott_smith_from_a_basement_on_the_hill_cover.jpg" ,
"https://upload.wikimedia.org/wikipedia/en/4/4e/New_Moon_%28Elliott_Smith_album%29_cover.jpg",
];
var counter = 0;
var discography = document.getElementById("album");
function moveToNextDisc() {
if (counter >= discs.length) {
counter = 0;
}
discography.setAttribute("src", discs[counter]);
counter++;
}
var interval = setInterval(moveToNextDisc, 1000);
discography.addEventListener("click", function () {
clearInterval(interval);
discography.innerHTML = "Counter stopped";
});
<h2>Discography</h2>
<div class="row">
<div class="col-lg-8">
<div class="albums">
<span>
<img id="album" alt="1994" class="img-responsive">
</span>
</div>
</div>
</div>
for learning purpose, you are developing a component that:
changes cover every track change
stops when the user pauses
Javascript should be used for business logic and html/css as a view reflection of the state of the component.
So we need for an Object which has at least three methods:
public play starts the player
public pause pauses the player
private _loop iterates through the tracks
and for a Controller which controls the html view.
function Player(element, interval) {
this.element = element;
this.tracks = element.querySelectorAll('.albums');
this.currentTrack = null;
this.isPlaying = false;
this._timeout = null;
this.interval = Number(interval) || 2000;
}
Player.prototype.pause = function() {
window.clearTimeout(this._timeout);
this.isPlaying = false;
return this;
};
Player.prototype.play = function() {
this.isPlaying = true;
return this._loop();
};
Player.prototype._loop = function() {
var self = this;
self._timeout = window.setTimeout(function() {
var track;
if(self.currentTrack) {
track = self.currentTrack.nextElementSibling;
self.currentTrack.style.opacity = 0;
}
if(!track) {
track = self.tracks[0];
}
track.style.opacity = 1;
self.currentTrack = track;
return self._loop();
}, self.interval);
return this;
}
/** VIEW CTRL **/
function PlayerCtrl() {
var element = document.querySelector('#album');
var player = new Player(element, 3000);
var play = document.querySelector('#Play');
var pause = document.querySelector('#Pause');
play.onclick = function() {
return player.isPlaying || player.play();
};
pause.onclick = function() {
return player.isPlaying && player.pause();
};
player.play();
}
document.addEventListener('DOMContentLoaded', PlayerCtrl);
#album {
width: 300px;
height: 300px;
margin: 10px auto;
overflow: hidden;
background: lightcoral;
position: relative;
border: 3px dotted #333;
}
.albums {
transition: 450ms opacity linear;
opacity: 0;
position: absolute;
top: 0;
left: 0;
}
.albums img { max-width: 100%; }
<button id="Play">Play</button>
<button id="Pause">Pause</button>
<hr />
<h2> Discography </h2>
<div class="row">
<div id="album" class="col-lg-8">
<div class="albums" id="album 0"> <span><img src="https://upload.wikimedia.org/wikipedia/en/b/b6/Elliottsmithromancandle.jpeg" alt="1994" class="img-responsive"></span></div>
<div class="albums" id="album 1"> <span><img src="https://upload.wikimedia.org/wikipedia/en/e/e3/Elliott_Smith_%28album%29.jpg" alt="1995" class="img-responsive"></span></div>
<div class="albums" id="album 2"> <span><img src="https://upload.wikimedia.org/wikipedia/en/f/fd/Elliottsmitheitheror55.jpg" alt="1997" class="img-responsive"></span></div>
<div class="albums" id="album 3"> <span><img src="https://upload.wikimedia.org/wikipedia/en/thumb/3/…albumcover.jpg/330px-ElliottsmithXOalbumcover.jpg" alt="1998" class="img-responsive"></span></div>
<div class="albums" id="album 4"> <span><img src="https://upload.wikimedia.org/wikipedia/en/thumb/a/…_cover.jpg/330px-Elliott_smith_figure_8_cover.jpg" alt="2000" class="img-responsive"></span></div>
<div class="albums" id="album 5"> <span><img src="https://upload.wikimedia.org/wikipedia/en/8/8c/Elliott_smith_from_a_basement_on_the_hill_cover.jpg" alt="2004" class="img-responsive"></span></div>
<div class="albums" id="album 6"> <span><img src="https://upload.wikimedia.org/wikipedia/en/4/4e/New_Moon_%28Elliott_Smith_album%29_cover.jpg" alt="2007" class="img-responsive"></span></div>
</div>
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I'm having problems with counter in js, i've made 3 img tags with different id's, but having difficulties what to put in if statement for each counter? How can i see which photo has been clicked?
var count = 0;
function promptImg() {
var count1 = document.getElementById(test1)
var count2 = document.getElementById(test2)
var count3 = document.getElementById(test3)
}
<div id="flowers">
<div class="1">
<img id="test1" onclick="promptImg()" src="rosa-avon-crvena-ajevke-52-373-standard-1.png">
</div>
<div class="2">
<img id="test2" onclick="promptImg()" src="gerbera.jpg">
</div>
<div class="3">
<img id="test3" onclick="promptImg()" src="gipsofila.jpg">
</div>
</div>
If you want to know how to determine which image was clicked, make sure you pass this into the function assigned to the onclick attribute.
To keep track of click frequency, you can use object or a Set to store the associated count with the ID of the image.
const counter = { };
function promptImg(img) {
counter[img.id] = (counter[img.id] || 0) + 1;
console.log(JSON.stringify(counter));
}
body div {
display: flex;
flex-direction: row;
grid-column-gap: 1em;
align-content: center;
}
.as-console-wrapper { max-height: 2.667em !important; }
<div id="flowers">
<div class="1">
<img id="test1" onclick="promptImg(this)" src="http://placekitten.com/120/60" />
</div>
<div class="2">
<img id="test2" onclick="promptImg(this)" src="http://placekitten.com/150/75" />
</div>
<div class="3">
<img id="test3" onclick="promptImg(this)" src="http://placekitten.com/160/80" />
</div>
</div>
Or store the click as a data attribute using dataset.
const counter = { };
const displayClickFrequency = () =>
console.log(JSON.stringify([...document.querySelectorAll('img')]
.reduce((map, img) => ({
...map,
[img.id]: parseInt(img.dataset.clicked, 10) || 0
}), {})));
function promptImg(img) {
const previousValue = parseInt(img.dataset.clicked, 10) || 0;
img.dataset.clicked = previousValue + 1;
displayClickFrequency();
}
body div {
display: flex;
flex-direction: row;
grid-column-gap: 1em;
align-content: center;
}
.as-console-wrapper { max-height: 2.667em !important; }
<div id="flowers">
<div class="1">
<img id="test1" onclick="promptImg(this)" src="http://placekitten.com/120/60" />
</div>
<div class="2">
<img id="test2" onclick="promptImg(this)" src="http://placekitten.com/150/75" />
</div>
<div class="3">
<img id="test3" onclick="promptImg(this)" src="http://placekitten.com/160/80" />
</div>
</div>
You can do it by using an event listener and checking the id of its target element:
document.addEventListener("click", function(element) {
if (element.target.id === "test1") {
//do something
}
});
You can do that with one of there two options:
function promptImg() {
console.log(event.target);
}
[...document.querySelectorAll(".flowers-with-eventlistener img")].forEach(img => {
img.addEventListener("click", () => {
console.log(event.target)
})
})
img {
width: 100px;
height: 100px;
}
<div class="flowers-with-onclick">
<img onclick="promptImg()" src="rosa-avon-crvena-ajevke-52-373-standard-1.png" >
<img onclick="promptImg()" src="gerbera.jpg">
<img onclick="promptImg()" src="gipsofila.jpg">
</div>
<div class="flowers-with-eventlistener">
<img src="rosa-avon-crvena-ajevke-52-373-standard-1.png" >
<img src="gerbera.jpg">
<img src="gipsofila.jpg">
</div>
If you apply a class to all of the images, you can create an event listener to find out which one has been clicked.
You can test it yourself by using the snippet below and clicking the images. Hope this helped.
var images = document.querySelectorAll(".shared-class");
for (i = 0; i < images.length; i++) {
images[i].addEventListener("click", function() {
console.log(this)
})
}
<div>
<img src="#" id="test1" class="shared-class" />
<img src="#" id="test2" class="shared-class" />
<img src="#" id="test3" class="shared-class" />
</div>
You possibly wat to delegate your clicks to the container - in your case the flowers div
window.addEventListener("load", function() { // on page load
document.getElementById("flowers").addEventListener("click", function(e) { // on click in flowers
const tgt = e.target;
if (tgt.tagName === "IMG") {
console.log(tgt.id);
}
})
})
img { width: 200px; }
<div id="flowers">
<div class="1"> <img id="test1" src="https://pharmarosa.hr/galeria_ecomm/5413/rosa-avon-crvena-ajevke-52-373-standard-1.png" /> </div>
<div class="2"> <img id="test2" src="https://upload.wikimedia.org/wikipedia/commons/2/23/Azimut_Hotels_Red_Gerbera.JPG" /></div>
<div class="3"> <img id="test3" src="https://www.provenwinners.com/sites/provenwinners.com/files/imagecache/low-resolution/ifa_upload/gypsophila-festival-star-02.jpg" /> </div>
</div>
To notice when a user clicks an element (such as an image) on your webpage, you probably want to use the .addEventListener method on that element or one of its "ancestor" elements in the DOM.
Check out MDN's Event Listener page and see the verbose example in the snippet.
// Identifies some elements;
const
flowersContainer = document.getElementById("flowers"),
rosaImg = document.getElementById("rosa-img"),
gerberaImg = document.getElementById("gerbera-img"),
gipsofilaImg = document.getElementById("gipsofila-img"),
countersContainer = document.getElementById("counters");
// Calls `handleImageClicks` when the user clicks on flowersContainer
// (This "event delegation" lets us avoid adding a listener
// for each image, which matters more in larger programs)
flowersContainer.addEventListener("click", handleImageClicks);
// Defines `handleImageClicks`
function handleImageClicks(event){
// Listeners can access events, which have targets
const clickedThing = event.target;
// Calls `incrementCount` for the selected flower
if(clickedThing == rosaImg){ incrementCount("rosa"); }
else if(clickedThing == gerberaImg){ incrementCount("gerbera"); }
else if(clickedThing == gipsofilaImg){ incrementCount("gipsofila"); }
}
// Defines `incrementCount`
function incrementCount(flowerName){
const
// `.getElementsByClassName` returns a list of elements
// (even though there will be only one element in the list)
listOfMatchingElements = countersContainer.getElementsByClassName(flowerName),
myMatchingElement = listOfMatchingElements[0], // First element from list
currentString = myMatchingElement.innerHTML, // HTML values are strings
currentCount = parseInt(currentString), // Converts to number
newCount = currentCount + 1 || 1; // Adds 1 (Defaults to 1)
myMatchingElement.innerHTML = newCount; // Updates HTML
}
#flowers > div { font-size: 1.3em; padding: 10px 0; }
#flowers span{ border: 1px solid grey; }
#counters span{ font-weight: bold; }
<div id="flowers">
<div><span id="rosa-img">Picture of rosa</span></div>
<div><span id="gerbera-img">Picture of gerbera</span></div>
<div><span id="gipsofila-img">Picture of gipsofila</span></div>
</div>
<hr />
<div id=counters>
<div>User clicks on rosa: <span class="rosa"></span></div>
<div>User clicks on gerbera: <span class="gerbera"></span></div>
<div>User clicks on gipsofila: <span class="gipsofila"></span></div>
</div>
In your promptImg function if you use jquery, and you should, inside it add
var idClick=$(this).attr("id");
console.log("This link was clicked"+idClick);
and then you can easily IF it
I am working on a rock paper scissor game. I'm very new to javascript and only know the basics. The code is a little sloppy. What I want is to be able to continue playing the game after a choice is selected. For example, right now if I click rock, the CPU will randomize a result, but then if I click on paper, the result will stay on the screen and the new result will overlap the old one.
I was thinking of adding another condition to the if statements. Also, I was thinking of adding another function to the return of the if statement that might reset it.
html
<div class="main-container">
<div class="score">
<p>You:0</p>
<p>Computer:0</p>
</div>
<div class="user-choice">
<img id="rock" class="choice" src="icons/rock.png">
<img id="paper" class="choice" src="icons/paper.png">
<img id="scissors" class="choice" src="icons/scissors.png">
</div>
<div class="cpu-result">
<img class="cpu-rock" src="icons/rock.png">
<img class="cpu-paper" src="icons/paper.png">
<img class="cpu-scissors" src="icons/scissors.png">
</div>
</div>
js
const userChoice = document.querySelectorAll('.choice')
const cpuScissors = document.querySelector('.cpu-scissors')
const cpuPaper = document.querySelector('.cpu-paper')
const cpuRock = document.querySelector('.cpu-rock')
function cpuChoice() {
const rand = Math.random()
if (rand < .34) {
cpuPaper.style.display = 'inline-block'
} else if (rand >= .67) {
cpuRock.style.display = 'inline-block'
} else {
cpuScissors.style.display = 'inline-block'
}
}
userChoice.forEach(userChoice =>
userChoice.addEventListener('click', cpuChoice))
css
.cpu-scissors {
display: none;
}
.cpu-paper {
display: none;
}
.cpu-rock {
display: none;
}
.cpu-result img {
position: absolute;
height: 11rem;
}
Firstly, you need to remove position: absolute; for img which was causing the overlapping.
Secondly, each time you call cpuChoice(), you need to hide the previous element before showing the current element.
const userChoice = document.querySelectorAll('.choice')
const cpuScissors = document.querySelector('.cpu-scissors')
const cpuPaper = document.querySelector('.cpu-paper')
const cpuRock = document.querySelector('.cpu-rock')
let currentItem;
function cpuChoice() {
const rand = Math.random();
if (currentItem) {
currentItem.style.display = 'none';
}
if (rand < .34) {
cpuPaper.style.display = 'inline-block';
currentItem = cpuPaper;
} else if (rand >= .67) {
cpuRock.style.display = 'inline-block';
currentItem = cpuRock;
} else {
cpuScissors.style.display = 'inline-block';
currentItem = cpuScissors;
}
}
userChoice.forEach(userChoice =>
userChoice.addEventListener('click', cpuChoice));
.cpu-scissors {
display: none;
}
.cpu-paper {
display: none;
}
.cpu-rock {
display: none;
}
.cpu-result img {
height: 5rem;
}
<div class="main-container">
<div class="score">
<p>You:0</p>
<p>Computer:0</p>
</div>
<div class="user-choice">
<img id="rock" class="choice" src="icons/rock.png">
<img id="paper" class="choice" src="icons/paper.png">
<img id="scissors" class="choice" src="icons/scissors.png">
</div>
<div class="cpu-result">
<img class="cpu-rock" src="icons/rock.png">
<img class="cpu-paper" src="icons/paper.png">
<img class="cpu-scissors" src="icons/scissors.png">
</div>
</div>
You don't need all those IDs and Classes.
Use Indexes!
Using indexes you can also retrieve the winner
See this answer: https://stackoverflow.com/a/53983473/383904
const moves = ["Rock", "Paper", "Scissors"],
messages = ["You won!", "AI won", "It's a draw!"], // [PL, AI, draw]
score = [0, 0, 0], // [PL, AI, draw]
ELS = sel => document.querySelectorAll(sel),
EL_result = ELS("#result")[0],
EL_PLScore = ELS("#PLScore")[0],
EL_AIScore = ELS("#AIScore")[0],
ELS_ai = ELS(".ai");
function game() {
const PL = +this.dataset.user; // Get played index as integer
const AI = ~~(Math.random() * 3); // All you need: 0, 1, 2
const result = PL === AI ? 2 : (AI + 1) % 3 === PL ? 0 : 1; // 0=PLwins 1=AIwins 2=draw
score[result]++; // Increment PL or AI's score (Increments number of draws too ;) )
EL_result.innerHTML = `You: ${moves[PL]}, AI: ${moves[AI]}, ${messages[result]}`;
EL_PLScore.textContent = score[0];
EL_AIScore.textContent = score[1];
ELS_ai.forEach(el => el.classList.remove('inline-block')); // Hide all
ELS_ai[AI].classList.add('inline-block'); // Show one
}
// EVENTS:
document.querySelectorAll("[data-user]").forEach(el => el.addEventListener("click", game));
.ai {
display: none;
}
.ai.inline-block {
display: inline-block
}
<div class="main-container">
<div class="score">
<span>You: <span id="PLScore">0</span></span>
<span>Computer: <span id="AIScore">0</span></span>
</div>
<div class="user-choice">
<img data-user="0" src="//placehold.it/50x50/888?text=ROCK">
<img data-user="1" src="//placehold.it/50x50/eee?text=PAPER">
<img data-user="2" src="//placehold.it/50x50/0bf?text=SCISSORS">
</div>
<div class="cpu-result">
<img class="ai" src="//placehold.it/50x50/888?text=ROCK">
<img class="ai" src="//placehold.it/50x50/eee?text=PAPER">
<img class="ai" src="//placehold.it/50x50/0bf?text=SCISSORS">
</div>
<div id="result"></div>
</div>
I know it sounds a bit confusing.
Here is what I'm trying to do:
I have five pictures,
each of the picture has a set of classes,
each time when clicked on one of the pictures the id (same as class name) will be pushed in to an array.
At the end, I want to only show the pictures if they contain the same classes (id) found in that array.
<div id="cameras" class="row text-center ">
<div id="d5" class=" professional landscape wedding micro sportaction wildlife portrait astrophotographer cameras">
<div class="thumbnail">
<img src="images/d5.png" alt="D5">
</div>
</div>
<div id="d810a" class=" professional landscape astrophotographer portrait micro cameras">
<div class="thumbnail">
<img src="images/d810a.png" alt="D3300">
</div>
</div>
<div id="d810" class=" professional landscape wedding micro portrait cameras">
<div class="thumbnail">
<img src="images/d810.png" alt="D810">
</div>
</div>
<div id="d750" class=" enthusiast landscape wedding micro sportaction wildlife portrait astrophotographer cameras">
<div class="thumbnail">
<img src="images/D750.png" alt="D750">
</div>
</div>
</div>
$('#sportaction').on('click', function () {
if ($("#sportaction").attr('data-click-state') == 1) {
$(this).attr('data-click-state', 0);
$("#snaButton").css({ fill: "#00725C" });
} else {
$(this).attr('data-click-state', 1);
$("#snaButton").css({ fill: "#00A388" })
}
});
$("#finish").click(function() {
$("[data-click-state= '0' ]").each(function () {
type_array.push($(this).attr("id"));
//some.push(this.id);
});
});
For example: If I clicked on "enthusiast" and "landscape" Only d750 should show up.
The code below doesn't work.
$(".cameras").each(function () {
$(this).hide();
for (var i = 0; i < type_array.length; i++) {
if ($(this).hasClass(type_array[i])) {
$(this).show();
}
}
});
I do not know if I understand correctly your question, but try this?
var type_array = [];
$(".cameras").click(function() {
var classArray = $(this).attr('class').split(/\s+/);
$.each(classArray, function() {
if (this.length > 0 && this != "cameras" && type_array.indexOf(this) == -1) {
type_array[type_array.length] = this + "";
}
})
})
and somewhere else:
$(".cameras").each(function () {
$(this).hide();
var clicked = this;
var hasAllClasses = true;
$.each(type_array,function(){
if($(clicked).hasClass(this)){
return true;
}
hasAllClasses=false;
return false;
});
if(hasAllClasses===true){
$(clicked).show();
}
});
type_array=[];
I created a fade slider with images, text and links. I'd like to add some navigation bullets below it to control the images.
like this :
http://www.parallaxslider.com/preview_images/skins/bullets_skin.jpg
Here is the slider code:
html
<div class="slides">
<div class="slidiv">
<a href="..." ><img src="..." >
<span> text1 </span></a>
</div>
<div class="slidiv">
<a href="..." ><img src="..." >
<span> text2 </span></a>
</div>
<div class="slidiv">
<a href="..." ><img src="..." >
<span> text3 </span></a>
</div>
<div class="slidiv">
<a href="..." ><img src="...">
<span> text4 </span></a>
</div>
</div>
CSS
.slides {
overflow:hidden;
top:0;
position:relative;
width:100%;
height:206px;
z-index:920;
border-bottom:white 6px solid;
}
.slides img {
position:absolute;
left:0;
top:0;
}
.slides span {
position: absolute;
right: 100px;
top: 160px;
color:white !important;
font-size:20px;
}
Javascript
<script type="text/javascript">
$(function() {
$('.slides .slidiv:gt(0)').hide();
setInterval(function () {
$('.slides').children().eq(0).fadeOut(2000)
.next('.slidiv')
.fadeIn(2000)
.end()
.appendTo('.slides');
}, 6000); // 6 seconds
});
</script>
You have to define a unique id for each slide, then build html for circles (make sure you have a way of referencing which circle matches up to which slide). Then you capture the on click event, clear the interval, cycle forward until the slide in the "current" position matches the circle, then create the interval again. And of course every time it cycles forward you need to set a visual cue for the circle associated with the active slide.
(Demo)
HTML
<div class="slider">
<div class="slides">
<div class="slidiv" id="1">
<a href="...">
<img src="http://placehold.it/350x150/3296fa/ffffff">
<span>text1</span>
</a>
</div>
<div class="slidiv" id="2">
<a href="...">
<img src="http://placehold.it/350x150/fa9632/ffffff">
<span>text2</span>
</a>
</div>
<div class="slidiv" id="3">
<a href="...">
<img src="http://placehold.it/350x150/ff3399/ffffff">
<span>text3</span>
</a>
</div>
<div class="slidiv" id="4">
<a href="...">
<img src="http://placehold.it/350x150/33ff99/ffffff">
<span>text4</span>
</a>
</div>
</div>
<div class="circles">
</div>
</div>
CSS
.circles, .circle {
display: inline-block;
}
.circles {
position: relative;
left: 50%;
transform: translateX(-50%);
}
.circle {
padding: 5px;
border-radius: 100%;
border: 1px solid #444;
}
.active {
background: rgb(50, 150, 250);
}
JAVASCRIPT
$(function () {
$('.slides .slidiv:gt(0)').hide();
$.fn.setActive = function () {
if ($(this).hasClass("slider")) {
$(".active", $(this)).removeClass("active");
$("#circle-" + $(".slidiv:first-child", $(this),$(this)).attr("id"),$(this)).addClass("active");
return this;
}
return false;
}
$.fn.cycleFwd = function(rateStart,rateEnd) {
if ($(this).hasClass("slider")) {
$('.slides', $(this)).children()
.eq(0)
.fadeOut(rateStart)
.next('.slidiv')
.fadeIn(rateEnd)
.end()
.appendTo($('.slides', $(this)));
$(this).setActive($('.slidiv:first-child',$(this)).attr("id"));
return this;
}
return false;
}
$.fn.cycleFwdTo = function (id,rate) {
if($(this).hasClass("slider")) {
var current = $(".slidiv:first-child", $(this));
if(current.attr("id") === id) return true;
var count = id;
if(current.attr("id") > id) {
count = Number(current.nextAll().length) + Number(id) + 1;
}
if(count - current.attr("id") === 1) {
$(this).cycleFwd(rate,2000);
} else {
$(this).cycleFwd(rate,0);
$(this).cycleFwdTo(id,0);
}
return this;
}
return false;
}
$(".circle").on("click", function () {
clearInterval(window.interval);
var newFirst = $(this).attr("data-moveto");
$(this).parent().parent().cycleFwdTo(newFirst,2000);
var self = this;
window.interval = setInterval(function () {
$(self).parent().parent().cycleFwd(2000,2000);
}, 6000); // 6 seconds
});
$('.slider').each(function(){
var self = this;
window.interval = setInterval(function () {
$(self).cycleFwd(2000,2000);
}, 6000); // 6 seconds
});
});
EDIT:
This answer is not very good because it does not very well explain how it works, but this falls into "I could write a novel" explaining all of the different methods of doing what the OP has asked and how each method works. If someone else wanted to come along and offer better explanations of how this code works, I would approve.
I have for images with a number on it. Those numbers are 1-4. I want to place them numerically and when the user clicks on 1, i want them to go to slide 1 and if they click on 2, then slide 2. This also needs to have a sliding effect.
I am using this particular javascript code below for left and right options but i am not sure if I can re-use this for my purpose:
HTML would be something like:
<img src="#" class="image_one">
<img src="#" class="image_two">
<img src="#" class="image_three">
<img src="#" class="image_four">
<div class="content_for_image_One" id="slide1">
You see this when you click on image 1
</div>
<div class="content_for_image_two" id="slide2">
You see this when you click on image 2
</div>
<div class="content_for_image_three" id="slide3">
You see this when you click on image 3
</div>
<div class="content_for_image_four" id="slide4">
You see this when you click on image 4
</div>
<script type="text/javascript">
$(document).ready(function () {
var $sliderMask = $('#slider_mask');
var $slideContainer = $('#slide_container');
var $slides = $slideContainer.find('.slide');
var slideCount = $slides.length;
var slideWidth = $sliderMask.width();
$slideContainer.width(slideCount * slideWidth);
$slides.width(slideWidth);
var currentSlide = 0;
function animate() {
$slideContainer.stop().animate({ marginLeft: -(currentSlide * slideWidth) + 'px' }, 'slow');
}
$('#left_button').on('click', function () {
currentSlide = (currentSlide - 1 + slideCount) % slideCount;
animate();
});
$('#right_button').on('click', function () {
currentSlide = (currentSlide + 1) % slideCount;
animate();
});
$('#click_left').on('click', function () {
currentSlide = (currentSlide - 1 + slideCount) % slideCount;
animate();
});
$('#click_right').on('click', function () {
currentSlide = (currentSlide + 1) % slideCount;
animate();
});
});
</script>
Your provided html does not fit to your code, but let's assume you have the following html:
<div id="slidesWrapper">
<div id="slidesContainer">
<div class="slide"><!-- your html --></div>
<div class="slide"><!-- your html --></div>
<div class="slide"><!-- your html --></div>
<div class="slide"><!-- your html --></div>
</div>
</div>
<div id="thumbnails">
<img src="#" class="thumb" />
<img src="#" class="thumb" />
<img src="#" class="thumb" />
<img src="#" class="thumb" />
</div>
with the following css:
#slidesWrapper {
width: 1000px;
height: 400px;
overflow: hidden;
position: relative;
}
#slidesContainer {
width: auto;
position: aboslute;
}
.slide {
float: left;
height: 400px;
}
you could use something like:
(function($){
$(function() {
var wrapper = $('#slidesWrapper'),
container = $('#slidesContainer'),
slides = container.children(),
thumbs = $('#thumbnails').children();
container.css('left', '0');
thumbs.click(function() {
var index = $('thumbnails').children().index(this);
container.stop().animate({
left: '-' + slides.eq(index).position().left + 'px'
}, 1000);
});
});
})(jQuery);
its not tested though and I dont quite get what you want. This example fits if you have a wrapper with slides in it and only one can be visible, fixed width and height
function next()
{
var mar=$("#img_ul").css("margin-left");
var nm=mar.replace("px","");
if(nm==0)
{
$("ul").animate({"marginLeft":"-500px"},"slow");
}
else if(nm>0 || nm!=-2000)
{
nm=nm-500;
$("ul").animate({"marginLeft":nm+"px"},"slow");
}
else if(nm==-2000)
{
$("ul").animate({"marginLeft":"0px"},"slow");
}
}
function previous()
{
var mar=$("#img_ul").css("margin-left");
var nm=mar.replace("px","");
if(nm==0)
{
$("ul").animate({"marginLeft":"-2000px"},"slow");
}
else
{
nm=+nm + +500;
$("ul").animate({"marginLeft":nm+"px"},"slow");
}
}
</script>
</head>
<body>
<div id="slide_wrapper">
<ul id="img_ul">
<li>
<q>
Learn everything you can, anytime you can, from anyone you can there will always come a time when you will be grateful
you did.
</q>
</li>
<li>
<q>
Make it simple. Make it memorable. Make it inviting to look at. Make it fun to read.
</q>
</li>
<li>
<q>
If plan A fails, remember there are 25 more letters.
</q>
</li>
<li>
<q>
Do not go where the path may lead, go instead where there is no path and leave a trail.
</q>
</li>
<li>
<q>
A journey of a thousand miles must begin with a single step.
</q>
</li>
</ul>
</div>
<input type="button" id="previous" value="Previous" onclick="previous();">
<input type="button" id="next" value="Next" onclick="next();">
code from TalkersCode complete tutorial here http://talkerscode.com/webtricks/content-slider-using-jquery-and-css.php