progress bar increases as we press the button - javascript

I am new to programming but trying to solve a problem.
I am trying to increase a progress bar as I press on the "d" button. I am trying to do it recursively but I don't have enough skills to do it properly. Any help would be greately appreciated.
My js file looks like this so far:
window.addEventListener('keypress', function(e) {
function counter(p) {
//if the button is "d"
if (e.keyCode === 100) {
//target progressbar width and increase it
$('#progressbar').css('width', function(index, value) {
return $("#progressbar").css('width', ((p * 2) + "%"));
});
if ($('#progressbar').width() < 100) {
return counti(p + 1)
}
}
};
counti(1);
});
My html:
<div id = "myProgress" >
<div id = "progressbar" > 0 / 50 </div>
</div>

var count = 0;
var maxCount = 50;
var progressBar = document.getElementById("progressbar")
window.addEventListener("keypress", function(e) {
//if the button is "d"
if (e.keyCode === 100) {
// increase count if it's less than maxCount
count = count === maxCount ? maxCount : count + 1;
//target progressbar width and increase it
var newWidth = (count / maxCount) * 100 + "%";
progressBar.style.width = newWidth;
progressBar.innerHTML = count + "/" + maxCount
}
});
#myProgress {
width: 400px;
height: 30px;
background-color: #e4e4e4;
}
#progressbar {
width: 0%;
height: 30px;
background-color: #5980a7;
color: #fff;
}
<div id="myProgress">
<div id="progressbar">0/50</div>
</div>

Related

change css class property increment

I have a small question!
I'am trying to change css width property using JavaScript like this:
document.getElementById("progressvalue").style.width = "80%";
.progress {
width: 100%;
max-width: 500px;
border: 3px solid black;
height: 20px;
padding: 1px;
}
#progressvalue {
height: 100%;
width: 0%;
background-color: #05e35e;
}
<div class="progress">
<div id="progressvalue"></div>
</div>
But instead of 80% in JavaScript code, I want to increase the width value by 20%.
Like (width = width + 20%)
I want to apply this changing once (So I can use it mutiple times using other conditions), and this is why I need it like this (width = width + 20%)
You can try to read the element's style.width property, by keeping only the numeric part of it and adding it to your step (eg 20%).
const step = 5;
const updateProgress = () => {
const currentWidth = Number(document.getElementById("progressvalue").style.width.replace( "%", ""));
if (currentWidth>=100) {
return;
}
else {
document.getElementById("progressvalue").style.width = `${currentWidth+step}%`;
}
}
You can check this out in this CodePen.
I guess you want to do some animation right ? If so you can use recursivity with setTimeout:
function progress(val) {
val += 20;
document.getElementById("progressvalue").style.width = val + "%";
if (val < 100) // To stop the loop when progress bar is full
setTimeout(function () {
progress(val);
}, 1000)
}
progress(0); // Start the animation
This will increase by 20% every 0.5 seconds.
let percent = 0;
setInterval(() =>
{
if(percent > 100) {
clearInterval();
return;
}
document.getElementById("progressvalue").style.width = percent + "%";
percent += 20;
}, 500);
You can use this:
var el = document.getElementById("progressvalue");
var elementWidth = el.style.width;
var newWidth = `${20+parseInt(elementWidth.substring(0, elementWidth.length-1))}%`
el.style.width=newWidth;
Assuming that you have set the width of the element initially to a percent value.
<button type="button" id="myBtn" onclick="myFunction()">Change the width</button>
<script>
function myFunction() {
let progress = document.getElementById("progressvalue");
let style = window.getComputedStyle(progress, null).getPropertyValue('width');
let currentSize = parseFloat(style);
progress.style.width = (currentSize + 20) + '%';
}
</script>
You can try it
//offsetWidth : returns the width of the element
var element_width=document.getElementById("progressvalue").offsetWidth
document.getElementById("progressvalue").style.width =element_width + (20*element_width/100) +'px' ;
You need to get the current width of <div id="progressvalue"></div>, put it in a variable and add 20 and reassign that value to <div id="progressvalue"></div>.

JavaScript: array values are automatically getting deleted

