jQuery setInterval to continuously update data attribute - javascript

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())) )

Related

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

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");
});

Javascript count up onload load function

I am creating a script which will refresh "viewers" count displayed at the top of my website.
Javascript:
<script type="text/javascript">
window.onload = function(){
var auto_refresh = setInterval(
function ()
{
$('#viewers').load('viewers.php');
}, 5000);
}
</script>
HTML:
<span id="viewers">0</span>
viewers.php output:
100
I'd like to add a "count up/down" effect, so for example if the viewers.php outputs 200, it will then count up after the 5000 milliseconds, and if this count dropped to 50, the 100 will count down to 50.
Thanks for the help!
Here is a solution that counts up or down to the new number of viewers over a given delay period. It seems to run a little slow, probably due to the delay of my code inside the setInterval.
Just call the setViewers whenever you want to update the count.
<script type="text/javascript">
window.onload = function(){
var delay = 4000;
var viewers = $("#viewers");
var auto_refresh = setInterval(
function ()
{
var curViewers = Number(viewers.html())
$('#viewers').load('viewers.php', function(){
var newViewers = Number(viewers.html());
setViewers(curViewers, newViewers);
});
}, 5000);
function setViewers(currentNum, newNum){
if(currentNum == newNum) return;
var updateSpeed = delay / Math.abs(currentNum - newNum);
var countDir = currentNum > newNum ? -1 : 1;
var timer = setInterval(function(){
currentNum += countDir;
viewers.text(currentNum);
if(currentNum == newNum) clearInterval(timer);
}, updateSpeed);
}
}
</script>

Add Class to div when click counter reaches 0

Right now when you click inside the div, the counter decreases by 1. How do I make it stop at 0?
Also when it reaches 0 how can I add a class?
I want the overlay to be enabled once the click counter reaches 0.
If there is a better way to disable the div box1 after the clicks reach 0. We can try it that way.
$( function() {
$('.box').click( function() {
var num = $(this).find('.num');
num.text( parseInt(num.text()) - 1 );
});
});
fiddle
Rather than searching DOM and parsing HTML on each click, I'd cache both element and its value:
var $box = $('#box1'),
$num = $box.find('.num'),
limit = $num.text();
$box.click(function() {
$num.text(--limit);
if (limit === 0) {
$('.overlay').show();
}
});
Demo.
This should do it:
$('.box').click( function() {
var num = $(this).find('.num');
val = parseInt(num.text()) - 1;
if (val > 0){
num.text(val - 1);
} else {
$(".overlay").show();
// add your class here.
}
num.text( val );
});
Updated Fiddle

Improve script of setting height of div by comparing two heights

I wrote a small script that compares the height of 2 divs and setting the height of the largest to another div.
My question is: how to improve this script?. Because I'm currently repeating the part of getting the hides of the 2 div's
$( document ).ready(function() {
showHeight($( "#tab-content2" ).height());
showHeight($( "#tab-content1" ).height());
});
var bheight = 0;
function showHeight(height) {
if( height > bheight){
bheight = height;
$("aside").height(bheight + 60);
}
}
Select both of of them by selecting all IDs that start with tab-content and then loop over them with .each
$(document).ready(function() {
$("div[id^='tab-content']").each(function(){
showHeight($(this).height());
});
});
i guess kind of this:
$( document ).ready(function() {
showHeight("[id^='tab']"); // pass the selector
});
function showHeight(elem) {
var heights = $(elem).map(function (){
return $(this).height();
}).get(), // loops through the selectors and gets the height in array
maxHeight = Math.max.apply(null, heights); // returns the max height value.
$("aside").height(maxHeight + 60); // and set it here.
}
Add some class to your tabs.
$(document).ready(function () {
var bheight = 0;
$('.tabClass').each(function () {
bheaight = Math.max(bheight, $(this).height());
});
$('aside').height(bheight + 60);
});

How to stop my javascript countdown?

How can I stop my javascript function when countdown = 0?
JS:
var settimmer = 0;
$(function(){
window.setInterval(function() {
var timeCounter = $("b[id=show-time]").html();
var updateTime = eval(timeCounter)- eval(1);
$("b[id=show-time]").html(updateTime);
}, 1000);
});
HTML:
<b id="show-time">20</b>
For one thing remove those evals. They don't do anything.
Then all you have to do is clear the timer when it reaches zero.
$(function(){
var timer = setInterval(function() {
var timeCounter = parseInt($("b[id=show-time]").text());
$("b[id=show-time]").text(--timeCounter); // remove one
if(!timeCounter) clearInterval(timer);
}, 1000);
});
It is easy! When you call setInterval it return an ID, so you can destroy the interval later. To destroy it you must use clearInterval(id), and voilà!
It works like this:
// Activate timer
var iv = window.setInterval(...);
// Deactive timer
window.clearInterval(iv);
Also you should use parseInt() instead of eval():
$(function() {
// Read the start value once and store it in a variable
var timeCounter = parseInt( $("b[id=show-time]").text() );
// Active the counter
var iv = window.setInterval(function() {
// Decrement by one and write back into the document
$("b[id=show-time]").text(--timeCounter);
// Check if counter == 0 -> stop counting
if (0 == timeCounter) {
window.clearInterval(iv);
// ...do whatever else needs to be done when counter == 0 ..
}
}, 1000);
});
Example:
var i = 0,
pid = setInterval(function() {
if (++i > 10)
clearInterval(pid);
}, 1000);
Based on what you wanted for your code ...
$(function() {
var el = document.getElementById('show-time'),
pid = setInterval(function() {
// (s - i) coerces s to Number
var t = el.innerHTML - 1;
el.innerHTML = t;
if (t < 1)
clearInterval(pid);
}, 1000);
});
Keep in mind that JS won't be 100% accurate with its timing.
Pasted code below or see the fiddle: http://jsfiddle.net/raHrm/
<script type="text/javascript">
$(function(){
var settimmer = 0,
timeCounter = $("#show-time").html(),
updateTime = timeCounter;
(function countDown() {
timeCounter = $("#show-time").html();
updateTime = parseInt(timeCounter)-1;
$("#show-time").html(updateTime);
if ( updateTime ) {
setTimeout(countDown, 1000);
}
})();
});​
</script>
Set the timer to a variable, then use clearInterval in-order to stop the loop. As for catching the end, use a simple conditional:
$(function(){
var elem=$('strong[id="show-time"]'),settimmer=0,updateTime,t;
t=window.setInterval(function() {
updateTime=parseFloat(elem.html(),10)-1;
if(updateTime==0) {
window.clearInterval(t);
elem.html('Done!');
} else {
elem.html(updateTime);
}
},1000);
});
Then in the HTML:
<strong id="show-time">20</strong>
The <b> tag is depreciated, try to avoid using it. Also, there is no reason to eval() the HTML you are getting from the element; a simple parseFloat() works just fine.

Categories