loop throught classes in javascript - javascript

I am trying to make progress bars using JS.
I am trying to loop through my classes to get the value of an attribute and thus increase the width of my progress bars.
function prog(){
var width = 1;
var elem = document.getElementsByClassName('bar');
var id = setInterval(frame, 10);
var attr = elem.getAttribute("data-progress");
function frame(){
if(width >= attr){
clearInterval(id);
} else {
width++;
for(i= 0; i < elem.length; i++){
elem[i].style.width = width + '%';
}
}
}
}
My question is, How do i access attr inside a loop in JS?

You can use a simple for ... of loop to go through all your elements :
function prog() {
let elem = document.getElementsByClassName('bar');
let width = 1;
for (let el of elem) { //HERE
let attr = el.getAttribute("data-progress");
let id = setInterval(_ => {
if (width >= attr) {
clearInterval(id);
} else {
width++;
for (i = 0; i < elem.length; i++) {
elem[i].style.width = width + '%';
}
}
}, 10);
}
}

Related

I want to start JS function when I scroll

I have a one-page website with a section for a progress bar. I have a function for animation and all that, and I know how to start it when the page loads. But I don't know how to start it when I scroll to that section.
JS code :
window.onload = function() {
move();
};
var i = 0;
function move() {
if (i == 0) {
i = 1;
var elem = document.getElementById("myBar");
var width = 1;
var id = setInterval(frame, 10);
function frame() {
if (width >= 95) {
clearInterval(id);
i = 0;
} else {
width++;
elem.style.width = width + "%";
}
}
}
}
If you want to trigger on scroll, you could do that through jquery.
$(element).scroll(() ={
function ()
}
But if you want to animate on scroll, I'd advise you to use a library called Gsap. Look in the scrollTrogger document.
Simply use the scroll event on the whole document:
document.addEventListener('scroll', function(e) {
move();
});
var i = 0;
function move() {
if (i == 0) {
i = 1;
var elem = document.getElementById("myBar");
var width = 1;
var id = setInterval(frame, 10);
function frame() {
if (width >= 95) {
clearInterval(id);
i = 0;
} else {
width++;
elem.style.width = width + "%";
}
}
}
}
<div style="height:1000px;width:100%;">
<div style="height:200px">padding</div>
<div id="myBar" style="background:green;">my bar</div>
</div>

Adding a image to an element

I'm making a element that is randomly appearing on the screen using javascript. What would I do in order to add an image using javascript to the randomly generated element?
function addEnemy() {
var interval = 0.1;
if (iterations > 1500) {
interval = 5;
} else if (iterations > 1000) {
interval = 3;
} else if (iterations > 500) {
interval = 1;
}
if (getRandom(50) == 0) {
var elementName = "enemy" + getRandom(10000000);
var enemy = createSprite(elementName, getRandom(450), -40, 45, 45);
var enemiesDiv = document.getElementById("enemiesDiv");
var element = document.createElement("div");
element.id = enemy.element;
element.className = "enemy";
enemiesDiv.appendChild(element);
enemies[enemies.length] = enemy;
element.enemy.innerHTML
}
}
You can create a new img element, give it the source to your image, then append that img element to your element you created. (I would suggest using a more descriptive variable name than just "element")
The relevant code could look like this:
var myImage = document.createElement('img');
myImage.src = 'my_image.jpg';
element.appendChild(myImage);
A little bit too broad, but I think you could consider using the background property of your created div. Something like this:
function addEnemy() {
var interval = 0.1;
if (iterations > 1500) {
interval = 5;
} else if (iterations > 1000) {
interval = 3;
} else if (iterations > 500) {
interval = 1;
}
if (getRandom(50) == 0) {
var elementName = "enemy" + getRandom(10000000);
var enemy = createSprite(elementName, getRandom(450), -40, 45, 45);
var enemiesDiv = document.getElementById("enemiesDiv");
var element = document.createElement("div");
element.id = enemy.element;
element.className = "enemy";
// Here
element.style.backgroundImage = "url('img_enemy.png')";
enemiesDiv.appendChild(element);
enemies[enemies.length] = enemy;
element.enemy.innerHTML
}
}

JS does not read first ID only second

Ok I have some JS that depending on the percentage the progress bar will load and display the % inside the bar.
see working code bellow
$("#next-button").click(function() {
a.eventHub.publish("ui/nextclick")
});
UI.prototype.updatePercentile = function(a) {
if (this.isStandalone || -1 == a.percentile) $("#results-percentages")
.hide();
else {
$("#results-percentages")
.show(), $("#results-percentile-1")
.html(a.percentile), $("#results-suffix")
.html(a.suffix), $("#results-suffix-2")
.html(a.suffix), 1 === a.timesTaken ? ($("#results-timestaken")
.html(a.timesTaken + " time"), $("#results-percentile-2")
.html("100")) : ($("#results-timestaken")
.html(a.timesTaken + " times"), $("#results-percentile-2")
.html(a.percentile));
var b = 0;
$("#percentile-scale .scale-item")
.each(function() {
b += $(this)
.outerWidth()
}), $("#percentile-scale .scale-indicator").css("width", b * a.percentile / 100 + "%"),
$(".scale-marker").css("left", b * a.percentile / 100 + "%")
}
}
function move() {
var elem = document.getElementById("myBar");
var width = 0;
var id = setInterval(frame, 50);
function frame() {
if (width >= document.getElementById("results-percentile-2").innerHTML) {
clearInterval(id);
} else {
width++;
elem.style.width = width + '%';
document.getElementById("demo").innerHTML = width * 1 + '%';
}
}
}
however now i want to pull in a ne ID to add along side the percentage do it will display like 10th or 3rd depending on the score, however when i alter my JS to include the other ID (See bellow) it just shows the th, rd or st no the number.
HTML
<h3 style="text-align: left;"> You scored in the <em class="big-six"><span id="results-percentile-1"></span><span id="results-suffix-2"></span></em> percentile.
</h3>
<div class="myProgress">
<div id="myBar" style="width:0">
<div id="demo"><span id="results-suffix"></span></div>
<!--<div id="demo"></div>-->
</div>
JS
(function() {
var elem = document.getElementById("myBar");
var width = 0;
var id = setInterval(frame, 50);
function frame() {
if (width >= Number(document.getElementById("results-percentile-2").innerHTML)) {
clearInterval(id);
} else {
width++;
elem.style.width = width + '%';
document.getElementById("demo").innerHTML = width * 1 + document.getElementById("results-suffix").innerHTML ;
}
}
}());
IDs MUST be unique. If you need multiple elements with the same identifier, use a class.
For example:
<div id="myBar" style="width:0">
<div class="demo"><span class="results-suffix"></span></div>
<div class="demo"></div>
</div>
And your javascript would change to:
function frame() {
if (width >= Number(document.getElementById("results-percentile-2").innerHTML)) {
clearInterval(id);
} else {
width++;
elem.style.width = width + '%';
var demoElems = document.getElementsByClassName('demo');
var i, innerHTML, resultsElems;
// loop through the list of elements
for(i = 0; i < demoElems.length; i++) {
resultsElems = demoElems[i].getElementsByClassName('results-suffix')
innerHTML = width * 1;
// only append the results-suffix element if it exists
if(resultsElems.length > 0) {
innerHTML += resultsElems[0].innerHTML;
}
demoElems[i].innerHTML = innerHTML;
}
}
}

I want to show a image moving from right top corner to left bottom corner in simple html

onmouseover() I am calling this function
function move_arrow() {
document.getElementById('arrow1').style.display = "block";
j = 100;
for (var i = 1000; i > 260; i--) {
document.getElementById('arrow1').style.left = i + 'px';
document.getElementById('arrow1').style.top = j + 'px';
if (j < 440) {
j = j + .5;
}
//alert();
}
}
With alert its shows image moving to desired position otherwise its not. I know with alert it gets sufficient time to execute the function.
What can be the right solution for this in simple html and javascript which works in all browsers.
You may use setInterval for example:
function move_arrow() {
document.getElementById('arrow1').style.display = "block";
j = 100;
i = 1000;
var intervalId = setInterval(
function() {
i--;
document.getElementById('arrow1').style.left = i + 'px';
document.getElementById('arrow1').style.top = j + 'px';
if (j < 440) {
j = j + .5;
}
if (i < 240)
clearInterval(intervalId); //switch off setInterval
},
10 //execute this function every 10ms
);
}

Fit text width to div width

SetBoxText = function(Box, Text) {
if(! Website.Connected) {
return false;
}
if(Box == null || ! Box.Created) {
return false;
}
if(Box.Text == Text) {
return false;
}
Box.Text = Text;
UpdateBox(Box);
// To avoid constant updating.
for(var LetterPos = 0; LetterPos < Box.Letter.length; LetterPos++) {
Box.Element.removeChild(Box.Letter[LetterPos].Element);
}
Box.Letter = [];
var
Letter = " ",
Element = null,
FontSize = 0
;
for(var LetterPos = 0; LetterPos < Box.Text.length; LetterPos++) {
Letter = Box.Text[LetterPos];
Element = document.createElement("font");
Box.Element.appendChild(Element);
Box.Letter[LetterPos] = {};
Box.Letter[LetterPos].Letter = Letter;
Box.Letter[LetterPos].Element = Element;
Box.Letter[LetterPos].Element.style.fontFamily = Box.Font;
Box.Letter[LetterPos].Element.style.textAlign = "center";
Box.Letter[LetterPos].Element.innerHTML = Box.Letter[LetterPos].Letter;
FontSize = 1;
Box.Letter[LetterPos].Element.style.fontSize = FontSize + "px";
while(Box.Letter[LetterPos].Element.offsetWidth < (Box.Element.offsetWidth / Box.Text.length)) {
FontSize++;
Box.Letter[LetterPos].Element.style.fontSize = FontSize + "px";
}
while(Box.Letter[LetterPos].Element.offsetWidth > (Box.Element.offsetWidth / Box.Text.length)) {
FontSize--;
Box.Letter[LetterPos].Element.style.fontSize = FontSize + "px";
}
Box.Letter[LetterPos].Element.style.width = Box.Letter[LetterPos].Element.offsetWidth + "px";
Box.Letter[LetterPos].Element.style.height = Box.Letter[LetterPos].Element.offsetHeight + "px";
}
return true;
}
I have this function ^ up there.
What it's supposed to do is create a font tag for every letter in the Text region.
While it does that, it's supposed to fit itself into it's parent's width Box.Element.
What's happening is my browser freezes if I try to run this function.
When I comment out the while statements, this runs but I'm stuck with 1px size font.
I don't want to use jQuery.
Please help me =]
Edit:
I've also noticed if I switch the tags from font to div, it will make it, but only vertically, and when I do Element.style.display = "inline-block"; to the div it will do the same as the font.
Edit2: I changed the while loops to a for loop:
for(var FontSize = 1; FontSize < 100; FontSize++) {
if(Box.Letter[LetterPos].Element.offsetWidth < (Box.Element.offsetWidth / Box.Text.length)) {
Box.Letter[LetterPos].Element.style.fontSize = FontSize + "px";
}
}
This runs but some of the letters too big and some too small.
i hope this helps, considering that your browser is hanging, i did a small test with a for loop nesting a while loop, my browser hanged, too..
i hope this could be the solution to your problem, using the keyword break.
while(Box.Letter[LetterPos].Element.offsetWidth < (Box.Element.offsetWidth / Box.Text.length)) {
FontSize++;
Box.Letter[LetterPos].Element.style.fontSize = FontSize + "px";
break; // break out of loop when condition is met
}
while(Box.Letter[LetterPos].Element.offsetWidth > (Box.Element.offsetWidth / Box.Text.length)) {
FontSize--;
Box.Letter[LetterPos].Element.style.fontSize = FontSize + "px";
break;
}

Categories

Resources