jQuery UI Slider for changing Image with auto slide - javascript

I´d like to build a UI Slider to change an Image. So far, I´ve managed that the Image will change manually and automaticly every three Seconds.
I´m not very happy with the code, because when it reaches the max-value and repeats from beginning, it skippes the last value because of the setInterval. Is there an easier and prettier way to solve this?
HTML
<div id="wrapper">
<div class="image">
<img id="image" src="http://fakeimg.pl/350x200/?text=0&font=lobster" />
</div>
<div id="slider"></div>
</div>
Script
$(function () {
$('#slider').slider({
value: 0,
min: 0,
max: 5,
step: 1,
change: function (event, ui) {
var slideruivalue = (ui.value);
image = $('#image');
image.attr('src', 'http://fakeimg.pl/350x200/?text=' + slideruivalue);
if (slideruivalue == $(this).data("slider").options.max) {
$('#slider').slider('value', 0);
}
}
});
$(function AutoSlider() {
setTimeout(function () {
$("#slider").slider("value", $('#slider').slider("value") + 1);
}, 3000);
setTimeout(AutoSlider, 3000);
});
});
jsFiddle Example

In your setTimeout, get the max of your slider, and then calculate the new value with a modulus (operator %) on max+1 :
setInterval(function () {
var value = $('#slider').slider("value");
var max = $('#slider').slider( "option", "max" );
$("#slider").slider("value", (value + 1)% (max+1));
}, 3000);
Then, there is no need to check the value in the change callback :)
You can also use setInterval instead of two setTimeout
http://jsfiddle.net/q5R68/1/

Related

Jquery UI Slider set value dynamically on sliding the slider

