Updating interval dynamically - jQuery or Javascript - javascript

I have two "stopwatches" in my code (and I may be adding more). This is the code I currently use below - and it works fine. But I'd really like to put the bulk of that code into a function so I'm not repeating the same code over and over.
When I tried doing it though, I could get it working - I think it was because I was passing stopwatchTimerId and stopwatch2TimerId into the function and it may have been passing by reference?
How can I reduce the amount of code repetition here?
var stopwatchTimerId = 0;
var stopwatch2TimerId = 0;
$('#stopwatch').click(function () {
if ($(this).hasClass('active')) {
$(this).removeClass('active');
clearInterval(stopwatchTimerId);
}
else {
$(this).addClass('active');
stopwatchTimerId = setInterval(function () {
var currentValue = parseInt($('#stopwatch-seconds').val()) || 0;
$('#stopwatch-seconds').val(currentValue + 1).change();
}, 1000);
}
});
$('#stopwatch2').click(function () {
if ($(this).hasClass('active')) {
$(this).removeClass('active');
clearInterval(stopwatch2TimerId);
}
else {
$(this).addClass('active');
stopwatch2TimerId = setInterval(function () {
var currentValue = parseInt($('#stopwatch2-seconds').val()) || 0;
$('#stopwatch2-seconds').val(currentValue + 1).change();
}, 1000);
}
});
As you can see, it's basically the same code in each except for stopwatchTimerId and $('#stopwatch-seconds') (and the same vars with 2 on it for the other one).

This won't pollute global scope and also you don't need to do any if-else statements. Just add data-selector to your new elements :)
<input id="stopwatch" type="text" data-selector="#stopwatch-seconds"/>
<input id="stopwatch2" type"text" data-selector="#stopwatch2-seconds"/>
$('#stopwatch stopwatch2').click(function () {
var $element = $(this),
interval = $element.data('interval');
selector = $element.data('selector');;
if ($element.hasClass('active')) {
$element.removeClass('active');
if (interval) {
clearInterval(interval);
}
}
else {
$element.addClass('active');
$element.data('interval', setInterval(function () {
var currentValue = parseInt($(selector).val()) || 0;
$(selector).val(currentValue + 1).change();
}, 1000));
}
});

function stopwatch(id){
$('#' + id).click(function () {
if ($(this).hasClass('active')) {
$(this).removeClass('active');
clearInterval(window[id]);
}
else {
$(this).addClass('active');
window[id] = setInterval(function () {
var currentValue = parseInt($('#' + id + '-seconds').val()) || 0;
$('#' + id + '-seconds').val(currentValue + 1).change();
}, 1000);
}
});
}
$(function(){
stopwatch("stopwatch");
stopwatch("stopwatch2");
});

You could do something like this (code is not very nice, you can improve it):
var stopwatchTimerId;
$('#stopwatch').click(function () {
doStopWatch(1);
});
$('#stopwatch2').click(function () {
doStopWatch(2);
});
var doStopWatch = function(option){
var stopWatch = option===1?$('#stopwatch'):$('#stopwatch2');
if (stopWatch.hasClass('active')) {
stopWatch.removeClass('active');
clearInterval(stopwatchTimerId);
}
else {
stopWatch.addClass('active');
stopwatchTimerId = setInterval(function () {
var currentValue = option===1?(parseInt($('#stopwatch-seconds').val()) || 0):(parseInt($('#stopwatch2-seconds').val()) || 0);
if(option===1)
$('#stopwatch-seconds').val(currentValue + 1).change();
else
$('#stopwatch2-seconds').val(currentValue + 1).change();
}, 1000);
}
}