I am making an image slider/ carousel. If you drag it, the images will get momentum and will keep on moving for sometime. There are few issues, one of them is getting the following error frequently: "glide.js:104 Uncaught TypeError: Cannot read property '1' of undefined". JavaScript here is supposed to access a value that is inside an array, but since the array is empty, i'm getting this error. However, the array shouldn't be empty, as the code that empties the array, comes later. Project
var projectContainer = document.querySelector(".project-container")
var projects = document.querySelectorAll(".project")
// exProject is declared so that every project has same transalte to refer to instead of referring to their individual transalations
var exProject = projects[0]
var style = window.getComputedStyle(exProject)
exProject.currentTranslationX = (new WebKitCSSMatrix(style.webkitTransform)).m41
// after dragging, do not add force if mouse has not been moved for pauseTime milliseconds
pauseTime = 40
lastMousePositions = []
//this will set margin to 80, i thought this is better than hardcoding
elementAOffset = projects[0].offsetLeft;
elementBOffset = projects[1].offsetLeft;
elementAWidth = parseInt(getComputedStyle(projects[0]).width)
margin = (elementBOffset - (elementAOffset + elementAWidth))
//projects will teleport to other side if they hit either of the boundary
LeftSideBoundary = -(elementAWidth)
RightSideBoundary = (elementAWidth * (projects.length)) + (margin * (projects.length))
RightSidePosition = RightSideBoundary - elementAWidth;
//how often to update speed (in milliseconds)
intervalTime = 15
//how much speed is lost at every interTime milliseconds
frictionPerMilliseconds = (20 / 1000);
frictionPerMilliseconds *= intervalTime * 5;
mouseInitialPosition = 0;
mouseIsDown = false
startTime = 0;
speed = 0;
mousemoving = false
projectContainer.addEventListener("mousedown", e => {
mouseInitialPosition = e.clientX
mouseIsDown = true;
startDate = new Date();
startTime = startDate.getTime();
lastMousePositions.push(e.clientX)
speed = 0
})
projectContainer.addEventListener("mousemove", e => {
if (!mouseIsDown) return;
distanceTravelled = e.clientX - mouseInitialPosition
if (speed === 0) {
projects.forEach(project => {
project.style.transform = 'translateX(' + ((exProject.currentTranslationX) + ((distanceTravelled))) + 'px)';
shiftPosition(project, distanceTravelled)
})
}
if ((new Date()).getTime() - lastMousePositions[lastMousePositions.length - 1][1] > 50) {
lastMousePositions = []
}
pushToMousePositions(e.clientX)
})
projectContainer.addEventListener("mouseup", e => {
dragEnd(e);
})
projectContainer.addEventListener("mouseleave", e => {
dragEnd(e);
})
function dragEnd(e) {
finalPosition = e.clientX;
distanceTravelled = finalPosition - mouseInitialPosition
endDate = new Date();
endTime = endDate.getTime();
timeElapsed = (endTime - startTime) / 1000
mouseIsDown = false;
tempSpeed = distanceTravelled / timeElapsed
tempSpeed = (tempSpeed / 1000) * 15
if (tempSpeed < 0 && speed < 0) {
if (tempSpeed < speed) {
speed = tempSpeed
}
} else if (tempSpeed > 0 && speed > 0) {
if (tempSpeed > speed) {
speed = tempSpeed
}
} else {
speed = tempSpeed
}
if (lastMousePositions.length === 0) {
console.log("error gonna pop up")
}
if (endTime - (lastMousePositions[lastMousePositions.length - 1])[1] >= pauseTime) {
speed = 0
}
mouseExit(e)
intervalFunction = setInterval(move, intervalTime)
}
function mouseExit(e) {
mouseIsDown = false
lastMousePositions = []
var style = window.getComputedStyle(exProject)
exProject.currentTranslationX = (new WebKitCSSMatrix(style.webkitTransform)).m41
projects.forEach(project => {
project.style.transform = 'translateX(' + (exProject.currentTranslationX) + 'px)'
shiftPosition(project, 0)
})
}
function move() {
if (speed === 0) {
clearInterval(intervalFunction)
} else if (Math.abs(speed) <= frictionPerMilliseconds) {
style = window.getComputedStyle(exProject)
exProject.currentTranslationX = (new WebKitCSSMatrix(style.webkitTransform)).m41
projects.forEach(project => {
project.style.transform = 'translateX(' + ((exProject.currentTranslationX) + (speed)) + 'px)'
shiftPosition(project, 0)
})
speed = 0
} else {
style = window.getComputedStyle(exProject)
exProject.currentTranslationX = (new WebKitCSSMatrix(style.webkitTransform)).m41
projects.forEach(project => {
project.style.transform = 'translateX(' + ((exProject.currentTranslationX) + (speed)) + 'px)'
shiftPosition(project, 0)
})
speed < 0 ? speed += frictionPerMilliseconds : speed -= frictionPerMilliseconds;
}
}
function pushToMousePositions(positionToPush) {
if (lastMousePositions.length < 50) {
lastMousePositions.push([positionToPush, (new Date()).getTime()])
} else {
lastMousePositions.shift();
lastMousePositions.push([positionToPush, (new Date()).getTime()])
}
}
function shiftPosition(project, mouseMovement) {
//projectVisualPosition is relative to the left border of container div
projectVisualPosition = project.offsetLeft + (exProject.currentTranslationX + mouseMovement)
tempStyle = window.getComputedStyle(project)
if (projectVisualPosition < LeftSideBoundary) {
project.style.left = ((parseInt(tempStyle.left) + RightSidePosition + 350) + 'px')
}
if (projectVisualPosition > RightSidePosition) {
project.style.left = ((parseInt(tempStyle.left)) - (RightSidePosition + elementAWidth)) + 'px'
}
}
*,
*::before,
*::after {
margin: 0px;
padding: 0px;
box-sizing: border-box;
font-size: 0px;
user-select: none;
font-size: 0;
}
body {
position: relative;
}
.project-container {
font-size: 0px;
position: relative;
width: 1500px;
height: 400px;
background-color: rgb(15, 207, 224);
margin: auto;
margin-top: 60px;
white-space: nowrap;
overflow: hidden;
padding-left: 40px;
padding-right: 40px;
}
.project {
font-size: 100px;
margin: 40px;
display: inline-block;
height: 300px;
width: 350px;
background-color: red;
border: black 3px solid;
user-select: none;
position: relative;
}
<div class="project-container">
<div class="project">1</div>
<div class="project">2</div>
<div class="project">3</div>
<div class="project">4</div>
<div class="project">5</div>
<div class="project">6</div>
<div class="project">7</div>
<div class="project">8</div>
</div>
The problem is this:
projectContainer.addEventListener("mouseleave", (e) => {
dragEnd(e);
});
You're calling dragEnd(e) when the cursor leaves projectContainer. That can happen while the lastMousePositions array is still empty.
Option 1: Don't call dragEnd(e) on the mouseleave event
Option 2: Inside the dragEnd(e) function, check that the array is not empty before you try to access its elements:
if (lastMousePositions.length !== 0) {
if (
endTime - lastMousePositions[lastMousePositions.length - 1][1] >=
pauseTime
) {
speed = 0;
}
}

