How to Add +200ms to css animation-duration on click jQuery - javascript

There is a div with css animation
.mydiv {
animation: ticker 2000ms linear 0s infinite normal none running;
}
The animation-duration property is set to 2000ms
and im trying to change the speed of the animation with jquery
for example adding 200ms to the currentvalue
something like
$( "#speedup" ).click(function() {
var mydiv = $( ".mydiv" );
var val = mydiv.css('animation-duration');
$(".mydiv").css("animation-duration", val + "ms")+200;
});

The variable 'val' is not an integer (2s). You can't multiply with this value. You need to use parseInt() to return the integer (2).
$('#speedup').click(function(){
var mydiv = $( ".mydiv" );
var val = mydiv.css('animation-duration');
var newVal = (parseInt(val) * 1000); //parseInt(val) creates the integer 2. Multiply with 1000 to get 2000
mydiv.css({"animation-duration" : newVal - 200 + "ms"});
});
Edit: ParseFloat is even better. This way you can use toFixed to get the integer with 2 decimals.
https://jsfiddle.net/qcajbtz8/
$('#speedup').click(function(){
var mydiv = $( ".mydiv" );
var val = mydiv.css('animation-duration');
var newVal = (parseFloat(val).toFixed(2) * 1000);
mydiv.css({"animation-duration" : newVal - 200 + "ms"});
});

Try this.
var val = currentvalue;
$( "#speedup" ).click(function() {
var mydiv = $( ".mydiv" );
val = val + 200;
$(".mydiv").css("animation-duration", val + "ms");
});

Related

Change jquery animate to manually control function

