Second picture sliding is not working by javascript - javascript

I want to add two picture slider at same page by JavaScript only. But only one slider is working and another is static.
Here is my code so far what I got from a website.
<script type="text/javascript">
window.onload = function() {
var rotator = document.getElementById("rotator");
var images = rotator.getElementsByTagName("img");
for (var i = 1; i < images.length; i++) {
images[i].style.display = "none";
}
var counter = 1;
setInterval(function() {
for (var i = 0; i < images.length; i++) {
images[i].style.display = "none";
}
images[counter].style.display = "block";
counter++;
if (counter == images.length) {
counter = 0;
}
}, 3000);
};​
</script>
<div id="rotator">
<img height="250px" width="200px" src="images/claim/1.jpg" alt="" />
<img height="250px" width="200px" src="images/claim/2.jpg" alt="" />
<img height="250px" width="200px" src="images/claim/3.jpg" alt="" />
</div>

Its because your code is applying the slide function only on one div.
Create another div with id = 'rotator2', then the following code will trigger slide on both.
<script type="text/javascript">
window.onload = function() { slideIt("rotator");slideIt("rotator2") ; } ;
function slideIt(contId) {
var rotator = document.getElementById(contId);
var images = rotator.getElementsByTagName("img");
for (var i = 1; i < images.length; i++) {
images[i].style.display = "none";
}
var counter = 1;
setInterval(function () {
for (var i = 0; i < images.length; i++) {
images[i].style.display = "none";
}
images[counter].style.display = "block";
counter++;
if (counter == images.length) {
counter = 0;
}
}, 3000);
};
</script>

You'll have to define two <div> for example rotator1 and rotator2, and apply the JS code to the 2 blocks.
<script type="text/javascript">
window.onload = function () {
var rotator = document.getElementById("rotator1");
var images = rotator.getElementsByTagName("img");
for (var i = 1; i < images.length; i++) {
images[i].style.display = "none";
}
var counter = 1;
setInterval(function () {
for (var i = 0; i < images.length; i++) {
images[i].style.display = "none";
}
images[counter].style.display = "block";
counter++;
if (counter == images.length) {
counter = 0;
}
}, 3000);
};
</script>
<div id="rotator1">
<img height="250px" width="200px" src="images/claim/1.jpg" alt="" />
<img height="250px" width="200px" src="images/claim/2.jpg" alt="" />
<img height="250px" width="200px" src="images/claim/3.jpg" alt="" />
</div>
<script type="text/javascript">
window.onload = function () {
var rotator = document.getElementById("rotator2");
var images = rotator.getElementsByTagName("img");
for (var i = 1; i < images.length; i++) {
images[i].style.display = "none";
}
var counter = 1;
setInterval(function () {
for (var i = 0; i < images.length; i++) {
images[i].style.display = "none";
}
images[counter].style.display = "block";
counter++;
if (counter == images.length) {
counter = 0;
}
}, 3000);
};
</script>
<div id="rotator2">
<img height="250px" width="200px" src="images/claim/3.jpg" alt="" />
<img height="250px" width="200px" src="images/claim/4.jpg" alt="" />
<img height="250px" width="200px" src="images/claim/5.jpg" alt="" />
</div>
Note that you should better define a JS function in a separate file and call it two times

Related

Add pause: "hover" to existing js

