scope in angular and applied css class only on first div - javascript

I'm calling js function every 2 seconds where on certain condition I want to update div on the view.
<div id="ball_{{ballIndex}}">{{ball}}</div>
on ng controller
var myCounter = 0;
var interval = $interval(function () {
if (myCounter <= 35) {
myCounter ++;
DoSomething();
} else {
//
}
}, 1500);
function setCurrentBallEffect() {
$('#ball_' + myCounter).addClass('magictime puffIn');
}
function DoSomething() {
if (myCounter == 0) {
$scope.ballIndex = 1;
} else {
$scope.ballIndex = myCounter;
}
}
using this code only first div in iteration is applied with class magictime puffIn. When I hardcode div id's on the view side like <div id="ball_1">1</div> <div id="ball_2">2</div> .. applied css class work on each div. What I'm doing wrong?
Update:
Tried with
<div ng-attr-id="{{ 'ball_' + ballIndex }}"> </div>
but problem is still present.

At first you must define
var myCounter =0;
I don't understand ball
you must defined it like this :
$scope.ball=0;
I Change view like this
<div id="ball_{{ballIndex}}">{{ballIndex}}</div>
and your javascript changed like this:
var poolCounter = 0;
var myCounter = 0;
var interval = $interval(function () {
if (myCounter <= 35) {
myCounter++;
DoSomething();
} else {
//
}
}, 1500);
function setCurrentBallEffect() {
$('#ball_' + myCounter).addClass('magictime puffIn');
}
function DoSomething() {
if (myCounter == 0) {
$scope.ballIndex = 1;
} else {
$scope.ballIndex = myCounter;
}
}

Related

Recursion with arguments method

The script must have to print 'Hello', then 'Good bye', because of the entries on function call. But only prints once. Why?
What's wrong here bellow.
PD: Now it doesn't work. It does if i comment the recursion call line
<html>
<head>
</head>
<body>
<script type="text/javascript">
function writing(i,first,second) {
len=arguments.length;
if (i<=len) {
current=arguments[i];
c=0;
inter=setInterval(function() {
if (c>=current.length) {
clearInterval(inter);
} else {
field=document.getElementById('div1');
field.innerHTML+=current[c];
c+=1;
}
},200);
}
i<len?writing(i+1,first,second):writing(i=0,first,second);
}
writing(1,'Hello','Good bye');
</script>
<div id="div1"></div>
</body>
There are so many problems with the code , first was it was infinite loop (never ending) , second was variable declaration , and others...
Here I have attached the snippet , please run and check, if its that you are looking for.
I have to add setTimeout for fullfill your requirement.
var interval_counter = 0;
function writing(i, first, second) {
var len = arguments.length;
if (i != 0 && i <= len) {
var current = arguments[i];
var c = 0;
setTimeout(function() {
var inter = setInterval(function() {
if (c >= current.length) {
clearInterval(inter);
} else {
field = document.getElementById('div1');
field.innerHTML += current[c];
c += 1;
}
}, 200);
}, 200 * interval_counter);
interval_counter = interval_counter + current.length;
i < (len - 1) ? writing(i + 1, first, second) : writing(i = 0, first, second);
} else {
return false;
}
}
writing(1, 'Hello', 'Good bye');
<div id="div1"></div>

java script Foreach loop

Javascript
function myFunction() {
for (i = 0; i < 5000;) {
setTimeout(function() {
document.getElementById("demo").innerHTML = i;
}, i);
i += 500;
}
}
HTML
<body onload="myFunction()">
<div id="demo"></div>
How to increase " i " every 5ms and print it in #demo every time it changes
I am trying to make a look that increases the value of ( i ) once every 5ms, and prints it out in # demo.
Right now, the value 5000 immediately prints out as soon as I run the script for some reason, as opposed to increasing by 500 every time.
Thanks in advance.
You can change myFunction to:
var i = 0;
function myFunction() {
var timerId = setInterval(function(){
if(i >= 5000)
{
clearInterval(timerId);
}
document.getElementById("demo").innerHTML = i;
i +=500;
}, 5);
}
this should work.
var i=0;
function looper(){
setTimeout(function(){
console.log(i+" data");
i=i+500;
if(i<5000)
looper();
}, i);
}
looper();
function myFunction() {
var i = 0;
var max = 5000;
var step = 500;
var intervalMs = 5;
var interval = setInterval(function() {
// clear interval if one step before max value
if (i >= max-step) {
clearInterval(interval);
}
// increment i by step
i+=step;
// set inner html of div
document.getElementById("demo").innerHTML = i;
}, intervalMs)
}
Plunkr: https://plnkr.co/edit/IfkGOpjUnf4sKpN4iCZ4?p=preview
If you want your code to look similar to what you have, you can use an IIFE:
function myFunction() {
for (i = 0; i <= 5000;i += 500) {
(function(index) {
setTimeout(function() {
document.getElementById("demo").innerHTML = index;
}, index);
})(i);
}
}
<body onload="myFunction()">
<div id="demo"></div>
</body>
You are having an issue with the closure not saving a reference to your timeout. Subsequent arguments after the second are passed into the callback function as arguments.
Here we are passing i as the third argument
setTimeout(fn, delay, i)
Then in the callaback we have access to the i, we are reassigning it to x within the scope of the callback.
function myFunction() {
for (i = 0; i <= 5000; i = i + 500) {
setTimeout(function(x) {
document.getElementById("demo").innerHTML = x;
}, i, i);
}
}
myFunction()
<div id="demo"></div>
function myFunction(max, ii = 0) {
document.getElementById('demo').innerHTML = ii
if (ii < max) {
setTimeout(myFunction, 500, max, ii + 500)
}
}
myFunction(5000)
<div id="demo"></div>
**
<div id="demo"></div>
<script>
function myFunction() {
var i = 0;
var setClock = function() {
if (i < 5000) {
local = i;
i += 500;
setTimeout(function() {document.getElementById("demo").innerHTML = local; setTimeout(setClock, 500);},
500);
}
}
setClock();
}
**
you should wrap scripts in tags
the javascript Closures. You should know that because of the Closures, second parameters for all setTimeout() are 5000, which is the i's final value. You can avoid the Closure by the codes I showed or erase the impact of Closure by below codes:
<div id="demo"></div>
<script>
function myFunction() {
var local;
for (i = 0; i < 5000; i+= 500) {
local = i;
setTimeout((function(interval){
return function() {document.getElementById("demo").innerHTML = interval;} ;
})(local), (function(interval){return interval})(local));
}
}