I want to change jquery animate function, to a function which would let me control everything manualy. Currently code increases multiple numbers with delay. Here's the code (https://jsfiddle.net/6mrLv1ma/8/):
var ammount = 10;
var duration = 0.5;
var delay = (1-duration)/ammount; // 0.05
curDelay = 0;
for(var i=0;i<ammount;i++) {
$( "#container" ).append("<div id='output"+i+"'>0</div>");
setTimeout(
(function(i) {
return function() {
animate(i, duration);
}
})(i, duration),curDelay*1000);
curDelay += delay;
}
function animate(i, duration){
$({value: 0}).animate({value: 1}, {
duration: duration*1000,
step: function() {
var placement = "output"+i;
document.getElementById(placement).innerHTML = this.value;
}
})
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container"></div>
Here's graph how it's working:
So if currentProc = 0.2, the output should be something like this:
0.3
0.16
0.07
0
0
0
0
0
0
0
I already started but need help with the formula(https://jsfiddle.net/18kd85hn/1/):
var ammount = 10;
var duration = 0.5;
var delay = (1-duration)/ammount; // 0.05
function myFunction(currentProc){ // currentProc value 0 - 1
var values = [];
for(var i = 0; i<ammount;i++){
var currentPos = i*delay; // formula
document.getElementById("output").innerHTML += "<br>"+currentPos;
}
}
myFunction(0.2)
<div id="output">output:</div>
Got it (https://jsfiddle.net/18kd85hn/7/)
var value = 1-(i*delay+duration-currentProc)/duration;
if (value<0){value =0}
if (value>1){value =1}
And replaced jquery animate - https://jsfiddle.net/18kd85hn/8/

jQuery setInterval to continuously update data attribute

I have a div class name "tw_marquee_scroller" . I want to update it's data-left value in every 1 second. For example in the first second the value will be 10, then 20,30,40 ....... I am using this code but it's keep returning 10 again and again. What's wrong with this?
jQuery(document).ready(function($){
$('.tw_marquee_scroller').attr('data-left', 0);
setInterval(function(){
var position = parseInt($('.tw_marquee_scroller').data('left'));
var new_position = position + 10;
$('.tw_marquee_scroller').attr('data-left', new_position);
console.log(new_position);
}, 1000);
});
Try also writing data attribute with data(), not attr():
$('.tw_marquee_scroller').data('left', 0);
setInterval(function(){
var position = parseInt($('.tw_marquee_scroller').data('left'));
var new_position = position + 10;
$('.tw_marquee_scroller').data('left', new_position);
console.log(new_position);
}, 1000);
why you didn't take the value in the same way?
jQuery(document).ready(function($){
$('.tw_marquee_scroller').attr('data-left', 0);
setInterval(function(){
var position = parseInt($('.tw_marquee_scroller').attr('data-left'));
var new_position = position + 10;
$('.tw_marquee_scroller').attr('data-left', new_position);
console.log(new_position);
}, 1000);
});
Change the data('left') in that line to:
var position = parseInt($('.tw_marquee_scroller').attr('data-left'))
And it will work
Here is a less window-polluting-shorter approach:
$( (function($) {
var scroller = $('.tw_marquee_scroller');
scroller.data('left', 0);
setInterval( function() {
scroller.data('left', parseInt( scroller.data('left'), 10 ) + 10 );
console.log( scroller.data("left") );
}, 1000 );
}(jQuery.noConflict())) )

Can't set value of JQuery UI Slider

I have 3 Sliders in one JQuery Dialog, i want them to have a maximum value, but the maximum is not only for one slider it is for the sum of all of them. My script runs fine in google chrome debuger the only problem is that the value of the slider is not updated in $(this).slider("value", (sliderMax - sum));
$(".slider").each(function() {
var id = $(this).attr("id");
id = id.replace("Slider", "Value");
var sliderMax = 27;
$(this).slider({
range : "min",
min : 0,
max : sliderMax,
value : $("#" + id).attr("value"),
slide : function(event, ui) {
var sum = 0;
$(".sliderValue").each(function() {
if ($(this).attr("id") != id) {
sum += parseInt($(this).attr("value"));
}
});
if ((sum + $(this).slider("value")) > sliderMax){
$(this).slider("value", (sliderMax - sum));
}
$("#" + id).val(ui.value);
}
});
});
pls help me.
Ok finaly i found the solution:
if ((sum + ui.value) > sliderMax){
return false;
}
It is because of params of parseInt and value:... parseInt returns fake value when the string provided as parameter doesn't contain a number! please define the value variable outside the options as follows
$(".slider").each(function() {
var id = $(this).attr("id");
id = id.replace("Slider", "Value");
var sliderMax = 27;
var _value=$("#" + id).attr("value");
$(this).slider({
range : "min",
min : 0,
max : sliderMax,
value :value,
slide : function(event, ui) {
var sum = 0;
$(".sliderValue").each(function() {
if ($(this).attr("id") != id) {
var valueString=$(this).attr("value");
sum += parseInt(valueString);
}
});
if ((sum + $(this).slider("value")) > sliderMax){
$(this).slider("value", (sliderMax - sum));
}
$("#" + id).val(ui.value);
}
});
});
EDITS:
copied your solution to help readers
if ((sum + ui.value) > sliderMax){
return false;
}

How to clone and change id?

I need to clone the id and then add a number after it like so id1, id2, etc. Every time you hit clone you put the clone after the latest number of the id.
$("button").click(function() {
$("#id").clone().after("#id");
});
$('#cloneDiv').click(function(){
// get the last DIV which ID starts with ^= "klon"
var $div = $('div[id^="klon"]:last');
// Read the Number from that DIV's ID (i.e: 3 from "klon3")
// And increment that number by 1
var num = parseInt( $div.prop("id").match(/\d+/g), 10 ) +1;
// Clone it and assign the new ID (i.e: from num 4 to ID "klon4")
var $klon = $div.clone().prop('id', 'klon'+num );
// Finally insert $klon wherever you want
$div.after( $klon.text('klon'+num) );
});
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<button id="cloneDiv">CLICK TO CLONE</button>
<div id="klon1">klon1</div>
<div id="klon2">klon2</div>
Scrambled elements, retrieve highest ID
Say you have many elements with IDs like klon--5 but scrambled (not in order). Here we cannot go for :last or :first, therefore we need a mechanism to retrieve the highest ID:
const all = document.querySelectorAll('[id^="klon--"]');
const maxID = Math.max.apply(Math, [...all].map(el => +el.id.match(/\d+$/g)[0]));
const nextId = maxID + 1;
console.log(`New ID is: ${nextId}`);
<div id="klon--12">12</div>
<div id="klon--34">34</div>
<div id="klon--8">8</div>
Update: As Roko C.Bulijan pointed out.. you need to use .insertAfter to insert it after the selected div. Also see updated code if you want it appended to the end instead of beginning when cloned multiple times. DEMO
Code:
var cloneCount = 1;;
$("button").click(function(){
$('#id')
.clone()
.attr('id', 'id'+ cloneCount++)
.insertAfter('[id^=id]:last')
// ^-- Use '#id' if you want to insert the cloned
// element in the beginning
.text('Cloned ' + (cloneCount-1)); //<--For DEMO
});
Try,
$("#id").clone().attr('id', 'id1').after("#id");
If you want a automatic counter, then see below,
var cloneCount = 1;
$("button").click(function(){
$("#id").clone().attr('id', 'id'+ cloneCount++).insertAfter("#id");
});
This is the simplest solution working for me.
$('#your_modal_id').clone().prop("id", "new_modal_id").appendTo("target_container");
This works too
var i = 1;
$('button').click(function() {
$('#red').clone().appendTo('#test').prop('id', 'red' + i);
i++;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<div id="test">
<button>Clone</button>
<div class="red" id="red">
</div>
</div>
<style>
.red {
width:20px;
height:20px;
background-color: red;
margin: 10px;
}
</style>
I have created a generalised solution. The function below will change ids and names of cloned object. In most cases, you will need the row number so Just add "data-row-id" attribute to the object.
function renameCloneIdsAndNames( objClone ) {
if( !objClone.attr( 'data-row-id' ) ) {
console.error( 'Cloned object must have \'data-row-id\' attribute.' );
}
if( objClone.attr( 'id' ) ) {
objClone.attr( 'id', objClone.attr( 'id' ).replace( /\d+$/, function( strId ) { return parseInt( strId ) + 1; } ) );
}
objClone.attr( 'data-row-id', objClone.attr( 'data-row-id' ).replace( /\d+$/, function( strId ) { return parseInt( strId ) + 1; } ) );
objClone.find( '[id]' ).each( function() {
var strNewId = $( this ).attr( 'id' ).replace( /\d+$/, function( strId ) { return parseInt( strId ) + 1; } );
$( this ).attr( 'id', strNewId );
if( $( this ).attr( 'name' ) ) {
var strNewName = $( this ).attr( 'name' ).replace( /\[\d+\]/g, function( strName ) {
strName = strName.replace( /[\[\]']+/g, '' );
var intNumber = parseInt( strName ) + 1;
return '[' + intNumber + ']'
} );
$( this ).attr( 'name', strNewName );
}
});
return objClone;
}
$('#cloneDiv').click(function(){
// get the last DIV which ID starts with ^= "klon"
var $div = $('div[id^="klon"]:last');
// Read the Number from that DIV's ID (i.e: 3 from "klon3")
// And increment that number by 1
var num = parseInt( $div.prop("id").match(/\d+/g), 10 ) +1;
// Clone it and assign the new ID (i.e: from num 4 to ID "klon4")
var $klon = $div.clone().prop('id', 'klon'+num );
// Finally insert $klon wherever you want
$div.after( $klon.text('klon'+num) );
});
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>

Mootools Javascript can't push to array

I have an array set with the heights of each hidden div, but when I use it, the div instantly jumps down, rather than slowly sliding as when there is a literal number.
EDIT: testing seems to reveal that it's a problem with the push method, as content_height.push(item.getElement('.moreInfo').offsetHeight);alert(content_height[i]);gives undefined, but alert(item.getElement('.moreInfo').offsetHeight); gives the correct values
Javascript:
window.addEvent('domready', function(){
var content_height = [];i=0;
$$( '.bio_accordion' ).each(function(item){
i++;
content_height.push( item.getElement('.moreInfo').offsetHeight);
var thisSlider = new Fx.Slide( item.getElement( '.moreInfo' ), { mode: 'horizontal' } );
thisSlider.hide();
item.getElement('.moreInfo').set('tween').tween('height', '0px');
var morph = new Fx.Morph(item.getElement( '.divToggle' ));
var selected = 0;
item.getElement( '.divToggle' ).addEvents({
'mouseenter': function(){
if(!selected) this.morph('.div_highlight');
},
'mouseleave': function(){
if(!selected) {
this.morph('.divToggle');
}
},
'click': function(){
if (!selected){
if (this.getElement('.symbol').innerHTML == '+')
this.getElement('.symbol').innerHTML = '-';
else
this.getElement('.symbol').innerHTML = '+';
item.getElement('.moreInfo').set('tween', {
duration: 1500,
transition: Fx.Transitions.Bounce.easeOut
}).tween('height', content_height[i]); //replacing this with '650' keeps it smooth
selected = 1;
thisSlider.slideIn();
}
else{
if (this.getElement('.symbol').innerHTML == '+')
this.getElement('.symbol').innerHTML = '-';
else
this.getElement('.symbol').innerHTML = '+';
thisSlider.slideOut();
item.getElement('.moreInfo').set('tween', {
duration: 1000,
transition: Fx.Transitions.Bounce.easeOut
}).tween('height', '0px');
selected = 0;
}
}
});
} );
});
Why could this be? Thanks so much!
There's nothing wrong with your code. The push method works as expected - here's an example: http://jsfiddle.net/oskar/D2xps/
You need content_height[i - 1].
Also I'd recomend you use another indexing (since your code using global variable 'i' and it could fail because of closures):
$$( '.bio_accordion' ).each(function(item, index) {
content_height[index] = item.getElement('.moreInfo').offsetHeight;
....
tween('height', content_height[index]);
});

Categories