New here so forgive any blunders. I've searched stackoverflow but cannot find a way to add pause on hover to an existing script I got from W3Schools, can anyone tell me how? This is the code I'm using:
<script>
var myIndex = 0;
carousel();
function carousel() {
var i;
var x = document.getElementsByClassName("mySlides");
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
myIndex++;
if (myIndex > x.length) {myIndex = 1}
x[myIndex-1].style.display = "block";
setTimeout(carousel, 3000);
}
</script>
html
<!DOCTYPE html>
<html>
<head>
<title>flytipping</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta content="text/html; charset=iso-8859-2" http-equiv="Content-Type">
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<h2 class="w3-center">Flytipping_5</h2>
<div class="w3-content w3-section" style="max-width:70%">
<img class="mySlides" src="1.JPG" style="width:100%" alt="">
<img class="mySlides" src="2.JPG" style="width:100%" alt="">
<img class="mySlides" src="3.JPG" style="width:100%" alt="">
</div>
<script>
var myIndex = 0;
carousel();
function carousel() {
var i;
var x = document.getElementsByClassName("mySlides");
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
myIndex++;
if (myIndex > x.length) {myIndex = 1}
x[myIndex-1].style.display = "block";
setTimeout(carousel, 3000);
}
</script>
</body>
</html>
Try this.
In your HTML file:
<div class="mySlides" onhover="myFunction" />
In your JS file:
function myFunction() {
... do something
}
You can create a variable in your script. Set it to true on element hover, and in your function check if that variable is true then don't move your image. But you must unset this variable on mouse out.
Something like this:
<div onmouseover="stopCarousel()" onmouseout="startCarousel()"></div>
var doCarousel = true;
function stopCarousel() {
doCarousel=false;
}
function startCarousel() {
doCarousel=true;
}
function carousel() {
if(!doCarousel) return;
var i;
var x = document.getElementsByClassName("mySlides");
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
myIndex++;
if (myIndex > x.length) {myIndex = 1}
x[myIndex-1].style.display = "block";
setTimeout(carousel, 3000);
}
Store the timeout-id in a variable and call window.clearTimeout(...) on it like
<script>
var myIndex = 0;
var timeout;
carousel();
function carousel() {
var i;
var x = document.getElementsByClassName("mySlides");
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
myIndex++;
if (myIndex > x.length) {
myIndex = 1
}
x[myIndex - 1].style.display = "block";
timeout = setTimeout(carousel, 3000);
}
function stopCarousel() {
window.clearTimeout(timeout);
}
</script>
Of course you need to call the stopCarousel-function on the event you like the carousel to stop.

Add Play/Pause Button To Image slider

I'm trying to add a play and pause button to my image viewer. I have next and prev buttons working fine but would love a play and pause button integrated into my JavaScript.
Can anyone please help out?
Here is a working demo via link Demo
Script:
<div class="w3-container">
</div>
<div class="w3-content" style="max-width:800px">
<img class="mySlides" src="http://www.chorleyweather.com/forecast-charts/ecmwfcharts/na500hpa_1.png" style="width:95%"></li>
<img class="mySlides" src="http://www.chorleyweather.com/forecast-charts/ecmwfcharts/na500hpa_2.png" style="width:95%"></li>
</div>
<div class="w3-section">
<button class="w3-btn" onclick="plusDivs(-1)"><h6> Prev Image<h6/></button>
<button class="w3-btn" onclick="plusDivs(1)"><h6>Next Image<h6/> </button><h6/>
</div>
</div>
<script>
var slideIndex = 1;
showDivs(slideIndex);
function plusDivs(n) {
showDivs(slideIndex += n);
}
function currentDiv(n) {
showDivs(slideIndex = n);
}
function showDivs(n) {
var i;
var x = document.getElementsByClassName("mySlides");
var dots = document.getElementsByClassName("demo");
if (n > x.length) {slideIndex = 1}
if (n < 1) {slideIndex = x.length}
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
for (i = 0; i < dots.length; i++) {
dots[i].className = dots[i].className.replace(" w3-red", "");
}
x[slideIndex-1].style.display = "block";
dots[slideIndex-1].className += " w3-red";
}
window.onload = function() {
var image = document.getElementById("img");
function updateImage() {
image.src = image.src.split("?")[0] + "?" + new Date().getTime();
}
setInterval(updateImage, 1000);
}
</script>
A way would be with a boolean which determines if it should be playing or not, and a button that changes the value of that boolean.
button:
<button id="playpause"></button>
updated window.onload = function
window.onload = function() {
var image = document.getElementById("img");
var playing = true;
function updateImage() {
if (playing) {
image.src = image.src.split("?")[0] + "?" + new Date().getTime();
}
}
var playpause = document.getElementById("playpause");
playpause.onclick = function() {
if (playing) {
playing = false;
} else {
playng = true;
}
};
setInterval(updateImage, 1000);
}
Didn't try this, but it should do the trick.

How to grab the src of img tag that is within an anchor tag with javascript?

