set and clear interval multiple times - javascript

On the first slide of my slider I've got some text that changes within an interval.
This is the jQuery to do this:
<script>
var x = 0;
var text = ["STRATEGICALLY", "COST-EFFECTIVELY", "EFFICIENTLY", "EXCEPTIONALLY"];
var counter = 0;
var elem = document.getElementById("banner-change");
var intervalID = setInterval(change, 1500);
function change() {
jQuery(elem).fadeOut('slow', function() {
jQuery(elem).text(text[counter++]);
if (counter >= text.length) {
counter = 0;
}
jQuery(elem).fadeIn('fast');
if (++x === 5) {
window.clearInterval(intervalID);
}
});
}
</script>
The slider looks something like this (The shortened code):
<div id="myCarousel" class="hp-top carousel fade" data-ride="carousel" data-interval="6000">
<div class="carousel-inner">
<div class="item active"><img src="" alt="Chicago"/><div class="carousel-caption">
<div class="carousel-caption-inner">
<p class="slider-text small"><span class="slider-padding">What makes</span> us <span class="slider-green">specialists?</span></p>
<p class="slider-text">We just do ip</p>
<p class="slider-text"><span id="banner-change" class="slider-green">exceptionally</span></p>
</div>
</div>
</div>
So the words in <span id="banner-change" class="slider-green"> keep changing. This works fine. However, it only works for the first time the first banner is shown. Which makes sense as I'm clearing the interval as each word is only supposed to show once, but not sure how to do this so that every time the first banner shows it starts the interval again?

You can use the carousel evelts to trigger action.
e.relatedTarget will then refer to the slide, that is sliding into view.
So if you give it a unique id, you can identify it and run whatever action afterwards.
$('#myCarousel').on('slide.bs.carousel', function (e) {
if (e.relatedTarget.id === 'firstSlide') // do something
})

Related

How do I update the HTML when a button is clicked (change image when button is clicked)?

I'm trying to update the HTML when a button is clicked.
I have tried to solve this issue for a few hours now and I don't know if I'm stupid, but the images are not changing.
const slider = document.querySelector(".slider")
const btn = document.querySelector(".next")
const btn2 = document.querySelector(".previous")
const images = ['car.jpg', `left.jpg`]
window.addEventListener("load", iniliatizeSlider())
function iniliatizeSlider(){
var x = 0
cars = ''
cars += `<div class="slide">
<img src="${images[x]}" alt"client">
<br><br>
</div>`
slider.innerHTML = cars;
}
btn.addEventListener("click", consoleMsg)
btn2.addEventListener("click", consoleMsg2)
function consoleMsg(){
x=1
}
function consoleMsg2(){
x=0
}
<section id="slider-section">
<div class="container">
<div class="subcontainer">
<div class="slider-wrapper">
<h2>client showcase</h2>
<br />
<div class="slider"></div>
<div id="controls">
<button class="previous">
<img src="left.jpg" alt="previous client" />
</button>
<button class="next">
<img src="right.jpg" alt="next client" />
</button>
</div>
</div>
</div>
</div>
</section>
I was expecting the image to change when the button was clicked, but the image stayed the same, but the value of x changed.
Your initialize function is running once, when the page loads and at that point you are setting the image source to 0 and you never change it after that. You need to adjust the image source within the functions that react to button clicks. Now you do update x in those functions but nothing is ever done with x after that point.
A couple of other things... With .addEventListener(), you pass a reference to the callback function, not invoke the function, so the line should be: window.addEventListener("load", iniliatizeSlider) <-- no () after the function name.
Also, you don't need to replace the HTML on the page to update the image, you only need to update the image's src property.
See comments below:
// Get a reference to an existing image element.
// No need to recreate the <img> element.
const img = document.querySelector(".slider img");
const next = document.querySelector(".next");
const prev = document.querySelector(".previous");
const images = ["https://cache.mrporter.com/content/images/cms/ycm/resource/blob/1252204/68e7f03297f41cb3ce41f15ec478f70f/image-data.jpg/w1500_q80.jpg", "https://play-lh.googleusercontent.com/VC7rta8PIK3MqmQG5c-F5CNJQ6cCv6Eb-kyBoUcQ2xj83dZVhn7YCj_GIWW8y7TnAMjU=w240-h480-rw"];
let currentIndex = 0; // Keeps track of which image is shown
next.addEventListener("click", function(){
// Check to see if we're at the end of the array
if(currentIndex === images.length-1){
currentIndex = 0; // Reset index
} else {
currentIndex++; // increase the index
}
img.src = images[currentIndex]; // Just update the existing image's source
});
prev.addEventListener("click", function(){
// Check to see if we're at the beginning of the array
if(currentIndex === 0){
currentIndex = images.length-1; // Reset index
} else {
currentIndex--; // decrease the index
}
img.src = images[currentIndex]; // Just update the existing image's source
});
img { width:50px; }
<section id="slider-section">
<div class="container">
<div class="subcontainer">
<div class="slider-wrapper">
<h2>client showcase</h2>
<br >
<div class="slider">
<!-- Here, we just put a static image element with the first image we want to see. -->
<img src="https://cache.mrporter.com/content/images/cms/ycm/resource/blob/1252204/68e7f03297f41cb3ce41f15ec478f70f/image-data.jpg/w1500_q80.jpg">
</div>
<div id="controls">
<button class="previous">
<img src="left.jpg" alt="previous client">
</button>
<button class="next">
<img src="right.jpg" alt="next client">
</button>
</div>
</div>
</div>
</div>
</section>
Call the function initializeSlider() on click of btn instead of consoleMsg().

