Attach JQuery animation to methods/setters instead of CSS properties? - jquery-ui

From the JQuery reference # http://api.jquery.com/animate/ :
$('#book').animate({
opacity: 0.25,
left: '+=50',
height: 'toggle' }, 5000, function() {
// Animation complete.
});
It seems we can only modify real CSS properties, however I wish I could animate JQuery object properties as well. As example I would like to animate the 'value' property of a progressbar:
http://jqueryui.com/demos/progressbar/#option-value
//setter
$('.selector').progressbar('option', 'value', 37);
I couldn't find a way to animate this 'value' property of the progressbar, is there any way to do so?
Thanks for help..

If it's to animate the value couldn't you use javascript setInterval() and clearInterval() method?
You could do something like:
var progressBar = $('#progress');
var index=0;
var maxCount=100;
var theInterval = setInterval (function(){
progressBar.progressbar({value:index});
if (index == maxCount) {
clearInterval(theInterval);
}
index++;
}, 100 );
In the above example the setInterval function fires every 100 milliseconds and just increases the value by 1 each time, when it hits 100 the clearInterval function stops it animating.

You might find this link useful: http://acko.net/blog/abusing-jquery-animate-for-fun-and-profit-and-bacon.
Not exactely what you wanted but you could get around and implement your own step function to update the progress bar.
var step_def = $.fx.step._default;
$.fx.step._default = function (fx) {
if ( fx.prop != 'progress' ) return step_def(fx);
fx.elem[fx.prop] = fx.now;
$(fx.elem).progressbar('option', 'value', fx.now);
};
// Now call animate
$('.selector').progressbar('option', 'value', 0)[0].progress = 0;
$('.selector').animate({ progress: 100 }, { duration: 1000 });

Related

Set a global variable inside jquery-ui slider?

I want the to prevent slider animation during page refresh, but allow it during the operation of my program.
I'm almost there:
// Initialise var animate as false
var animate = false;
// Jquery UI
function slider(min, max, step) {
$(target_slider).slider({
min: min,
max: max,
range: "min",
step: step,
// var animate set to false on load, so no animation from this guy:
animate: animate,
// var animate now set to true to allow animation every time slider is changed from now on:
var animate = true;
slide: function (event, ui) {
console.log("slider is moving!");
};
},
});
}
// Initialise slider
slider(0, 200, 0.01);
However, the code on line 13 that turns var animate to true is regarded and syntactically incorrect by jquery UI, so how can I change the variable "animate"?
I'm also still a little shaky with javascript's scope. If jquery UI did accept my variable change, would my logic work? I'm assuming it would because var animate is first declared in the global scope, but please correct me if I'm wrong!
You would want to change the value of animate after the initialization of the slider:
...
slider(0, 200, 0.01);
animate = true;
...
Also, after a variable is defined, you do not need to use the var keyword to access it.
Update After looking at the API documentation you can use the setter method to set the animate property after initialization. Try this:
function slider(min, max, step) {
$(target_slider).slider({
min: min,
max: max,
range: "min",
step: step,
animate: false,
slide: function (event, ui) {
console.log("slider is moving!");
}
});
}
// Initialise slider
slider(0, 200, 0.01);
$(target_slider).slider('option', 'animate', 'fast');

How to change jquery ui datepicker position?