The Html Code is as follows, I have more of these tags hence the class:
<a class = "openmodal">
<img class="case" src="aqua.jpg>
<h4>Aqua</h4>
</a>
The javascript is as follows,basically i want to grab the img tag so that i can get its src:
var btns = document.getElementsByClassName("openmodal");
for(let i=0;i<btns.length;i++){
var x = btns[i].firstChild;
console.log(x);
btns[i].onclick = function() {
modal.style.display = "block";
}
}
Use querySelectorAll
// will give all anchor tag with this class
var btns = document.querySelectorAll(".openmodal");
// iterating this collection
for (let i = 0; i < btns.length; i++) {
// inside this element it is querying for img tag & adding event listener to it
btns[i].querySelector('img').addEventListener('click', function() {
// get the src attribute from it
var m = this.getAttribute('src');
console.log(m)
})
}
<a class="openmodal">
<img class="case" src="aqua.jpg" alt="img">
<h4>Aqua</h4>
</a>
<a class="openmodal">
<img class="case2" src="aqua2.jpg" alt="img">
<h4>Aqua2</h4>
</a>
try document.getElementsByTagName("img") to get images only
HTML
<a class = "openmodal">
<img class="case" src="aqua.jpg" />
<h4>Aqua</h4>
</a>
<img class="case" src="aqua1.jpg" />
JS
var imgclasses = document.getElementsByClassName('openmodal');
for (var imgclass of imgclasses) {
var imgs = imgclass.getElementsByTagName("img");
for(let i=0;i<imgs.length;i++){
var x = imgs[i];
console.log(x.src);
imgs[i].onclick = function() {
modal.style.display = "block";
}
}
};
codepen: https://codepen.io/YasirKamdar/pen/zRWqyg
Much faster and better approach.
var btns = document.getElementsByClassName("openmodal");
var len = btns.length;
while(len--){
var btn = btns[len];
btn.children[0].onclick = function() {
console.log(this.src);
};
}
<a class = "openmodal">
<img class="case" src="aqua.jpg">
<h4>Aqua</h4>
</a>
<a class = "openmodal">
<img class="case" src="aqua2.jpg">
<h4>Aqua</h4>
</a>
You could try in this way to get src attribute of an img.
var ele = document.getElementsByClassName('openmodal');
if(ele.length > 0){
for (i = 0; i < ele.length; i++) {
for(j = 0; j < ele[i].children.length; j++){
if(ele[i].children[j].hasAttribute('src')){
console.log(ele[i].children[j].getAttribute('src'));
}
}
}
}
<a class="openmodal">
<img class="case" src="aqua.jpg">
<h4>Aqua</h4>
</a>

Unable to add an onclick event to element using JS

Hey I have a span element that I am creating with JS and I want it to also have an onclick event that calls a function. I am referring to the function fillSlides() and dotFunction(), but I will show all of my functions.
function openModal() {
document.getElementById('myModal').style.display = "block";
}
function closeModal() {
document.getElementById('myModal').style.display = "none";
}
var slideIndex = 1;
showSlides(slideIndex);
function plusSlides(n) {
showSlides(slideIndex += n);
}
function currentSlide(n) {
showSlides(slideIndex = n);
}
function fillSlides(modalID){
var container = document.getElementsByClassName("modal-content");
var bcontainer = document.getElementById("myModal");
var dcontainer = document.createElement('dot_content');
var slides = {
"1": ["Images/LS_01.jpg", "Images/LS_02.jpg", "Images/LS_03.jpg", "Images/LS_04.jpg" ],
"2": ["Images/LS_05.jpg", "Images/LS_06.jpg", "Images/LS_07.jpg", "Images/LS_08.jpg" ],
"3": ["Images/img1.jpg", "Images/img2.jpg", "Images/img3.jpg", "Images/2.jpg" ]
};
var modal_num = modalID.getAttribute('data-modal');
//alert(slides[modal_num].length);
for (var i = 0 ; i < slides[modal_num].length; i++) {
var the_divs = document.createElement('div');
var s_img = document.createElement('img');
var s_dot = document.createElement('span');
the_divs.className = 'mySlides';
s_img.src = slides[modal_num][i];
the_divs.appendChild(s_img);
container[0].appendChild(the_divs);
dcontainer.className = 'dot-content';
dcontainer.id = 'dot_content';
s_dot.className = 'demo';
dcontainer.appendChild(s_dot);
container[0].appendChild(dcontainer);
s_dot.onclick = currentSlide(i);
}
}
/*
function clearSlides(){
var myNode = document.getElementById("modal_content");
while (myNode.firstChild) {
myNode.removeChild(myNode.firstChild);
}
}*/
function clearSlides() {
var myNode = document.getElementById("modal_content");
//use spread operator to convert nodelist to array for using
// array methods
var c = [...myNode.children];
c.forEach(function(item, index) {
console.log(item)
// check if the current element have a class using 'contains'
if (!item.classList.contains('elbutton')) {
//use remove method to remove the element
item.remove();
}
})
}
/*
function clearSlides(){
var myNode = document.getElementById("modal_content");
var childNodes = myNode.childNodes;
for(var i=0; i<childNodes.length; i++){
if(childNodes[i].className === "mySlides"){
myNode.removeChild(childNodes[i])
}
}
}
*/
function showSlides(n) {
var i;
var slides = document.getElementsByClassName("mySlides");
var dots = document.getElementsByClassName("demo");
var captionText = document.getElementById("caption");
if (n > slides.length) {slideIndex = 1}
if (n < 1) {slideIndex = slides.length}
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
for (i = 0; i < dots.length; i++) {
dots[i].className = dots[i].className.replace(" active", "");
}
slides[slideIndex-1].style.display = "block";
dots[slideIndex-1].className += " active";
//captionText.innerHTML = dots[slideIndex-1].alt;
}
function dotfunction() {
var slides = document.getElementsByClassName("mySlides");
var dotfunctionadder = document.getElementsByClassName("demo");
for (var i = 0; i < slides.length; i++) {
dotfunctionadder.onclick = currentSlide(i);
}
}
<body id="modal-2">
<h2 id="title" style="text-align:center">hellkkko</h2>
<div class="row">
<div class="column">
<img id="modal-1" src="https://www.yosemitehikes.com/images/wallpaper/yosemitehikes.com-bridalveil-winter-1200x800.jpg" style="max-width:100%" data-modal="1" onclick="fillSlides(this); openModal(); currentSlide(1); " class="hover-shadow cursor">
</div>
</div>
<div class="row">
<div class="column">
<img id="modal-2" src="https://www.yosemitehikes.com/images/wallpaper/yosemitehikes.com-bridalveil-winter-1200x800.jpg" style="max-width:100%" data-modal="2" onclick="fillSlides(this); openModal(); currentSlide(1); " class="hover-shadow cursor">
</div>
</div>
<div class="row">
<div class="column">
<img id="modal-3" src="https://www.yosemitehikes.com/images/wallpaper/yosemitehikes.com-bridalveil-winter-1200x800.jpg" style="max-width:100%" data-modal="3" onclick="fillSlides(this); openModal(); currentSlide(1); " class="hover-shadow cursor">
</div>
</div>
<div id="myModal" class="modal">
<span class="close cursor" onclick="clearSlides(); closeModal();">×</span>
<div class="modal-content" id="modal_content">
<a class="elbutton prev" onclick="plusSlides(-1)">❮</a>
<a class="elbutton next" onclick="plusSlides(1)">❯</a>
</div>
</div>
I tried calling dot function from the onclick of a different element (because the span I want to add it to is being created with JS) within the html but nothing happened. How do I do this and what am I doing wrong?
Try putting your script in the head section if you want to bind click handler inside html.
Below is the fiddle that i tested with your chanegs.
<head>
<script>
function openModal() {
document.getElementById('myModal').style.display = "block";
}
function closeModal() {
document.getElementById('myModal').style.display = "none";
}
..........
</script>
<head>
"https://jsfiddle.net/ajaygandhi06/smca56fv/"
It works when you put your js inside head tag.