How to select between a list css classes

I have a div with a next and previous button
<div class="b1"></div>
<input type="button" class="btnP" value="Prev"/>
<input type="button" class="btnN" value="Next"/>
and a list of css classes
.b1 { background-color:#fff;}
.b2 { background-color:#000;}
.b3 { background-color:#123;}
.b4 { background-color:#444;}
.b5 { background-color:#bbb;}
which i want to use for that div when the user press the next or previous button by that numbering order.
This is what i did so far:
http://jsfiddle.net/51dq5num/
var size_ini = 1;
$(".btnN").click(function () {
var size_increase = size_ini++;
var size_increase1 = size_ini;
$("#content").html("<span>" + size_increase + "</span>").removeClass().addClass("b" + size_increase);
if (size_increase > 4) {
size_ini = 1;
}
});
I manage to get the next button working but i'm not sure how to do it for the previous button
Is there a better way to do this rather then adding and removing css classes from the div?
Try this :
$(".btnP").click(function () {
var size_increase = $("#content").attr("class").substring(2, 1);
size_increase--;
if (size_increase < 1) {
size_increase = 5;
}
$("#content").html("<span>" + size_increase + "</span>").removeClass().addClass("b" + size_increase);
});
jsFiddle : http://jsfiddle.net/51dq5num/7/
You can do something like this:
var newClass = function(div, next) {
div[0].className = div[0].className.replace(/b\d+/, "b" + newClass[next ? 'next' : 'prev']());
};
newClass.atual = 1;
newClass.last = 5;
newClass.next = function(){
this.atual = (this.atual == this.last ? 1 : this.atual + 1);
return this.atual;
};
newClass.prev = function(){
this.atual = (this.atual == 1 ? this.last : this.atual - 1);
return this.atual;
};
var myDiv = $("#content");
$(".btnN").click(function () {
newClass(myDiv, true);
});
$(".btnP").click(function () {
newClass(myDiv, false);
});
Jsfiddle here.
This is a combined solution for both buttons.
var size_ini = 0;
$("input[type='button']").click(function () {
if($(this).hasClass("btnN"))
{
size_ini=size_ini+1;
var c="b"+size_ini;
$("#content").removeClass().addClass(c).html("TG"+size_ini);
}
else
{
size_ini=size_ini-1;
var c="b"+size_ini;
$("#content").removeClass().addClass(c).html("TG"+size_ini);
}
});
Note as it is not mentioned i have not checked on the max condition thus btnP can increase the counter infinitely.You can put it in a condn and limit it to a max value.
http://jsfiddle.net/n8dLgh3L/1/
Here is js code to increase and decrease.
var size_ini = 0;
$(".btnN").click(function () {
if (size_ini > 4) {
size_ini = 1;
} else {
size_ini++
}
$("#content").html("<span>" + size_ini + "</span>").removeClass().addClass("b" + size_ini);
});
$(".btnP").click(function () {
var size_decrease = $("#content").attr("class").substring(1, 2);
if (size_decrease <= 1) {
size_decrease = 5;
} else {
size_decrease--;
}
$("#content").html("<span>" + size_decrease + "</span>").removeClass().addClass("b" + size_decrease);
});
You ca achieve this with the help of .substr() for incrementing the number of class. Have a look.
function Getnumber(classNumber,nav)
{
var no=0;
if(nav=="P")
{
no=parseInt(classNumber.substr(1,2))-1;
}
else
{
no=parseInt(classNumber.substr(1,2))+1;
}
return no;
}
$(".btnN").on("click",function(){
var oldClass=$('div').attr("class");
var num=Getnumber(oldClass,"N");
if(num<6)
$('div').addClass("b"+num).removeClass(oldClass);
});
$(".btnP").on("click",function(){
var oldClass=$('div').attr("class");
var num=Getnumber(oldClass,"P");
if(num>0)
$('div').addClass("b"+num).removeClass(oldClass);
});
Feel free to ask.

get interval ID from else statement when set in IF

I am attempting to create a responsive slider, that will change to a simple set of dot points when in mobile mode (< 940).
The issue I am facing is in my else statement I am unable to clearintervals that were made in the if statement, because t comes up as undefined. I have resorted to using
for (var i = 1; i < 99999; i++) window.clearInterval(i); to clear the interval which works, but I don't like it because it's ugly and cumbersome, is there another way of accomplishing this?
$(document).ready(function() {
function rePosition() {
//get responsive width
var container_width = $('.container').width();
//Slider for desktops only
if(container_width >= 940) {
//get variables
var slide_width = $('.slider_container').width();
var number_of_slides = $('.slider_container .slide').length;
var slider_width = slide_width*number_of_slides;
//set element dimensions
$('.slide').width(slide_width);
$('.slider').width(slider_width);
var n = 1;
var t = 0;
$('.slider_container').hover(function() {
clearInterval(t);
}, function() {
t = setInterval(sliderLoop,6000);
});
var marginSize = i = 1;
//Called in Doc Load
function sliderLoop(trans_speed) {
if (trans_speed) {
var trans_speed = trans_speed;
}
else
{
var trans_speed = 3000;
}
if (i < number_of_slides) {
marginSize = -(slide_width * i++);
}
else
{
marginSize = i = 1;
}
$('.slider').animate({ marginLeft: marginSize }, trans_speed);
}
t = setInterval(sliderLoop,6000);
$('.items li').hover(function() {
$('.slider').stop();
clearInterval(t);
var item_numb = $(this).index();
i = item_numb;
sliderLoop(500);
}, function() {
t = setInterval(sliderLoop,6000);
});
}
else
{
for (var i = 1; i < 99999; i++)
window.clearInterval(i);
$('.slider').stop(true, true);
$('.slider').css('margin-left', '0px');
//rearrange content
if($('.slider .slide .slide_title').length < 1) {
$('.items ul li').each(function() {
var item_numb = $(this).index();
var content = $(this).text();
$('.slider .slide:eq(' + item_numb + ')').prepend('<div class="title slide_title">' + content + '</div>')
});
}
}
}
rePosition();
$(window).resize(function() {
rePosition();
});
});
Teemu's comment is correct. I'll expand on it. Make an array available to all of the relevant code (just remember that globals are bad).
$(document).ready(function() {
var myIntervalArray = [];
Now, whenever you create an interval you will need to reference later, do this:
var t = setInterval();//etc
myIntervalArray.push(t); //or just put the interval directly in.
Then to clear them, just loop the array and clear each interval.
for (var i=0; i<myIntervalArray.length; i++)
clearInterval(myIntervalArray[i]);
}
Umm, wouldn't t only be defined when the if part ran... as far as I can tell, this is going to run and be done... the scope will be destroyed. If you need to maintain the scope across calls, you'll need to move your var statements outside of reposition(), like so:
$(document).ready(function() {
var t = 0;
...
function rePosition() { ... }
});

need to reset the function how do i do it

I want to reset this flash in between so that i need not have to wait till the end to restart the flash, how do i reset this?
function flash() {
var arrayId = 0,
splitSet = $('#text_original').html().split(" "),
splitSetLength = splitSet.length;
function flashWord() {
$("#flash_word").html(splitSet[arrayId]);
arrayId += 1;
var t = setTimeout(remove, 1000);
}
function remove() {
if (arrayId < splitSetLength) {
$("#flash_word").html(" ");
flashWord();
} //else reset_flash();
}
flashWord(); }
please see the http://jsfiddle.net/HcDfS/
Make the timer variable a global one and cancel the time-out on it (with clearTimeout()). Then, hide #flash_word.
I took the liberty of re-implementing your fiddle:
var timer, words;
function startFlashing() {
words = $("#source").text().split(" ");
showNextWord(0);
}
function stopFlashing() {
clearTimeout(timer);
$("#banner").text("");
}
function showNextWord(index) {
$("#banner").text(words[index]);
index++;
if (index < words.length) timer = setTimeout(function () {
showNextWord(index);
}, 1000);
else $("#banner").text("");
}
​
With HTML:
<p id="source">This is the text to be flashed.</p>
<button onclick='startFlashing()'>Start Flashing!</button>
<button onclick='stopFlashing()'>Stop Flashing!</button>
<p id="banner"></p>​
And it's here: http://jsfiddle.net/CZnVc/6/

Categories

Resources