JavaScript - Stop laser once its in its incrementation cycle

To see a working example simply copy code into notepad++ and run in chrome as a .html file, I have had trouble getting a working example in snippet or code pen, I would have given a link to those websites if I could get it working in them.
The QUESTION is; once I fire the laser once it behaves exactly the way I want it to. It increments with lzxR++; until it hits boarder of the game arena BUT if I hit the space bar WHILST the laser is moving the code iterates again and tries to display the laser in two places at once which looks bad and very choppy, so how can I get it to work so the if I hit the space bar a second time even whilst the laser was mid incrementation - it STOPS the incrementing and simply shoots a fresh new laser without trying to increment multiple lasers at once???
below is the Code:
<html>
<head>
<style>
#blueCanvas {
position: absolute;
background-color: black;
width: 932px;
height: 512px;
border: 1px solid black;
top: 20px;
left: 20px;
}
#blueBall {
position: relative;
background-color: white;
border: 1px solid blue;
width: 10px;
height: 10px;
border-radius: 100%;
top: 0px;
left: 0px;
}
#laser {
position: absolute;
background-color: white;
border: 1px solid blue;
width: 10px;
height: 1px;
top: 10px;
left: 10px;
}
#pixelTrackerTop {
position: absolute;
top: 530px;
left: 20px;
}
#pixelTrackerLeft {
position: absolute;
top: 550px;
left: 20px;
}
</style>
<title>Portfolio</title>
<script src="https://ajax.googleapis.com/
ajax/libs/jquery/1.12.4/jquery.min.js">
</script>
<SCRIPT LANGUAGE="JavaScript" type="text/javascript">
document.addEventListener("keydown", keyBoardInput);
var topY = 0;
var leftX = 0;
var lzrY = 0;
var lzrX = 0;
function moveUp() {
var Y = document.getElementById("blueBall");
topY = topY -= 1;
Y.style.top = topY;
masterTrack();
if (topY < 1) {
topY = 0;
Y.style.top = topY;
};
stopUp = setTimeout("moveUp()", 1)
/**allows for progression of speed with additional key strokes**/
topStop();
stopConflictYup();
console.log('moveUp');
};
function moveDown() {
var Y = document.getElementById("blueBall");
topY = topY += 1;
Y.style.top = topY;
masterTrack();
if (topY > 500) {
topY = 500;
Y.style.top = topY;
};
stopDown = setTimeout("moveDown()", 1)
/**allows for progression of speed with additional key strokes**/
topStop();
stopConflictYdown();
console.log('moveDown');
};
function moveLeft() {
var X = document.getElementById("blueBall");
leftX = leftX -= 1;
X.style.left = leftX;
masterTrack();
if (leftX < 1) {
leftX = 0;
Y.style.leftX = leftX;
};
stopLeft = setTimeout("moveLeft()", 1)
/**allows for progression of speed with additional key strokes**/
leftStop();
stopConflictXleft();
console.log('moveLeft');
};
function moveRight() {
var X = document.getElementById("blueBall");
leftX = leftX += 1;
X.style.left = leftX;
masterTrack();
if (leftX > 920) {
leftX = 920;
Y.style.leftX = leftX;
};
stopRight = setTimeout("moveRight()", 1)
/**allows for progression of speed with additional key strokes**/
leftStop();
stopConflictXright();
console.log('moveRight');
};
function masterTrack() {
var pxY = topY;
var pxX = leftX;
document.getElementById('pixelTrackerTop').innerHTML =
'Top position is ' + pxY;
document.getElementById('pixelTrackerLeft').innerHTML =
'Left position is ' + pxX;
};
function topStop() {
if (topY <= 0) {
clearTimeout(stopUp);
console.log('stopUp activated');
};
if (topY >= 500) {
clearTimeout(stopDown);
console.log('stopDown activated');
};
};
function leftStop() {
if (leftX <= 0) {
clearTimeout(stopLeft);
console.log('stopLeft activated');
};
if (leftX >= 920) {
clearTimeout(stopRight);
console.log('stopRight activated');
};
};
function stopConflictYup() {
clearTimeout(stopDown);
};
function stopConflictYdown() {
clearTimeout(stopUp);
};
function stopConflictXleft() {
clearTimeout(stopRight);
};
function stopConflictXright() {
clearTimeout(stopLeft);
};
function shootLaser() {
var l = document.getElementById("laser");
var lzrY = topY;
var lzrX = leftX;
fireLaser();
function fireLaser() {
l.style.left = lzrX; /**initial x pos **/
l.style.top = topY; /**initial y pos **/
var move = setInterval(moveLaser, 1);
/**continue to increment laser unless IF is met**/
function moveLaser() { /**CALL and start the interval**/
var bcrb = document.getElementById("blueCanvas").style.left;
if (lzrX > bcrb + 920) {
/**if the X axis of the laser goes beyond the
blueCanvas 0 point by 920 then stop incrementing the laser on its X
axis**/
clearInterval(move);
/**if statement was found true so stop increment of laser**/
} else {
lzrX++;
l.style.left = lzrX;
};
};
};
};
function keyBoardInput() {
var i = event.keyCode;
if (i == 32) {
shootLaser();
};
if (i == 38) {
if (topY > 0) {
moveUp();
};
};
if (i == 40) {
if (topY < 500) {
moveDown();
};
};
if (i == 37) {
if (leftX > 0) {
moveLeft();
};
};
if (i == 39) {
if (leftX < 920) {
moveRight();
};
};
};
/**
!! gradual progression of opacity is overall
!! being able to speed up element is best done with setTimout
!! setInterval is constant regards to visual speed
!! NEXT STEP IS ARRAYS OR CLASSES
IN ORDER TO SHOOT MULITPLE OF SAME ELEMENT? MAYBEE?
var l = document.getElementById("laser");
lzrX = lzrX += 1;
l.style.left = lzrX;
lzrY = topY += 1;
l.style.top = lzrY;
**/
</SCRIPT>
</head>
<div id="blueCanvas">
<div id="laser"></div>
<div id="blueBall">
</div>
</div>
<p id="pixelTrackerTop">Top position is 0</p>
<br>
<p id="pixelTrackerLeft">Left position is 0</p>
</body>
</html>
Solved the problem with using a variable called "g" and incrementing it once the laser is shot!
var g = 0;
function keyBoardInput() {
var i = event.keyCode;
if (i == 32) {
if (g < 1) {
shootLaser();
g++;
};
};

How to create a curved slider?

i'm trying to create a curved slider with jquery like this:
with no success.
can anyone point be to the right direction?
Thanks allot
Avi
This is what you want exactly. By using the jQuery roundSlider plugin you can make any type of arc slider with custom appearance.
Please check this jsFiddle for the demo of you requirement.
Live demo:
$("#arc-slider").roundSlider({
sliderType: "min-range",
circleShape: "custom-quarter",
value: 75,
startAngle: 45,
editableTooltip: true,
radius: 350,
width: 6,
handleSize: "+32",
tooltipFormat: function (args) {
return args.value + " %";
}
});
#arc-slider {
height: 110px !important;
width: 500px !important;
overflow: hidden;
padding: 15px;
}
#arc-slider .rs-container {
margin-left: -350px; /* here 350 is the radius value */
left: 50%;
}
#arc-slider .rs-tooltip {
top: 60px;
}
#arc-slider .rs-tooltip-text {
font-size: 25px;
}
#arc-slider .rs-border{
border-width: 0px;
}
/* Appearance related changes */
.rs-control .rs-range-color {
background-color: #54BBE0;
}
.rs-control .rs-path-color {
background-color: #5f5f5f;
}
.rs-control .rs-handle {
background-color: #51c5cf;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.roundslider/1.0/roundslider.min.js"></script>
<link href="https://cdn.jsdelivr.net/jquery.roundslider/1.0/roundslider.min.css" rel="stylesheet"/>
<div id="arc-slider" class="rslider"></div>
Screenshots of the Output:
To know more about the roundSlider, please check the demos and documentation page.
Please check this LINK, you will get enough details for the slider.
'slide': function(e, ui){
var percentLeft;
var submitValue;
var Y = ui.value - 100; //Find center of Circle (We're using a max value and height of 200)
var R = 100; //Circle's radius
var skip = false;
$(this).children('.ui-slider-handle').attr('href',' UI.val = ' + ui.value);
//Show default/disabled/out of bounds state
if ( ui.value > 0 && ui.value < 201 ) { //if in the valid slide rang
$(this).children('.ui-slider-handle').addClass('is-active');
}
else {
$(this).children('.ui-slider-handle').removeClass('is-active');
}
//Calculate slider's path on circle, put it there, by setting background-position
if ( ui.value >= 0 && ui.value <= 200 ) { //if in valid range, these are one inside the min and max
var X = Math.sqrt((R*R) - (Y*Y)); //X^2 + Y^2 = R^2. Find X.
if ( X == 'NaN' ) {
percentLeft = 0;
}
else {
percentLeft = X;
}
}
else if ( ui.value == -1 || ui.value == 201 ) {
percentLeft = 0;
skip = true;
}
else {
percentLeft = 0;
}
//Move handle
if ( percentLeft > 100 ) { percentLeft = 100; }
$(this).children('.ui-slider-handle').css('background-position',percentLeft +'% 100%'); //set new css sprite, active state
//Figure out and set input value
if ( skip == true ) {
submitValue = 'fail';
$(this).children('.ui-slider-handle').css('background-position',percentLeft +'% 0%'); //reset css sprite
}
else {
submitValue = Math.round(ui.value / 2); //Clamp input value to range 0 - 100
}
$('#display-only input').val(submitValue); //display selected value, demo only
$('#slider-display').text(submitValue); //display selected value, demo only
$(this).prev('.slider-input').val(ui.value); //Set actual input field val. jQuery UI hid it for us, but it will be submitted.
}
You can also try this LINK also.
If you want any other assistance, then please add comment.
Regards D.
Alternative way you can use this plugin for a curved/360 degree slider
Reference
Here is the coding:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="js/round-slider.min.js"></script>
<div class="box dotted">
<div class="left">
<div id="degrees" class="demo"></div>
</div>
<div class="right">
<p class="name">Degrees</p>
<p id="degrees-data"></p>
</div>
</div>
Javascript
(function($){
'use strict';
var set_html = function(value, index, angle, unit){
var html = ''
,val = value;
if(unit !== ''){
val += unit;
}
html += '<b>Value: </b>' + val + '<br/>';
html += '<b>Index: </b>' + index + '<br/>';
html += '<b>Angle: </b>' + angle + '<br/>';
return html;
};
$('document').ready(function(){
var self = {
degrees: null
};
self.degrees = $('#degrees').round_slider({
min: 0,
max: 359,
unit_sign: '\u00b0',
bg: 'img/bg/degrees-theme.png',
handle_bg: 'img/handles/wheel-33-33.png',
input_bg: 'img/input/round-50.png',
points_bg: 'img/points/degress-white.png',
angle_changed_callback: function(value, index, angle, unit){
$('#degrees-data').html(set_html(value, index, angle, unit));
}
});
});
})(jQuery);
Check here for the demo
Demo

How to color every second row using jQuery when the number of element in a row is variable?

Consider the following example which should color every second row: (live demo here)
JS:
$(function() {
var wrapper = $("<div></div>")
for (i = 0; i < 100; i++) {
wrapper.append("<span></span>");
}
$("body").append(wrapper);
color_rows();
});
function color_rows() {
$("span").each(function(i) {
if (i % 10 >= 5) {
$(this).css("background-color", "red");
}
});
}
CSS:
div {
width: 450px;
height: 400px;
background-color: #ccc;
overflow: auto;
}
span {
display: inline-block;
width: 50px;
height: 50px;
background-color: #777;
margin: 0 30px 30px 0;
}
The output is:
As you can see, color_rows() function assumes that there are 5 elements per row. If, for example, I change the width of the div to be 350px, the color_rows() function will not work properly (i.e. will not color every second row).
How could I fix color_rows() so that it will work for every width of the div ?
this is my solution:
this works based on the top offset of each element and by comparing the it to the top offset of last element in the loop it detects if new row is seen or not, and then based on the number of row colors rows.
function color_rows() {
var lastTop = -1;
var rowCount = 0;
$("span").each(function(i) {
var top = $(this).position().top;
if (top != lastTop) {
rowCount++;
lastTop = top;
}
if(rowCount % 2 == 0)
{
$(this).css("background-color", "red");
}
});
}
jsFiddle: http://jsfiddle.net/Ug6wD/4/
Look at my fixes http://jsfiddle.net/Ug6wD/5/
I am getting Container width, itemWidth + margin. And calculating how many items per row. Get margin-right from span item.
Then minus 20 to the container width, coz of overflow scrollbar.
function color_rows() {
var containerWidth = $('div').width()-20;
var itemWidth = $('span:first').width() + parseInt($('span:first').css('margin-right'));
var itemsPerRow = parseInt(containerWidth / itemWidth);
$("span").each(function(i) {
if (i % (itemsPerRow *2) >= itemsPerRow ) {
$(this).css("background-color", "red");
}
});
}
UPDATE with dynamic margin-right value from CSS AND Right scrollbar fix causing breakage : http://jsfiddle.net/Ug6wD/5/
Edit: This only works on some div-widths.. -.- Nevermind, then..
This should do it:
function color_rows() {
var divW = $('div').width();
var spanW = $('span').outerWidth(true); //Get margin too
var cnt = parseInt(divW/spanW, 10); //Remove decimals
$("span").each(function(i) {
if (i % (cnt*2) >= cnt) {
$(this).css("background-color", "red");
}
});
}
fiddle: http://jsfiddle.net/gn5QW/1/
html
<div id="container">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>
js
$(document).ready(function(){
var box = $(".box");
var con = $("#container");
var box_per_line = Math.floor(parseInt($("#container").width())/ (parseInt( $(".box").width()) +10*2/*px*/));
var style = "black";
$(".box").each(function(i){
if(i % box_per_line == 0){ style = (style == "black") ? "grey" : "black"; }
$(this).css("background-color",style);
});
});
css
.box {
width: 100px;
height: 100px;
float: left;
margin: 10px;
}
#conainer {
background-color: grey;
display: inline-block;
}
I've fixed your code, but please PLEASE don't do this. The internet the in pain,
$(function() {
var wrapper = $("<div></div>")
for (i = 0; i < 100; i++) {
wrapper.append("<span></span>");
}
$("body").append(wrapper);
color_rows();
});
function color_rows() {
var rowWidth = Number( $('div:first').css('width').slice(0,-2) );
var itemWidth = Number( $('span:first').css('width').slice(0,-2) ) + Number( $('span:first').css('margin-right').slice(0,-2) );
var perRow = Math.floor( rowWidth/itemWidth );
$("span").each(function(i) {
if (i % 10 >= perRow ) {
$(this).css("background-color", "red");
}
});
}
There is a simpler way:
$('tr:even').css("background-color", "red");

Categories