button to start and stop my code in javascript

I would like to have a stop and start button for my code. So I can break the working the source code does.
<script language="JavaScript">
var i = 0;
var path = new Array();
// LIST OF IMAGES
path[0] = "http://static.giantbomb.com/uploads/original/0/31/11738-ssj_goku.jpg";
path[1] = "http://i.kinja-img.com/gawker-media/image/upload/arjw8wqvwnihalb6fq3k.png";
path[2] = "http://orig03.deviantart.net/8999/f/2013/167/1/7/sword_art_online_by_sakimichan-d69cxwk.jpg";
function swapImage() {
document.slide.src = path[i];
if (i < path.length - 1)
i++;
else
i = 0;
setTimeout("swapImage()",3000);
}
window.onload=swapImage;
</script>
<img height="200" name="slide" src="image_1.gif" width="400" />
This will define a variable (running) and toggle between true and false on click of the toggle link:
<!DOCTYPE html>
<html>
<body>
<script language="JavaScript">
var running = true;
var i = 0;
var path = new Array();
// LIST OF IMAGES
path[0] = "http://static.giantbomb.com/uploads/original/0/31/11738-ssj_goku.jpg";
path[1] = "http://i.kinja-img.com/gawker-media/image/upload/arjw8wqvwnihalb6fq3k.png";
path[2] = "http://orig03.deviantart.net/8999/f/2013/167/1/7/sword_art_online_by_sakimichan-d69cxwk.jpg";
function ToggleRunning()
{
running = !running;
if (running)
swapImage();
}
function swapImage()
{
document.slide.src = path[i];
if(i < path.length - 1) i++; else i = 0;
if (running)
setTimeout("swapImage()",3000);
}
window.onload=swapImage;
</script>
<img height="200" name="slide" src="image_1.gif" width="400" />
<button onclick="ToggleRunning();">Toggle</button>
</body>
</html>

Categories