Try
var arr = $.map($("div[id^=stopwatch]"), function(el, index) {
el.onclick = watch;
return 0
});
function watch(e) {
var id = this.id;
var n = Number(id.split(/-/)[1]);
if ($(this).hasClass("active")) {
$(this).removeClass("active");
clearInterval(arr[n]);
} else {
$(this).addClass("active");
arr[n] = setInterval(function() {
var currentValue = parseInt($("#" + id + "-seconds").val()) || 0;
$("#" + id + "-seconds").val(currentValue + 1).change();
}, 1000);
}
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div id="stopwatch-0">stopwatch1</div>
<input type="text" id="stopwatch-0-seconds" />
<div id="stopwatch-1">stopwatch2</div>
<input type="text" id="stopwatch-1-seconds" />

Related

How to do this in jQuery?

I want to transform this code from JavaScript into jQuery.
This is the current code:
var i = 0;
var start = true;
document.getElementById("startclick").addEventListener("click", function() {
if (start) {
start = false;
interval = setInterval(function() {
i++;
document.getElementById('list').innerHTML += "albastru_" + i + '<br>' ;
}, 3000);
} else {
start = true;
clearInterval(interval);
}
});
Here is my attempt:
$x = 0;
$start = true;
$(document).ready(function () {
$('#buton2').on('click',function () {
if($start){
$start = false;
$interval = setInterval(function () {
$x ++;
$('#list').html('<p>albastru_</p>' + $x + '<br>'); }, 1000);
} else {
$start = true;
clearInterval($interval);
}
})
});
You can do something like below. I'm assuming startclick is a button, after you click it .append() will add the required data to #list div after 3 seconds.
Updated Answer with start and stop buttons.
var i = 0;
var start = true;
var interval = null;
$('#startclick').click(function() {
if (interval !== null) return;
interval = setInterval(function() {
i++;
$('#list').append("albastru_" + i + '<br>');
}, 3000);
});
$("#stop").click(function() {
clearInterval(interval);
interval = null;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="list">
</div>
<br />
<button id="startclick">START!</button>
<button id="stop">STOP!</button>

How to run a function in jQuery for 15 times

I have a jQuery function
setInterval(function () {
secondPlay()
}, 1000);
setInterval(function () {
secondPlay1()
}, 1000);
function secondPlay() {
$("body").removeClass("play");
var aa = $("ul.secondPlay li.active");
var ii = $('ul.secondPlay li:last-child').val();
if (aa.html() == undefined) {
aa = $("ul.secondPlay li").eq(0);
aa.addClass("before")
.removeClass("active")
.next("li")
.addClass("active")
.closest("body")
.addClass("play");
}
if (aa.is(":last-child")) {
$("ul.secondPlay li").removeClass("before");
aa.addClass("before").removeClass("active");
aa = $("ul.secondPlay li").eq(0);
aa.addClass("active")
.closest("body")
.addClass("play");
}
else {
$("ul.secondPlay li").removeClass("before");
aa.addClass("before")
.removeClass("active")
.next("li")
.addClass("active")
.closest("body")
.addClass("play");
}
}
I want to run this function for 15 times. How can I run it ?
Declare a variable as a counter. Increment that variable eachtime you calling the function. If the variable reaches 15, the stop the setInterval() by using clearInterval() function
var counter = 1;
var interval = setInterval(function () {
if (counter == 15) {
clearInterval(interval);
}
secondPlay()
counter++;
}, 1000);
You can use following code as reference.
(function(){
var count = 0;
var interval = setInterval(function(){
if(count>15){
window.crearInterval(interval);
}
else{
document.getElementById("lblCount").innerHTML = count;
count++;
}
},1000);
})()
<p id="lblCount"></p>
Try This
var timePlyed = 0;
function secondPlay() {
timePlyed++;
console.log(timePlyed);
if (timePlyed != 15) {
secondPlay();
}
}
secondPlay();
Enclose them in a for loop?
for (i = 0; i < 15; i++) {
...
}
you can use timeout function:
function secondPlay(i){
console.log(i);
}
function test(){
for(var i = 0; i < 15; i++){
setTimeout(function(){
secondPlay(i);
}, i * 1000);
}
}
call test() to execute the function.
Instead of setInterval, you could use a timeout:
var i = 0;
function secondPlay1() {
// do function
setTimeout(function() {
if (i < 15) {
i++;
secondPlay1();
}
}, 1000);
}

Writing Text Effect with jquery

I am use this code for Writing Text Effect:
<script type="text/javascript">
$(document).ready(function () {
function changeText(cont1, cont2, speed) {
var Otext = cont1.text();
var Ocontent = Otext.split("");
var i = 0;
function show() {
if (i < Ocontent.length) {
cont2.append(Ocontent[i]);
i = i + 1;
};
};
var Otimer = setInterval(show, speed);
};
$(document).ready(function () {
changeText($("#TypeEffect p"), $(".p2"), 150);
});
});
</script>
but its not working for multiline, I use this code:
changeText($("#TypeEffect p, #TypeEffect br"), $(".p2"), 150);
so, its not working.
please help me for Writing Text Effect in multi line.
Try
$(document).ready(function () {
function changeText(cont1, cont2, speed) {
var contents = $(cont1).contents().map(function () {
if (this.nodeType == 3) {
if ($.trim(this.nodeValue).length) {
return this.nodeValue.split("")
}
} else {
return $(this).clone().get();
}
}).get();
var i = 0;
function show() {
if (i < contents.length) {
cont2.append(contents[i]);
i = i + 1;
} else {
clearInterval(Otimer)
}
};
var Otimer = setInterval(show, speed);
};
$(document).ready(function () {
changeText($("#TypeEffect p"), $(".p2"), 150);
});
});
Demo: Fiddle
Try this:
$("[class*=autoWrite]").each(function(e){
autoWriteText($(this));
})
function autoWriteText(elm){
var clas = elm.attr("class");
clas = clas.split("-");
var speed = clas[1];
var delay = clas[2];
var txt = elm.html();
elm.html("");
setTimeout(function(){
elm.fadeIn("fast");
txt = txt.split("");
var txtI = 0;
var html = "";
var intrvl = setInterval(function(){
html = html + txt[txtI] ;
elm.html(html + "_");
txtI = txtI + 1;
if(txtI == txt.length){
clearInterval(intrvl);
}
},speed);
},delay)
}
.autoWriteText{
display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<h5 class="autoWrite-10-0" >This element will write a <b>letter every 10 milliseconds</b> in this box, with a <b>delay of 0 milliseconds</b>.</h5>
<hr>
<h5 class="autoWrite-50-1000" >This element will write a <b>letter every 50 milliseconds</b> in this box, with a <b>delay of 1 second</b>.</h5>
<hr>
<h5 class="autoWrite-200-3000" >This element will write a <b>letter every 200 milliseconds</b> in this box, with a <b>delay of 3 second</b>.</h5>
<hr>
<h5 class="autoWrite-500-5000" >This element will write a <b>letter every 500 milliseconds</b> in this box, with a <b>delay of 5 second</b>.</h5>
<hr>

Js and Divs, (even <div> is difference)

I Have find a javascript code that works perfectly for showing a DIV.
but this code works only for showing one div for each page.
i want to include many DIVS for hiding and showing in the same page.
I was try to replace the div id and show/hide span id with a rundom php number for each include, but still is not working.
so how i have to do it?
the JS code:
var done = true,
fading_div = document.getElementById('fading_div'),
fade_in_button = document.getElementById('fade_in'),
fade_out_button = document.getElementById('fade_out');
function function_opacity(opacity_value) {
fading_div.style.opacity = opacity_value / 100;
fading_div.style.filter = 'alpha(opacity=' + opacity_value + ')';
}
function function_fade_out(opacity_value) {
function_opacity(opacity_value);
if (opacity_value == 1) {
fading_div.style.display = 'none';
done = true;
}
}
function function_fade_in(opacity_value) {
function_opacity(opacity_value);
if (opacity_value == 1) {
fading_div.style.display = 'block';
}
if (opacity_value == 100) {
done = true;
}
}
// fade in button
fade_in_button.onclick = function () {
if (done && fading_div.style.opacity !== '1') {
done = false;
for (var i = 1; i <= 100; i++) {
setTimeout((function (x) {
return function () {
function_fade_in(x)
};
})(i), i * 10);
}
}
};
// fade out button
fade_out_button.onclick = function () {
if (done && fading_div.style.opacity !== '0') {
done = false;
for (var i = 1; i <= 100; i++) {
setTimeout((function (x) {
return function () {
function_fade_out(x)
};
})(100 - i), i * 10);
}
}
};
Check out the Fiddle, you can edit code based on your needs ;)
$(function() {
$('.sub-nav li a').each(function() {
$(this).click(function() {
var category = $(this).data('cat');
$('.'+category).addClass('active').siblings('div').removeClass('active');
});
});
});
finaly i found my self:
<a class="showhide">AAA</a>
<div>show me / hide me</div>
<a class="showhide">BBB</a>
<div>show me / hide me</div>
js
$('.showhide').click(function(e) {
$(this).next().slideToggle();
e.preventDefault(); // Stop navigation
});
$('div').hide();
Am just posting this in case someone was trying to answer.

jQuery / Javascript - loop

I want to make it so when I click somewhere in my website, the background changes. I have three backgrounds, and I want to make a loop of them.
$(document).ready(function() {
$('body').click((function(){
return function()
{
if (counter == null) {
var counter = 1;
}
if(counter == 3) {
$(this).css("background-image","url(3.jpg)");
$(this).css("background-position","10% 35%");
var counter = null;
}
if(counter == 2) {
$(this).css("background-image","url(2.jpg)");
$(this).css("background-position","10% 35%");
var counter = 3;
}
if(counter == 1) {
$(this).css("background-image","url(1.jpg)");
$(this).css("background-position","40% 35%");
var counter = 2;
}
}
})());
});
Why doesn't this work?
Your counter variable isn't scoped right, you need one counter variable. Overall though, why not let .toggle() manage this for you? Here's what it would look like:
$(function() {
$('body').toggle(function(){
$(this).css({"background-image":"url(1.jpg)", "background-position":"40% 35%"});
}, function() {
$(this).css({"background-image":"url(2.jpg)", "background-position":"10% 35%"});
}, function() {
$(this).css({"background-image":"url(3.jpg)", "background-position":"10% 35%"});
});
});
Although the name and common usages suggest that .toggle() only takes 2 functions, it actually takes 2 or more and will cycle through them.
this no longer refers to the body element, it refers to the anonymous function.
Does this code work?
var counter = 1;
$(document).ready(function() {
$('body').click(function() {
if (counter == null) {
counter = 1;
}
if (counter == 3) {
$(this).css("background-image", "url(3.jpg)");
$(this).css("background-position", "10% 35%");
counter = 1;
}
if (counter == 2) {
$(this).css("background-image", "url(2.jpg)");
$(this).css("background-position", "10% 35%");
counter = 3;
}
if (counter == 1) {
$(this).css("background-image", "url(1.jpg)");
$(this).css("background-position", "40% 35%");
counter = 2;
}
});
});
Your function uses this which is refering to itself, not the element. This would fix it:
$('body').click((function(){
var $this = $(this);
return ... {
$this // use $this instead of $(this)
Also, have a look on jQuery .toggle
Your counter declarations are strewn all over the place which makes it difficult to follow what's happening. Further, counter is declared local to the callback function, which means it loses its value every time the function executes.
Here's a simpler solution:
$(function() { // this is equivalent to $(document).ready(...)
var counter = 0;
var images = [
[ '1.jpg', '40% 35%' ],
[ '2.jpg', '10% 35%' ],
[ '3.jpg', '10% 35%' ]
];
$('body').click(function() {
$(this).css('background-image', 'url(' + images[counter][0] + ')');
$(this).css('background-position', images[counter][1]);
// increment counter, wrapping over to 0 when it reaches end of array
counter = (counter + 1) % images.length;
});
});
You can easily extend to this to any number of images by simply adding more entries to the images array.
$(document).ready(function () {
function changeBgImage() {
var imgs = [
["1.jpg", "10% 35%"],
["2.jpg", "10% 35%"],
["3.jpg", "40% 35%"]
];
var counter = 0;
return function() {
$(this).css({
"backgroundImage": "url(" + imgs[counter][0] + ")",
"backgroundPosition": imgs[counter][1]
});
counter += 1;
if (counter === imgs.length) { counter = 0; }
};
}
$('body').click(changeBgImage());
});
Update:
OK, so here we have another solution. It is basically Nick's answer but without redundancy.
$(function () {
var imgs = [["1.jpg", "10% 35%"], ["2.jpg", "10% 35%"], ["3.jpg", "40% 35%"]];
var i = 0;
$("body").click(function () {
$(this).css({"background-image": "url(" + imgs[i][0] + ")", "background-position": imgs[i][1]});
if (++i === imgs.length) { i = 0; }
});
});

Categories