Is it possible to change top and left positions (get current values and change them) of jQuery UI datepicker. Please note that i need to change position, not set margin as it is in other examples.
Sure it is. As there's always only one datepicker active, you can select active datepicker with:
var $datepicker = $('#ui-datepicker-div');
and change its position:
$datepicker.css({
top: 10,
left: 10
});
EDIT
Whoah, tricky one. If you set top or left position in beforeShow, it gets overriden again by datepicker plugin. You have to put css changes in a setTimeout:
$("#datepicker").datepicker({
beforeShow: function (input, inst) {
setTimeout(function () {
inst.dpDiv.css({
top: 100,
left: 200
});
}, 0);
}
});
DEMO: http://jsfiddle.net/BWfwf/4/
Explanation about setTimeout(function () {}, 0): Why is setTimeout(fn, 0) sometimes useful?
If you get really stuck you can edit your jquery-ui-[version].custom.js. The function that controls the position where the calender will appear is:
_findPos: function(obj) {
var position,
inst = this._getInst(obj),
isRTL = this._get(inst, "isRTL");
while (obj && (obj.type === "hidden" || obj.nodeType !== 1 || $.expr.filters.hidden(obj))) {
obj = obj[isRTL ? "previousSibling" : "nextSibling"];
}
position = $(obj).offset();
return [position.left, position.top];
},
I have some custom code that uses a CSS3 transformation to zoom the page in or out based on its width. This throws out the screen coordinates that the calendar widget relies on. I added some custom code to the _findPos to detect and handle the zoom level. Modified code looks like this:
_findPos: function(obj) {
var position,
inst = this._getInst(obj),
isRTL = this._get(inst, "isRTL");
while (obj && (obj.type === "hidden" || obj.nodeType !== 1 || $.expr.filters.hidden(obj))) {
obj = obj[isRTL ? "previousSibling" : "nextSibling"];
}
position = $(obj).offset();
/* Custom Code for Zoom */
var zoomLevel = 1;
var minW = 1024;
if ($(window).width() > minW)
{ zoomLevel = $(window).width() / minW;}
return [position.left, position.top/zoomLevel];
},
May be an old question, but ran into the problem myself just today and could not get other suggestions to work. Fixed it alternatively (using .click(function(){}) and wanted to add my two cents.
I have an input field with the id sDate which, when clicked, displays the datepicker.
What I did to solve the problem was add a click routine to the #sDate field.
$('#sDate').click(function(){ //CHANGE sDate TO THE ID OF YOUR INPUT FIELD
var pTop = '10px'; //CHANGE TO WHATEVER VALUE YOU WANT FOR TOP POSITIONING
var pLeft = '10px'; //CHANGE TO WHATEVER VALUE YOU WANT FOR LEFT POSITIONING
$('#ui-datepicker-div').css({'left':pLeft, 'top':pTop});
});
your solution works provided you run it after calling the datepicker in the code, I tried calling it before but it didn't work, so I tried to understand how it worked for you.
I have adapted the datepicker in the context of an input field which is fixed at the top of the page to scroll. The datepicker was lost ...
Here is my example code for adaptation in a context of datepicker which becomes dynamically fixed:
Example found on w3schools.com: https://www.w3schools.com/howto/howto_js_sticky_header.asp
HTML:
<div class="padding-16 center" id="resa_nav">
<div style="margin: 24px 0 0;">
<label for="date_selector"
class="text-gray">Choose a date</label>
<input type="text" id="date_selector" name="date_selector" class="padding-small">
</div>
</div>
CSS:
.sticky {
position: fixed;
top: 0;
width: inherit;
background: white;
box-shadow: 0px 0px 7px 4px #69696969;
}
JS:
// init datepicker
$('#date_selector').datepicker();
// When the user scrolls the page, execute myFunction
window.onscroll = function() { myFunction() };
// Get the header
var header = document.getElementById('resa_nav');
// Get the offset position of the navbar
var sticky = header.offsetTop;
// Add the sticky class to the header when you reach its scroll position. Remove "sticky" when you leave the scroll position
function myFunction() {
if (window.pageYOffset > sticky) {
// set block sticky
header.classList.add('sticky');
// adjust datepicker position
// attach a namespace for unbind click later in "non-sticky" context
$('#date_selector').on('click.sticked', function(){
var top = '10px';
var left = '10px';
$('#ui-datepicker-div').css({'left': left, 'top': top});
});
}
else {
// remove sticky
header.classList.remove('sticky');
// unbind the second event 'click' for retrieve the
// default of settings in "non-sticky" context
$('#date_selector').off('click.sticked');
}
}
// END FUNCTION
hope to help!
just add css as below for datepicker
.datepicker {
top: -150px;
/* adjust value as per requirement. if not work try with addin !important*/
}

Change and Slide called together jqueryui slider

I am trying to create a jquery handle that when you slide it it moves another div inside a container. Following is my js
function handleSliderChange(e, ui)
{
console.log('1');
var maxScroll = $(".content-item").width()*$(".content-item").length - $("#content-scroll").width();
$("#content-scroll").animate({scrollLeft: ui.value * (maxScroll / 100) },1000);
}
function handleSliderSlide(e, ui)
{
console.log('2');
var maxScroll = $(".content-item").width()*$(".content-item").length - $("#content-scroll").width();
$("#content-scroll").animate({scrollLeft: ui.value * (maxScroll / 100) }, 10);
}
$("#content-slider").slider({
animate: true,
slide: handleSliderSlide,
change: handleSliderChange
});
So when I click on the bar both handleSliderChange and handleSliderSlide are called, but when i drag the slider it works fine any solution ? I don't mind cancelling the click function from the slider i only need the drag anyways
I found the solution to that, the trick is to check prior to running the methods for what type of event is triggered. This is how i did it
sliderBar.slider({
start: checkType,
animate: options.animateSpeed,
slide: handleSliderSlide,
step: options.step,
change: handleSliderChange,
});
function checkType(e){
_isSlide = $(e.originalEvent.target).hasClass("ui-slider-handle");
}

Add ticks to Slider UI

I'm fairly javascript and jquery. I'm trying to add a slider to my webpage. It's a basic slider where anyone can select a value between 0-100. I'm not sure how to mark SOME intervals in the middle.
This is the code i have so far
<script>
$(function() {
var temp = 0;
$( "#slider" ).slider({
animate: true,
value:temp,
min: 0,
max: 100,
step: 1,
slide: function( event, ui ) {
$( "#amount" ).val(ui.value );
},
stop: function(event, ui) {
temp = ui.value;
//Do something
}
});
$( "#amount" ).val($( "#slider" ).slider( "value" ) );
});
</script>
It is functioning properly. What i wanna try to do is add interval markers at 0.25,50,75 and 100.
I have gone through a few questions on SO but not sure how to proceed with the implementation. Would appreciate the help.
I tried this implementation: http://jsbin.com/iwime but this is not what i am trying to do as i just want the ticks to appear at those regular intervals but users shold stll be able to select other values.
Thanks
Cheers
I am guessing you want something like this: http://jsbin.com/iwime/116
So, instead of using the number of ticks in the max option of slider, you use whatever max units you want to provide, e.g. 100. Then in refershTicks(), update the algorithm to toggle the class.
Slider settings:
var slider = $("#slider").slider({
...
max: 100, // the only change
...
});
And the refreshTicks() method:
function refreshTicks() {
var s = slider
, lo = s.slider("values", 0), hi = s.slider("values", 1);
var max = s.slider('option', 'max');
s.find(".tick").each(function(i) {
var i = (i + 1) * (max/ticks.length) - (max/ticks.length)/2; // the updated algorithm
var inRange = (i >= lo && i < hi);
$(this)
[(inRange ? 'add' : 'remove') + 'Class']("ui-widget-header")
[(inRange ? 'remove' : 'add') + 'Class']("ui-widget-content");
});
}
Similar to this SO Question : The answer from Bijan might help.
The implementation of jQuery UI slider he suggest may help you to find a solution:
http://www.filamentgroup.com/lab/update_jquery_ui_slider_from_a_select_element_now_with_aria_support/

reposition the dragged div after dropping it

is it possible to change the left position of a div after dropping it?
i'm trying to do that using this code but it's not working, can anybody help me...
thanks a million in advance :)
$(function () {
$("#task_1").draggable({ revert: 'invalid' });
$("#Lina").droppable({
drop: function (ev, ui) {
var pos = $("#task_1").position();
// kolla(pos.left);
if (pos.left < 0) {
alert(pos.left);
$("#task_1").position().left = 0;
}
else {
// do something else
}
}
});
});
Just a quick idea, have you tried:
$("#task_1").css("left","0");
If the outer drop-area has relative positioning (not sure, have to check) that should work.
Basically, you want the dropped div to shift to the very left of the drop area, right?
Update
You have it so that the position is changed when the condition is pos < 0. Since the div won't be in the drop-area if it's outside of it, I think you mean pos > 0. Also, why bother checking, if it's already 0, it just changes it to what it already is.
For instance:
$(function () {
$("#task_1").draggable({ revert: 'invalid' });
$("#Lina").droppable({
drop: function (ev, ui) {
this.position().left = 0;
}
});
});
Notice I also made it "this" since you are changing the selector.

Resources