recently I've tried to Design a slider Using Javascript and HTML . Here is what I have in HTML :
each slide is a division
<div id="sliderHolder">
<div id="slide1">Content For Slider1 </div>
<div id="slide2">Content For Slider2 </div>
<div id="slide3">Content For Slider3 </div>
</div>
And Here Is JS scripts :
function show_slider(){
document.getElementById('slide1').style.display="none";
document.getElementById('slide2').style.display="block";
document.getElementById('slide3').style.display="none";
}
function show_slider2(){
document.getElementById('slide1').style.display="none";
document.getElementById('slide2').style.display="none";
document.getElementById('slide3').style.display="block";
}
function show_slider3(){
document.getElementById('slide1').style.display="block";
document.getElementById('slide2').style.display="none";
document.getElementById('slide3').style.display="none";
}
window.onload = function() {
setTimeout(show_slider, 8000);
setTimeout(show_slider2, 16000);
setTimeout(show_slider3, 24000);
}
I'm New to JavaScript . This Works for 1 round of 24 seconds and shows each slide for 8 second and in the end shows the first slide . But what I'm looking for is to repeat the whole thing again after round finishes so the slider will continue forever .
Can You Please Help Me Out ??!
MORE To Say :
I'm not sure if I can write window.onload = function() inside another function . but I did something Like below After function show_slider3() :
function repeat() {
window.onload = function() {
setTimeout(show_slider, 8000);
setTimeout(show_slider2, 16000);
setTimeout(show_slider3, 24000);
}
}
and I added setTimeout(repeat, 25000); to window.onload = function() but it did not help me out .
Special Thanks ;
You can call the function on load, then run the function again in an interval.
window.onload = loop();
function loop() {
setTimeout(show_slider, 8000);
setTimeout(show_slider2, 16000);
setTimeout(show_slider3, 24000);
setTimeout(loop, 24000);
}
You should use the function window.setInterval to queue up a function which will run every eight seconds, eg.
var activeSlider = 0;
var sliders = [ "slide1", "slide2", "slide3" ];
function showNextSlider() {
document.getElementById('slide1').style.display="none";
document.getElementById('slide2').style.display="none";
document.getElementById('slide3').style.display="none";
var activeSliderName = sliders[ ++activeSlider % sliders.length ];
document.getElementById(activeSliderName).style.display="block";
}
window.setInterval( showNextSlider, 8000 );
Here is simple code with no requirement of function for each div, just added class "slide" to each div
<div id="sliderHolder">
<div id="slider_1" class="slide">Content For Slider1 </div>
<div id="slider_2" class="slide" style="display:none;">Content For Slider2 </div>
<div id="slider_3" class="slide" style="display:none;">Content For Slider3 </div>
</div>
And here is javascript code( no jquery)
var s=1;// start div
function show_slider() {
var cusid_ele = document.getElementsByClassName('slide');//getting all div by class name
console.log(s);
for (var i = 0; i < cusid_ele.length; ++i) {
var item = cusid_ele[i].style.display="none";// hiding all div of class "slide"
}
s++;
if( s>3 )// if reach at last div, set it to first again
s = 1;
document.getElementById('slider_'+s).style.display="block";//showing next div
}
window.setInterval(show_slider, 1000);
here is jsfiddle demo
Related
I make slideshow width 4 photos that appear with opacity: 1 and z-index: 2, and I could make it run automatically, but to control it, not yet and this is my js code with some of jquery:
$(document).ready(function() {
var i = 0
function next() {
move(i++);
if (i === 4) {
i = 0
}
console.log("first i = " + i)
};
setInterval(next, 2000);
function move(n) {
var images = document.querySelectorAll('img')
var img = images[n]
$(img).addClass('showSlide')
$(img).removeClass('hideSlide')
$(img).siblings(".img").addClass('hideSlide')
}
$('.next').click(
() => {
if (i === 3) {
i = 0
};
move(i++);
console.log("next i = " + i)
}
)
$('.previous').click(
() => {
if (i === 0) {
i = 3
};
move(i--);
console.log("previous i = " + i)
}
)})
my automatic slide work but when I click the next or the previous button the slide do not continue from the last position ,and my HTML code is :
<div class="container">
<button class="next">next</button>
<button class="previous">previous</button>
<img class="img" src="gallery-img7.jpg" alt="">
<img class="img" src="gallery-img2.jpg" alt="">
<img class="img" src="gallery-img8.jpg" alt="">
<img class="img" src="gallery-img3.jpg" alt="">
</div>
I think the way you are handling increment and decriment might be the issue? This is a good use case for modulo %. I also cleared and reset the interval after button click to get the same interval on the newly shown image. Here's an example that seems to work as your intending:
$(document).ready(function() {
var i = 0
function next() {
move(i++);
};
let nextInterval = setInterval(next, 2000);
function move(n) {
clearInterval(nextInterval)
nextInterval = setInterval(next, 2000);
n = i%4;
var images = document.querySelectorAll('img')
var img = images[n]
$(img).addClass('showSlide')
$(img).removeClass('hideSlide')
$(img).siblings(".img").addClass('hideSlide')
}
$('.next').click(
() => {
move(i++);
}
)
$('.previous').click(
() => {
move(i--);
}
)})
.img{
display:block;
width:100px;
height:100px;
}
.showSlide{
display:block;
}
.hideSlide{
display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<button class="next">next</button>
<button class="previous">previous</button>
<img class="img" src="https://via.placeholder.com/100x100.png?text=1" alt="">
<img class="img hideSlide" src="https://via.placeholder.com/100x100.png?text=2" alt="">
<img class="img hideSlide" src="https://via.placeholder.com/100x100.png?text=3" alt="">
<img class="img hideSlide" src="https://via.placeholder.com/100x100.png?text=4" alt="">
</div>
I think your code to trigger the next and previous clicks is basically working, the Interval function you are running is never interrupted by your button clicks, so the slideshow continues to cycle around.
Your classes to show and hide may not be attaching to the DOM properly either. I find it's a good practice to attach less specific classes before I attach a specific one, i.e. blanket hide all slides and then show the selected slide.
Another technique that I think is helpful is to try and figure out the manual user interaction first and then base my automation on it. I've worked up an alteration of the code you posted, where the slides 'slide' themselves by triggering the next action, similarly to how a user would.
So the slideshow should start itself on page load by use of a setInterval being declared. That setInterval is interrupted when the user moves the mouse into the slideshow area - this way the button will control the active/shown slide. If you move the mouse off or away from the slideshow container the setInterval is allowed to kick in again, and the slides should cycle around automatically.
$(document).ready(function() {
var i = 0;
function move(n) {
var images = document.querySelectorAll('img');
var img = images[n];
$(img).siblings(".img").addClass('hideSlide');
$(img).siblings(".img").removeClass('showSlide');
$(img).addClass('showSlide');
$(img).removeClass('hideSlide');
}
var next = setInterval(autoRotate, 2000);
function autoRotate() {
$('.next').trigger('click');
}
$('.container').on('mouseenter', function() {
clearInterval(next);
});
$('.container').on('mouseleave', function() {
next = setInterval(autoRotate, 2000);
});
$('.next').click(() => {
if (i === 3) {
i = 0;
} else {
i++;
}
move(i);
});
$('.previous').click(() => {
if (i === 0) {
i = 3;
} else {
i--;
}
move(i);
});
})
I was looking in other posts for the answer, but the answers never seem to work in my favor. I'm trying to make an image fade when the page finishes loading. I've figured out I can loop until the counter reaches 0 (when image is invisible) and fade the image slowly.
The problem is, the setTimeout() function doesn't seem to be working.
Here's the code:
function timeout() {
setTimeout(function () {
//A comment said something about looping,
//but it was confusing to understand...
}, 50);
}
function setup() {
var load = document.getElementById('img');
load.style.opacity = 0 //Start at being visible
for (var i = 10; i > 0; i = i - 0.1) { //For loop
load.style.opacity = i; //Use the index variable and use that to set the opacity
setTimeout(); //Set the timeout, but this function does not pause the program for some reason...
//I need to pause for 0.05 seconds.
}
}
window.addEventListener('load', setup, true); //Add event listener for when the page is done loading
<!DOCTYPE html>
<html>
<head>
<title>Webpage</title>
</head>
<body>
<div id="img">
<img src="http://www.downgraf.com/wp-content/uploads/2014/09/01-progress.gif" width="200" height="150">
</div>
</body>
</html>
I put the javascript in a seperate file, I just can't access it from Stack Overflow...
Can someone help? And also, sometimes the image can be finicky at times as well, like sometimes it won't hide like it's supposed to do. Thanks!
You declared a setTimeout without arguments, hence the error:
'Window': 1 argument required, but only 0 present."
Give it the appropriate amount of arguments:
for (var i = 10; i > 0; i = i - 0.1) { //For the loop
load.style.opacity = i;
setTimeout(functionName, milliseconds);
}
If you intended to use your timeout() function instead, call it. You're just instantiating a new setTimeout from the one you already created in the timeout() function.
You can use a recursive function instead of a loop
var load = document.getElementById('img');
function setup() {
load.style.opacity = "1"; //Start at being visible
timeout(1);
}
function timeout(i) {
setTimeout(function() {
i -= 0.1;
if(i<=0)
return;
load.style.opacity = i.toString();
timeout(i);
}, 200);
}
window.addEventListener('load', setup, true); //Add event listener for when the page is done loading
<!DOCTYPE html>
<html>
<head>
<title>Webpage</title>
</head>
<body>
<div>
<img src="http://www.downgraf.com/wp-content/uploads/2014/09/01-progress.gif" width="200" height="150" id="img">
</div>
</body>
</html>
Basically you want to countdown the opacity with a recursive call. Here we are going from 1 down to 0 in 0.01 increments. The setTimeout will trigger the next recursive call after pausing for 50 msecs. These values, can of course, be adjusted as needed but the opacity needs to be a number from 1 (visible) to 0 (invisible).
function setOpacity(el, lvl) {
el.style.opacity = lvl;
}
function countDown(el, lvl) {
function action(el, lvl) {
return function () {
countDown(el, lvl);
}
}
setOpacity(el, lvl);
if (lvl > 0) {
lvl -= 0.01
setTimeout(action(el, lvl), 50);
}
}
function setup() {
var load = document.getElementById('img');
load.style.opacity = 1; //Start at being visible
countDown(load, 1);
}
window.addEventListener('load', setup, true);
<!DOCTYPE html>
<html>
<head>
<title>Webpage</title>
</head>
<body>
<div id="img">
<img src="http://www.downgraf.com/wp-content/uploads/2014/09/01-progress.gif" width="200" height="150">
</div>
</body>
</html>
function setup() {
var load = document.getElementById('img');
(function(){
var i = 1;
setTimeout(function () {
i -= 0.1;
load.style.opacity = i;
if (i > 0) {
setTimeout(arguments.callee, 100);
}
}, 100);
})();
}
window.addEventListener('load', setup, true); //Add event listener for when the page is done loading
<div id="img">
<img src="http://www.downgraf.com/wp-content/uploads/2014/09/01-progress.gif" width="200" height="150">
</div>
I'm programming an image slideshow and for some reason it isn't working. Below I have the HTML:
<div id = "images">
<img id = "imageSrc" />
</div>
Here is my JavaScript which is what I'm using to change my images:
var images = document.getElementById("imageSrc");
var x = 0;
var imagesArray = ["image.png", "anotherImage.png", "yetAnotherImage.png"];
function changeImages() {
images.src = imagesArray[x];
if (x < 2) {
x++;
} else {
x = 0;
}
alert(images.src);
}
setInterval(changeImages(), 3000);
Demo
Why am I not getting an alert every 3 seconds with my image code? The images aren't switching so where is my mistake?
Thanks in advance for your help!
When calling a function as an argument, don't use parentheses.
setInterval(changeImages, 3000);
Demo
If you did need to pass arguments in the function call, wrap it in an anonymous function:
setInterval(function() {
var myArg;
changeImages(myArg);
}, 3000);
Demo
Remove the curly braces when you are calling the function
Change
setInterval(changeImages(), 3000);
to
setInterval(changeImages, 3000);
I have one question about image grid system.
I created this DEMO from codepen.io
In this demo you can see :
<div class="photo-row">
<div class="photo-item">
<!--Posted image here <img src="image/abc.jpg"/>-->
</div>
</div>
This DEMO is working fine but. My question is how can I use my grid system like in this css:
<div class="photo">
<div class="photo-row">
<img src="abc.jpg"/>
</div>
<div class="photo-row">
<img src="abc.jpg"/>
</div>
</div>
I created second demo for this: second DEMO. In the second demo you can see the grid system not working like first DEMO.
Also my jQuery code:
(function($,sr){
var debounce = function (func, threshold, execAsap) {
var timeout;
return function debounced () {
var obj = this, args = arguments;
function delayed () {
if (!execAsap)
func.apply(obj, args);
timeout = null;
};
if (timeout)
clearTimeout(timeout);
else if (execAsap)
func.apply(obj, args);
timeout = setTimeout(delayed, threshold || 100);
};
}
// smartresize
jQuery.fn[sr] = function(fn){ return fn ? this.bind('resize', debounce(fn)) : this.trigger(sr); };
})(jQuery,'smartresize');
/* Wait for DOM to be ready */
$(function() {
// Detect resize event
$(window).smartresize(function () {
// Set photo image size
$('.photo-row').each(function () {
var $pi = $(this).find('.photo-item'),
cWidth = $(this).parent('.photo').width();
// Generate array containing all image aspect ratios
var ratios = $pi.map(function () {
return $(this).find('img').data('org-width') / $(this).find('img').data('org-height');
}).get();
// Get sum of widths
var sumRatios = 0, sumMargins = 0,
minRatio = Math.min.apply(Math, ratios);
for (var i = 0; i < $pi.length; i++) {
sumRatios += ratios[i]/minRatio;
};
$pi.each(function (){
sumMargins += parseInt($(this).css('margin-left')) + parseInt($(this).css('margin-right'));
});
// Calculate dimensions
$pi.each(function (i) {
var minWidth = (cWidth - sumMargins)/sumRatios;
$(this).find('img')
.height(Math.floor(minWidth/minRatio))
.width(Math.floor(minWidth/minRatio) * ratios[i]);
});
});
});
});
/* Wait for images to be loaded */
$(window).load(function () {
// Store original image dimensions
$('.photo-item img').each(function () {
$(this)
.data('org-width', $(this)[0].naturalWidth)
.data('org-height', $(this)[0].naturalHeight);
});
$(window).resize();
});
Anyone can help me in this regard ? Thank you in advance for your answer.
Since you'll be creating the HTML dynamically you should remove the .photo-row container but keep .photo-item like so:
<div class="photo-item">
<img src="..." />
</div>
<div class="photo-item">
<img src="..." />
</div>
<div class="photo-item">
<img src="..." />
</div>
...
Then what you can do is wrap your elements with .photo-row on page load. First starting with various sets of two:
var imgGrab = $('.photo-item'); //photos
var imgLength = imgGrab.length; //number of photos
for ( i=0; i<imgLength; i=i+3 ) {
imgGrab.eq(i+1).add( imgGrab.eq(i+1) ).add( imgGrab.eq(i+2) ).wrapAll('<div class="photo-row"></div>'); //wrap photos
}
Then find the remanding ones and wrap those with .photo-row as well:
$(".photo-item").each(function(){
if($(this).parent().is(":not(.photo-row)")){
$(this).wrap('<div class="photo-row"></div>');
}
});
This will wrap your images dynamically and let the CSS do its job regardless of the number of them:
CODEPEN
I want to create a For loop for a series of 'click' events on my page. I'm creating a timetable where clicking on a Day button will display the events assigned to that day in a div box.
HTML
<div class="cwt-buttons">
<a id="cwt-button1">Monday</a>
<a id="cwt-button2">Tuesday</a>
<a id="cwt-button3">Wednesday</a>
<a id="cwt-button4">Thursday</a>
<a id="cwt-button5">Friday</a>
<a id="cwt-button6">Saturday</a>
<a id="cwt-button7">Sunday</a>
</div>
<div id="cwt-timetable">
<div class="current">Housework</div>
<div class="cwt-Day1">Kickboxing</div>
<div class="cwt-Day2">Homework</div>
<div class="cwt-Day3">Yoga</div>
<div class="cwt-Day4">Eating</div>
<div class="cwt-Day5">Fasting</div>
<div class="cwt-Day6">Running</div>
<div class="cwt-Day7">Funeral</div>
</div>
JS
$(function() {
for ( var i = 1; i < 8; i++ ) {
var clickedButton = $("#cwt-button"+i);
$(clickedButton).click(function() {
var currentDay = $('#cwt-timetable div.current');
var selectedDay = $('#cwt-timetable div.cwt-Day'+i);
currentDay.removeClass('current').addClass('previous');
(selectedDay).css({ opacity: 0.0 }).addClass('current').animate({ opacity: 1.0 }, 1000,
function() {
currentDay.removeClass('previous');
});
})
}
});
The JavaScript works fine when I have the exact value in e.g. "#cwt-button1"
It just doesn't work when I concatenate the 'i' counter in the loop.
Can anyone see where I'm going wrong? Or am I do something JavaScript can't handle?
This is just the same old issue that gets asked multiple times a day. All your functions created in the loop are created in the same variable scope, so they share the same i variable.
To scope a variable you need a function invocation. jQuery's $.each() is a handy way to do this:
$(function () { // -----------v-----scoped to the function
$.each(Array(7), function(i) {
var clickedButton = $('#cwt-button' + (++i));
$(clickedButton).click(function () {
var currentDay = $('#cwt-timetable div.current');
// --------using scoped `i`------------------------v
var selectedDay = $('#cwt-timetable div.cwt-Day' + i);
currentDay.removeClass('current').addClass('previous');
(selectedDay).css({
opacity: 0.0
}).addClass('current').animate({
opacity: 1.0
}, 1000, function () {
currentDay.removeClass('previous');
});
});
});
});