Creating a div slider in jquery

I am trying to make an image change when I click on a piece of text on a website that I am building.
At this moment I have created a class called device with one of them being device active as shown below:
<div class="col-md-3">
<div class="device active">
<img src="app/assets/images/mockup.png" alt="">
</div>
<div class="device">
<img src="app/assets/images/mockup.png" alt="">
</div>
<div class="device">
<img src="app/assets/images/mockup.png" alt="">
</div>
</div>
And then what i am currently trying to do is remove the class of active when I click on some text with the i.d of #search2. This is my whole jquery script so far:
$("#search2").click(function() {
var currentImage = $('.device.active');
var nextImage = currentImage.next();
currentImage.removeClass('active');
});
However this does not seem to remove the class of active and the image is still displayed? any ideas?
Your selection is done right and it is working for me (the active class is removed from that item). The problem must be somewhere else in your code.
Here is an alternative:
var activeDeviceIndex = 0;
$("#search2").click(function() {
var devicesContainer = $('.device');
$(devicesContainer[activeDeviceIndex]).removeClass('active');
activeDeviceIndex === devicesContainer.length - 1 ? activeDeviceIndex = 0 : activeDeviceIndex++;
$(devicesContainer[activeDeviceIndex]).addClass('active');
});
.device {
display: none;
}
.device.active {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-3">
<div class="device active">
<p>Device 1</p>
</div>
<div class="device">
<p>Device 2</p>
</div>
<div class="device">
<p>Device 3</p>
</div>
</div>
<button id="search2">click</button>
Check on the following, the id on the button to click should be search2 and not #search2, may be just typo stuffs.
after that update your code as follows
/**
*#description - gets the next image to slide, if the last image is the current image, it will loop the sliding
*#param {Element} current - the currently active image
*#param {Boolean} islooped - boolean value indicating if a looping just started
*/
var nextImage = function(current, islooped) {
var next = islooped? current : current.nextSibling;
while(next && next.nodeName.toLowerCase() !== 'div') {
next = next.nextSibling;
}
next = next? next : nextImage(current.parentNode.firstChild, true);
return next;
};
$('#search2').bind('click', function(event) {
var current = $('.device.active').removeClass('active').get(0);
var next = nextImage(current, false);
$(next).addClass('active');
});

javascript slideshow shows all photos when site opens but not otherwise

My JavaScript slideshow is acting a little wonky. When I load the page the slide show pictures are visible, but it shows all the photos in the slideshow.
After a couple of seconds, it does decompress to one photo showing, and works how it's supposed to, flipping through each one at a 5 second pace.
However, no matter what I do, it still shows all the pictures at the beginning, which defeats the point...
This is my HTML:
<div class="container">
<div style="display: inline-block; ">
<img class="mySlides" src="../images/fullshot1.jpg">
</div>
<div style="display: inline-block; ">
<img class="mySlides2" src="../images/unnamed.jpg">
</div>
<div style="display: inline-block; ">
<img class="mySlides3" src="../images/fullshot2.jpg">
</div>
</div>
And this is my Jquery/JavaScript:
$(document).ready(function() {
console.log( "document loaded" );
//declare section variables
var currentIndex = 0,
items = $('.container div'),
itemAmt = items.length;
//how to click and make it work
function cycleItems() {
var item = $('.container div').eq(currentIndex);
items.hide();
item.css('display','inline-block');
}
//interval time
var autoSlide = setInterval(function() {
currentIndex += 1;
if (currentIndex > itemAmt - 1) {
currentIndex = 0;
}
cycleItems();
}, 3000);
//this closes the doc ready
});
Can anybody help me with this/has had this problem too? Thanks!

jQuery: show/hide are instantaneous

I've one div that contains to other one:
<div>
<div id="card-container">....</div>
<div id="wait-for-result-container" style="display: none;">...</div>
</div>
On some event, I want to change the displayed element, with a fadeIn/fadeOut effect.
$('#card-container').hide(5000);
$('#wait-for-result-container').show(5000);
(I put some big number to really see the effect)
But when I trigger my effect, it is instantaneous, there is no fade-in/fade-out.
I'm not sure it matters, but I'm using jquery-3.1.1 and bootstrap 4 alpha.
Any idea what is going wrong?
EDIT
As asked, here is some clarification.
The element that I'm trying to hide is hided immediatly and the one I show is appearing immediately.
EDIT
I tried to put a demo here with the code from above:
$('#myBt').click(function(){
$('#card-container').hide(5000);
$('#wait-for-result-container').show(5000);
});
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js"></script>
<div>
<div id="card-container">First one</div>
<div id="wait-for-result-container" style="display: none;">Second one</div>
</div>
<button id="myBt">Click me</button>
If you can use the full version of jQuery, give jQuery fadeOut and fadeIn a try :)
$('#myBt').click(function(){
var duration = 5000;
$('#card-container').fadeOut(duration);
$('#wait-for-result-container').delay(duration).fadeIn(duration);
});
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<div>
<div id="card-container">First one</div>
<div id="wait-for-result-container" style="display: none;">Second one</div>
</div>
<button id="myBt">Example1</button>
If you have to stick with the slim version, you can use setInteval
$('#myBt').click(function(){
var duration = 5000;
var op = 0.9; // initial opacity
var timer1 = setInterval(function () {
if (op <= 0.1){
clearInterval(timer1);
op = 0;
$('#card-container')[0].style.display = 'none';
}
$('#card-container')[0].style.opacity = op;
op -= 100/duration;
}, 100);
var timer2 = setInterval(function () {
if (op <= 0){
$('#wait-for-result-container')[0].style.opacity = 0;
$('#wait-for-result-container').show();
}
if (op >= 1){
clearInterval(timer2);
}
if($('#wait-for-result-container').is(':visible')){
$('#wait-for-result-container')[0].style.opacity = op;
op += 100/duration;
}
}, 100);
});
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<div>
<div id="card-container">First one</div>
<div id="wait-for-result-container" style="display: none;">Second one</div>
</div>
<button id="myBt">Example2</button>