I'm using jquery slider , If I slide the slider,In slide function
I will test certain scenario . If the scenario is not satisfied the slider should be positioned back to its original position .
For example :
The current slider value is 1 and the user slide it to value 2, in slide: function (event, ui) function I'm checking the condition if not satisfied the value of the slider should be reverted back to value 1 .
So that I have used the code in else part
$("#slider").slider({ value: parseFloat(return_slider_value) });
$("#slider").slider('value', 1);
It is not setting back the value 1 still it shows the value 2 in the slider.
My requirement is the value of slider value should be dynamically changed .
var slider_Value = $.trim(data.details.merchant_table_booking_hours);
if (slider_Value == '')
{
slider_Value = 0;
}
var return_slider_value = slider_Value;
$("#slider").slider({
value: slider_Value,
min: 0,
max: 12,
step: 0.5,
slide: function (event, ui)
{
var selected_button_count = 0;
$(".time_slot_buttons").each(function ()
{
if(this.attr('selected-id')==0)
{
selected_button_count = parseInt(selected_button_count)+1;
}
});
if (selected_button_count>0)
{
if (parseFloat(ui.value) != 0)
{
$("#slider-value").val(ui.value);
$("#show-slider-hrs").html(ui.value + " hrs ");
} else
{
$("#slider-value").val('');
$("#show-slider-hrs").html('');
}
}
else
{
alert("Please Select a Floor And Timing Buttons" + return_slider_value);
$("#slider-value").val(return_slider_value);
$("#show-slider-hrs").html(return_slider_value + " hrs ");
$("#slider").slider({ value: parseFloat(return_slider_value) });
$("#slider").slider('value', 1);
}
}
})
Thanks in advance .
As you will see from the API documentation on jQuery UI Slider (http://api.jqueryui.com/slider/), the slider can be read and set the following way, after initialization:
// Getter
var value = $( ".selector" ).slider( "option", "value" );
// Setter
$( ".selector" ).slider( "option", "value", 10 );
EDIT:
The answer might possibly depend on the value that you return to the slide event.
Consider this code.
$(function() {
$("#slider").slider({
value: 1,
min: 0,
max: 12,
step: 0.5,
slide: function(event, ui) {
//Evaluate condition
var condition = false; //or true
if (!condition)
return false; //Canceling the event will prevent the handle from moving and the handle will continue to have its previous value.
else
return true;
}
});
});
Full example here.
Canceling the slide event will prevent the handle from moving and the handle will continue to have its previous value.

Storing values of UI Slider

After spending hours on several tutorial books and online help I am not able to figure out my problem.Here i am trying to store values of UI slider using localstorage object and it is working fine ( i am getting stored value on every page load) but UI slider pointer not moving according to stored value
it shows position as zero(0) on every page load.
Any suggestion would be a great help
Thanks
<script>
$(function() {
$( "#slider-range" ).slider({
min: 0,
max: 100,
step:25,
value:show(),
change: function() {
iremember();
},
stop: function( event, ui ) {
$.post('volume.php', {volume: ui.value}, function(data) {
});
$('#volume').val(ui.value+' %');
}
});
});
function iremember()
{
var dataTosave=document.getElementById("volume").value
localStorage.setItem("intdata",dataTosave)
}
function show()
{
var dataToshow=localStorage.getItem("intdata")
document.getElementById("volume").value=dataToshow
}
</script>
html-----
<div class="def_class" id="slider-range"></div>
<input type="text" id="volume"/>
Your function show() should return a value:
function show() {
var dataToshow=localStorage.getItem("intdata");
document.getElementById("volume").value=dataToshow;
return parseInt(dataToshow);
}

Fading a tag in, fading it out and then changing the text before repeating the process

I have an tag that is having its contents changed via jquery and then faded in and out (using the velocity js library) utilizing the setInterval function. When I run this it tends to work fine for about 30 seconds before it starts to malfunction and jquery starts to change the contents of the tag before the tag has faded out.
Here is the Javascript code
let counter = 0;
function chooseWord() {
let words = ["foo", "bar", "foo"];
if (counter !== 2) {
counter += 1;
} else {
counter = 0;
}
return words[counter];
}
function refreshText() {
$("#div").text("Foo " + chooseWord())
.velocity("fadeIn", {
duration: 2500
})
.velocity("fadeOut", {
delay: 1500,
duration: 2500
});
}
$(document).ready(function() {
refreshText();
setInterval(function() {
refreshText();
}, 7000);
});
And here is my tag that is being used
<h1 class="foobar" id="div"></h1>
I've tried using Jquery's timer and I have the same issue. Does anyone know what the problem might be or maybe a different way of achieving what I want to do?
You just need to change the order of operations. I have moved the text-change command after fade-out. So the element fades out, and then jQuery will update its text.
$("#div")
.velocity("fadeIn", {
duration: 2500
})
.velocity("fadeOut", {
delay: 1500,
duration: 2500
})
.text("Foo " + chooseWord());
Fiddle: https://jsfiddle.net/Nisarg0/gLed0h1y/

Alternate content of a div every 3 seconds with javascript

I would like to alternate the contents of a div (or swap in a new div if better) every few seconds, with a fade in/out. Jquery prefered, or pure js fine too.
Based on Arun's solution, I have added the Jquery below, and it works perfectly... but how do I make it repeat?
HTML:
<div class="wrapper" style="height:100px">
<div id="quote1">I am a quote</div>
<div id="quote2">I am another quote</div>
<div id="quote3">I am yet another quote</div>
</div>
Javascript: (as per Arun in the comments)
jQuery(function () {
var $els = $('div[id^=quote]'),
i = 0,
len = $els.length;
$els.slice(1).hide();
setInterval(function () {
$els.eq(i).fadeOut(function () {
$els.eq(++i % len).fadeIn();
})
}, 2500)
})
Try
jQuery(function () {
var $els = $('div[id^=quote]'),
i = 0,
len = $els.length;
$els.slice(1).hide();
setInterval(function () {
$els.eq(i).fadeOut(function () {
i = (i + 1) % len
$els.eq(i).fadeIn();
})
}, 2500)
})
Demo: Fiddle
Here is a working example:
jQuery(function () {
var $els = $('div[id^=quote]'),
i = 0,
len = $els.length;
$els.slice(1).hide();
setInterval(function () {
$els.eq(i).fadeOut(function () {
i = (i + 1) % len
$els.eq(i).fadeIn();
})
}, 2500)
})
this sounds like a job for...a slider. There are a ton of jQuery plugin options out there,
I've always been a fan of Malsup
jQuery plugins by malsup
he even has responsive ones ready to go. Google "jQuery slider" to be overwhelmed with options.
Use a slider plugin there are lots on the internet. This is a simple snippet I wrote that works with any number of elements without having to change the javascript.
It's very easy to change.
http://jsfiddle.net/Ux9cD/39/
var count = 0;
$('.wrapper div').css('opacity', '0');
var varName = setInterval(function() {
//hide all the divs or set opacity to 0
$('.wrapper div').css('opacity', '0');
//get length
var length = $('.wrapper div').length;
//get first child:
var start = $('.wrapper div').eq(count);
if (count < length) {
animateThis(start,length,count);
count++;
} else {
console.log('end of list');
//restore back to hidden
//set count back to 0
$('.wrapper div').css('opacity', '0');
count = 0;
}
}, 2000);
varName;
function animateThis(start,length,count)
{
$( start ).animate({
opacity: 1
}, 1000, "linear", function() {
//return count++;
});
}
This will do it if you set your second and third divs to hidden:
window.setInterval(function(){
window.setTimeout(function(){
$('#quote1').fadeIn('slow').delay(3000).fadeOut('fast').delay(6000);
}, 0);
window.setTimeout(function(){
$('#quote2').fadeIn('slow').delay(3000).fadeOut('fast').delay(6000);
}, 3000);
window.setTimeout(function(){
$('#quote3').fadeIn('slow').delay(3000).fadeOut('fast').delay(6000);
}, 6000);
}, 3000);
It's not going to do exactly what you want because fading takes time, so two divs will be onscreen at the same time. I tried to remedy this by having them fadeIn() slowly and fadeOut() quickly, but I'd recommend taking out the fading altogether and just hiding them.
See demo.
Also, #ArunPJohny has a solution here that is a bit difficult to understand but does get rid of the fading delay problem. Alternatively, here's my no-fading solution.
HTML
<div id="div1">quote 1</div>
<div id="div2" style="display:none">quote 2</div>
JavaScript
i=0;
setInterval(function(){
if(i%2 == 0)
$('#div1').fadeOut('slow', function(){
$('#div2').fadeIn('slow')
})
else
$('#div2').fadeOut('slow', function(){
$('#div1').fadeIn('slow')
})
i++;
}, 2000)
Fiddle
Here is something you can try if you can do without fade in and fadeout. Just a simple few lines of java script no need to add any plugins etc.
Also look at this link Jquery delay it has sample with delay and fade in fadeout. May be you can tailor it to your needs.
Try in your browser
<html>
<head>
<script type="text/javascript">
function swapDiv(){
var firstString = document.getElementById("quote1").innerHTML;
var secondString = document.getElementById("quote2").innerHTML;
document.getElementById("quote1").innerHTML = secondString;
document.getElementById("quote2").innerHTML = firstString;
setTimeout(swapDiv, 3000);
}
setTimeout(swapDiv, 3000);
</script>
</head>
<body>
<div id="quote1">I am another quote</div><span>
<div id="quote2">I am yet another quote</div><span>
</body>
</html>

add autoplay to basic jquery slider

Im making a basic jQuery slider for class. and would like to have it autoplay playing the next slide after 5 seconds but haven't used the timer before it isn't doing what I thought it should do. It waits for the proper interval and then keeps triggering the callback function.
//basic slider on click
$('.slider>ul>li').click(function()
{
$('.slider>ul>li').removeClass('current');
$(this).toggleClass('current');
right=$(this).index()*745;
$(this).parent('ul').parent('.slider').children('div').children('ul').animate({'right': right}, 1000, 'easeOutBack');
})
//attempt to use timer plugin to auto play
$('.slider>ul>li').timer(
{
delay: 1000,
callback: function()
{alert($('.slider>ul>li.current').index())
if($('.slider>ul>li.current').index()!=3)
{
$('.slider>ul>li.current').next('li').click();
}else//oddly this doesn't trigger at all
{
$('.slider>ul').first().click();
}
}
})
Try this:
setInterval(function(){
var i = $('.slider>ul>li.current').index();
var next = (i < 3 ? i+1 : 0);
var items = $('.slider>ul>li');
$(items[next]).click();
}, 5000);
EDIT:
changed setTimeout to setInterval and bumped time to 5sec; this should now loop.

Categories