I have two divs which numerically represent the width and height of the window's screen, counting from every 100th pixel. The numeric values are wrapped inside span tags and inserted into their respective div container through two loops. Since both of these loops share almost the same exact methods and conditional logic I was wondering if there was a way that I could combine them somehow:
HTML
<div class="rule rule--horizontal"></div>
<div class="rule rule--vertical"></div>
JS
document.addEventListener("DOMContentLoaded", function() {
var horizontal = document.getElementsByClassName("rule--horizontal")[0],
vertical = document.getElementsByClassName("rule--vertical")[0];
for (var i = 50, screenWidth = screen.width; i < screenWidth; i+= 50) {
if (i % 100 === 0) {
horizontal.innerHTML += "<span class='num num--visible'>" + i + "</span>";
}
}
for (var i = 50, screenHeight = screen.height; i < screenHeight; i+= 50) {
if (i % 100 === 0) {
vertical.innerHTML += "<span class='num num--visible'>" + i + "</span>";
}
}
});
JSFiddle
This produce the same result
document.addEventListener("DOMContentLoaded", function() {
var horizontal = document.getElementsByClassName("rule--horizontal")[0],
vertical = document.getElementsByClassName("rule--vertical")[0];
var a = screen.width > screen.height ? screen.width : screen.height;
for (var i = 50; i < a; i+= 50) {
if (i % 100 === 0) {
if(i < screen.width)horizontal.innerHTML += "<span class='num num--visible'>" + i + "</span>";
if(i < screen.height)vertical.innerHTML += "<span class='num num--visible'>" + i + "</span>";
}
}
});
You can create function and use it in two places:
document.addEventListener("DOMContentLoaded", function() {
var horizontal = document.getElementsByClassName("rule--horizontal")[0],
vertical = document.getElementsByClassName("rule--vertical")[0];
loop(horizontal, screen.width);
loop(vertical, screen.height);
});
function loop(element, max) {
for (var i = 50; i < max; i+= 50) {
if (i % 100 === 0) {
element.innerHTML += "<span class='num num--visible'>" + i + "</span>";
}
}
}
You can factor out the if statement if (i % 100 === 0) this is true on 100, 200, etc. Just start i at 100 and increment by 100
document.addEventListener("DOMContentLoaded", function() {
var horizontal = document.getElementsByClassName("rule--horizontal")[0],
vertical = document.getElementsByClassName("rule--vertical")[0];
var createDivs = function (axis, maxSize) {
for (var i = 100; i < maxSize; i += 100) {
axis.innerHTML += "<span class='num num--visible'>" + i + "</span>";
}
};
createDivs(horizontal, screen.width);
createDivs(vertical, screen.height);
});
Related
<script>
var animate = function (element, target, callback) {
clearInterval(element.timer);
element.timer = setInterval(function () {
var step = (target - element.offsetLeft) / 10;
step = step > 0 ? Math.ceil(step) : Math.floor(step);
element.style.left = element.offsetLeft + step + 'px';
// console.log(element.offsetLeft);
if (element.offsetLeft == target) {
clearInterval(element.timer);
callback && callback();
}
}, 20)
};
window.addEventListener('load', function () {
var ul = document.querySelector('.local-nav');
console.log(ul);
for (var i = 0; i < ul.children.length; i++) {
ul.children[i].children[0].children[0].style.backgroundPosition = '0 ' + -i * 32 + 'px';
}
var ul2 = document.querySelector('.subnav-entry ul');
console.log(ul2);
for (var i = 0; i < ul2.children.length; i++) {
console.log(ul2.children[i].children[0].children[0]);
ul2.children[i].children[0].children[0].style.backgroundPosition = '0 ' + -i * 32 + 'px';
}
var focus_ul = document.querySelector('.focus ul');
var ol = document.querySelector('.focus ol');
var count = 0;
var focus_timer = setInterval(function () {
if (count == 2) {
animate(focus_ul, focus_ul.offsetLeft - 375);
// console.log('i run');
// console.log(focus_ul.offsetLeft + ' ' + count);
// focus_ul.style.left = focus_ul.offsetLeft + 375 * 2 + 'px';
focus_ul.style.left = 0 + 'px'; // Here is my problem
console.log(focus_ul);
console.log(focus_ul.offsetLeft + ' ' + count);
}
else {
console.log('before animation ' + focus_ul.offsetLeft + ' ' + count);
animate(focus_ul, focus_ul.offsetLeft - 375);
console.log(focus_ul.offsetLeft + ' ' + count);
}
// focus_ul.style.left = focus_ul.offsetLeft + 375 + 'px';
count++;
count = count % 3;
for (var i = 0; i < ol.children.length; i++) {
ol.children[i].className = '';
}
ol.children[count].className = 'current-choice';
console.log('after a round ' + focus_ul.offsetLeft + ' ' + count);
}, 2500)
})
</script>
I meant to do a photo show that can play automaticly, like a Carousel or swiper, The 375px means that the screen is 375px wide, according to the code, when comming to the last photo, as the animation end, it should change back to the initial one which style.left == 0px, but 0px only occur a small while, next time it would be -1125px, -1500px and so on, I'm confused why i set style.left to 0 but fruitless. I'm new in front end ,thanks helping
You can use more of CSS (and less JavaScript) for this animation.
Declare two separate CSS class definitions for focus_ul. Use JavaScript to change the className of focus_ul.
Use CSS transition for animation of CSS offset-left property.
See: https://www.w3schools.com/css/tryit.asp?filename=trycss3_transition1
Write that custom className instead :hover in above example.
I am trying to add all values of class tmpcpa and place result in final_cpa but final_cpa always return 0.
document.getElementById('cpa' + arr[0]).innerHTML = cpa + '(' + '<label id="tmpcpa">' + tmp_cpa + "</label>" +' For Final' + ')';
var final_cpa = calculate_final_cpa();
console.log(final_cpa);
function calculate_final_cpa() {
var final_cpa = 0;
$('.tmpcpa').each(function () {
if ($(this).val() != 0)
final_cpa += parseInt($(this).text()) || 0;
});
return final_cpa;
}
Surprisingly when i view source code in browser HTML appears as
<label class="tmpcpa">0</label> but when i do inspect element it shows as
<label class="tmpcpa">30.0</label>
Update here is the whole JS. HTML calls process function which ultimately calls calculate_final_cpa()
//"use strict";
function process(arr) {
document.getElementById('txtgrade' + arr[0] + arr[1] + arr[2]).innerHTML = show_grade(document.getElementById('txtpercentage' + arr[0] + arr[1] + arr[2]).value);
if (validateForm(arr)) {
var module_percentage = +document.getElementById('txtpercentage' + arr[0] + arr[1] + arr[2]).value;
var module_credit = +document.getElementById('txtcredit' + arr[0] + arr[1] + arr[2]).innerHTML;
if (!isNaN(module_percentage) || !isNaN(module_credit)) {
module_percentage = 0;
module_credit = 0;
var total_credit_semester = 0;
var sum_module_percentage_x_credit = 0;
for ( i= 2 ; i <= arr[3] + 1 ; i++) {
module_percentage = +document.getElementById('txtpercentage' + arr[0] + arr[1] + i).value;
module_credit = +document.getElementById('txtcredit' + arr[0] + arr[1] + i).innerHTML;
sum_module_percentage_x_credit += module_percentage * module_credit;
total_credit_semester += module_credit;
}
//console.log(module_percentage);
var spa = sum_module_percentage_x_credit / total_credit_semester;
spa = spa.toFixed(1);
document.getElementById('spa' + arr[0] + arr[1]).innerHTML = spa;
calculate_cpa(arr);
}
}
}
function validateForm(arr) {
var isValid = true;
var tbl_id = 'tbl_semester' + arr[0] + arr[1];
$('#' + tbl_id + ' :input').each(function () {
if ($(this).val() === '')
isValid = false;
});
return isValid;
}
function calculate_final_cpa() {
var final_cpa = 0;
$('.tmpcpa').each(function () {
if ($(this).val() != 0)
final_cpa += parseInt($(this).text()) || 0;
});
return final_cpa;
}
/*
* Works for 2 semester per level and 3 year course (optimize later)
*/
function calculate_cpa(arr) {
var isValid = true;
for ( i= 1 ; i <= 2 ; i++) {
var spa = document.getElementById('spa' + arr[0] + i).innerHTML;
if (spa == "N/A") {
isValid = false;
}
}
if (isValid) {
var total_credit_level = 0;
var total_spa_x_credit = 0;
for ( i= 1 ; i <= 2 ; i++) {
var arr2= [arr[0], i];
var spa = +document.getElementById('spa' + arr[0] + i).innerHTML;
total_spa_x_credit += spa * getcredits(arr2);
total_credit_level += getcredits(arr2);
}
var cpa = total_spa_x_credit / total_credit_level;
cpa = cpa.toFixed(1);
document.getElementById('cpa' + arr[0]).innerHTML = cpa;
var level = +document.getElementById('level' + arr[0]).innerHTML
var tmp_cpa = ((level / 100) * cpa).toFixed(1);
document.getElementById('cpa' + arr[0]).innerHTML = cpa + '(' + '<label class="tmpcpa">' + tmp_cpa + "</label>" +' For Final' + ')';
var final_cpa = calculate_final_cpa();
console.log(final_cpa);
if (final_cpa != 0) {
var award = show_award(final_cpa);
document.getElementById('award').innerHTML = award;
document.getElementById('finalcpa').innerHTML = final_cpa;
}
}
}
function getcredits(arr) {
var sum = 0;
var tbl_id = 'tbl_semester' + arr[0] + arr[1];
$('#' + tbl_id + ' .sum').each(function () {
sum += parseInt($(this).text())||0;
});
return sum;
}
function show_grade(module_percentage) {
if (isNaN(module_percentage)) {
return 'N/A';
}
if (module_percentage >= 70 && module_percentage <= 100) {
return 'A';
} else if (module_percentage >= 60 && module_percentage < 70) {
return 'B';
} else if (module_percentage >= 50 && module_percentage < 60) {
return 'C';
} else if (module_percentage >= 40 && module_percentage < 50) {
return 'D';
} else {
return 'F';
}
}
function show_award(cpa) {
if (isNaN(cpa)) {
return 'N/A';
}
if (cpa >= 70 && cpa <= 100) {
return 'First Class with Honours';
} else if (cpa >= 60 && cpa < 70) {
return 'Second Class First Division with Honours';
} else if (cpa >= 50 && cpa < 60) {
return 'Second Class Second Division with Honours';
} else if (cpa >= 45 && cpa < 50) {
return 'Third Class with Honours';
} else if (cpa >= 40 && cpa < 45) {
return 'Pass';
} else if (cpa < 40) {
return 'No award';
}
}
you need to be sure you are calling the function after the document is ready.
Also, you are using unassigned value.
</body>
<script>
function calculate_final_cpa() {
var final_cpa = 0;
$('.tmpcpa').each(function () {
if ($(this).val() != 0)
final_cpa += parseInt($(this).text()) || 0;
});
return final_cpa;
}
$(document).ready(function(){
var final_cpa = calculate_final_cpa();
document.getElementById('cpa' + arr[0]).innerHTML = cpa + '(' + '<label id="tmpcpa">' + final_cpa + "</label>" +' For Final' + ')';
console.log(final_cpa);
});
</script>
Simple button that should be creating new <p> elements when its clicked but it isn't working and I'm not sure why as I've compared it to other code of mine.
Demo
var battle = function() {
while(monsterHP > 0){
var playerDam = Math.floor(Math.random() * ((playerAtk - monsterAtk) + 2);
$('#battle').append("<p>You have hit the monster for " + playerDam + " damage. The monster has " + (monsterHP - playerDam) + "HP left</p>");
monsterHP -= playerDam;
if(monsterHP <= 0) {
$('#battle').append("<p>You have defeated the monster</p>");
}
}
}
$('#battleButton').click(function() {
battle();
}
You have many syntax errors in your code. If you correct them (as below), then it works fine. When you write a JQuery append, you need to put a ')' after your argument. Likewise, functions need to have a '}' after them.
var playerAtk = 5;
var playerDef = 5;
var playerHP = 10;
var monsterAtk = 4;
var monsterDef = 4;
var monsterHP = 8;
var battle = function() {
while(monsterHP > 0){
var playerDam = Math.floor(Math.random() * ((playerAtk - monsterAtk) + 2));
$('#battle').append("<p>You have hit the monster for " + playerDam + " damage. The monster has " + (monsterHP - playerDam) + "HP left</p>");
monsterHP -= playerDam;
if(monsterHP <= 0) {
$('#battle').append("<p>You have defeated the monster</p>");
}
}
}
$('#battleButton').click(function() {
battle();
});
How can I add a fade effect in this javascript?
I try to make fade or slide effect in this script but not working.
my idea is made slideshow effect in my wordpress page. i don't want use plugin because my page is very slow and a try to make very optimized with this javascript
var ultimateshow = new Array()
//ultimateshow[x]=["#", "OPTIONAL link for image", "OPTIONAL link target"]
ultimateshow[0] = ['image1.jpg', '#']
ultimateshow[1] = ['image2.jpg', '#']
var slidewidth = "980px" // width
var slideheight = "250px" // height
var slidecycles = "2" //
var randomorder = "no" //
var preloadimages = "yes" //preload images? "yes" or "no"
var slidebgcolor = 'white'
var slidedelay = 3000
var ie = document.all
var dom = document.getElementById
var curcycle = 0
if (preloadimages == "yes") {
for (i = 0; i < ultimateshow.length; i++) {
var cacheimage = new Image()
cacheimage.src = ultimateshow[i][0]
}
}
var currentslide = 0
function randomize(targetarray) {
ultimateshowCopy = new Array()
var the_one
var z = 0
while (z < targetarray.length) {
the_one = Math.floor(Math.random() * targetarray.length)
if (targetarray[the_one] != "_selected!") {
ultimateshowCopy[z] = targetarray[the_one]
targetarray[the_one] = "_selected!"
z++
}
}
}
if (randomorder == "yes")
randomize(ultimateshow)
else
ultimateshowCopy = ultimateshow
function rotateimages() {
curcycle = (currentslide == 0) ? curcycle + 1 : curcycle
ultcontainer = '<center>'
if (ultimateshowCopy[currentslide][1] != "") ultcontainer += '<a href="' + ultimateshowCopy[currentslide][1] + '" target="' + ultimateshowCopy[currentslide][2] + '">'
ultcontainer += '<img src="' + ultimateshowCopy[currentslide][0] + '" border="0">'
if (ultimateshowCopy[currentslide][1] != "")
ultcontainer += '</a>'
ultcontainer += '</center>'
if (ie || dom)
crossrotateobj.innerHTML = ultcontainer
if (currentslide == ultimateshow.length - 1)
currentslide = 0
else
currentslide++
if (curcycle == parseInt(slidecycles) && currentslide == 0)
return
setTimeout("rotateimages()", slidedelay)
}
if (ie || dom)
document.write('<div id="slidedom" style="width:' + slidewidth + ';height:' + slideheight + '; background-color:' + slidebgcolor + '"></div>')
function start_slider() {
crossrotateobj = dom ? document.getElementById("slidedom") : document.all.slidedom
rotateimages()
}
if (ie || dom)
window.onload = start_slider
I am trying to create a circular page with tabs around it and the SVG path are not being appended to the html.
Any help would be grateful. I have not worked with JS in a long time since I have moved on to Java so my skills are rusty.
var tabs = 10;
var radius = 500;
var xcords = [];
for (var i = 1; i <= tabs; i++) {
xcords[xcords.length] = radius + Math.cos(36 * i + 18) * radius;
}
var ycords = [];
for (var i = 1; i <= tabs; i++) {
ycords[ycords.length] = radius + Math.sin(36 * i + 18) * radius;
}
$(document).ready(function(){
for (var i = 1; i < tabs; i++) {
$(".svg").prepend("<path class='piece' />");
$(".piece").attr({
"d" : "M" + xcords[i] + "," + ycords[i] + "L500,500 L" + xcords[i + 1] + "," + ycords[i + 1] " A500,500 0 0,0 " + xcords[i] + "," + ycords[i] + " Z"
});
}
$(".piece").mouseenter(function() {
$(this).fadeTo(100, 0.7);
});
$(".piece").mouseleave(function() {
$(this).fadeTo(100, 1);
});
$(".piece").click(function() {
$(".center").attr("fill",$(this).attr("fill"));
});
});
I know that the array id not large enough to get xcords[11] but a solution to it would be helpful.