How to set this "slider" to change every 5 seconds

I developed this "slider" in jQuery
HTML:
<div class="col-md-6 pos-rel text-center">
<div class="slider-meio slider1">
<img class="img-responsive" src="http://www.novahidraulica.com.br/imgcategoria/1/2014-09-24-11-09-0420.jpg">
</div>
</div>
<div class="col-md-6 pos-rel text-center">
<div class="slider-meio active slider2">
<img class="img-responsive" src="http://www.novahidraulica.com.br/imgcategoria/1/2014-09-24-11-09-0420.jpg">
</div>
</div>
<div class="col-md-3">
<ul class="controle-slider">
<li class="active-slider"><a data-target=".slider1" >LINHA FACE PLANA</a></li>
<li class=""><a data-target=".slider2" >LINHA COLHEDORA</a></li>
</ul>
</div>
JS:
function montaSlider() {
$(".slider-meio").each(function () {
if($(this).hasClass("active")){
$(this).fadeIn();
}else {
$(this).fadeOut();
}
});
}
montaSlider();
$(".controle-slider li a").click(function () {
$(".controle-slider li a").parent().removeClass("active-slider");
$(this).parent().addClass("active-slider")
$(".slider-meio").removeClass("active");
$($(this).attr("data-target")).addClass("active")
montaSlider();
});
i want to change the slide every 5 seconds, but i cant think of how to do it
can anyone help me?
You can use the window.setInterval() javascript method to call your montarSlider() every 5 seconds. Example:
var timer = window.seInterval(montarSlider, 5000);
I recommend you to store the variable returned by the setInterval() method so you can later stop it if necessary.
EDIT: Since you also need to rotate the elements with the active class, you can first make a function called slide() to activate the next element before calling the montarSlider() function. Then, instead of set the interval to the montarSlider() function, you set it to the slide() function. Example:
function slide() {
var currentActive = $(".slider-meio.active");
var nextActive;
currentActive.removeClass("active");
if(currentActive.parent().next().children(".slider-meio").length > 0) {
nextActive = currentActive.parent().next().children(".slider-meio");
} else {
nextActive = $(currentActive.parent().siblings()[0]).children(".slider-meio");
}
nextActive.addClass("active");
montaSlider();
}
var timer = window.seInterval(slide, 5000);
Use the setInterval() function:
var intrvl = setInterval(function(){montaSlider()},5000);
I you need to stop it use:
clearInterval(intrvl);

Categories

Resources