How can this counter start from zero? - javascript

How can this script start counting from zero? At the moment it starts with the number it's supposed to count to before starting from zero
The JavaScript function loads the counter when it is called into view. How can the numerical values in the counter start with zeros when it is called into view
function isVisible(el) {
const element = $(el);
var WindowTop = $(window).scrollTop();
var WindowBottom = WindowTop + $(window).height();
var ElementTop = element.offset().top;
//var ElementBottom = ElementTop + element.height();
var ElementBottom = ElementTop + 20;
return ElementBottom <= WindowBottom && ElementTop >= WindowTop;
}
function Counter(el) {
obj = $(el);
if (obj.hasClass("ms-animated")) {
return;
}
obj.addClass("ms-animated");
// get the number
var number = obj.text();
obj.attr("data-number", number);
// clear the HTML element
obj.empty();
// create an array from the text, prepare to identify which characters in the string are numbers
var numChars = number.split("");
var numArray = [];
var setOfNumbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
// for each number, create the animation elements
for (var i = 0; i < numChars.length; i++) {
if ($.inArray(parseInt(numChars[i], 10), setOfNumbers) != -1) {
obj.append(
'<span class="digit-con"><span class="digit' +
numArray.length +
'">0<br>1<br>2<br>3<br>4<br>5<br>6<br>7<br>8<br>9<br></span></span>'
);
numArray[numArray.length] = parseInt(numChars[i], 10);
} else {
obj.append("<span>" + numChars[i] + "</span>");
}
}
// determine the height of each number for the animation
var increment = obj.find(".digit-con").outerHeight();
var speed = 2000;
// animate each number
for (var i = 0; i < numArray.length; i++) {
obj
.find(".digit" + i)
.animate({
top: -(increment * numArray[i])
},
Math.round(speed / (1 + i * 0.333))
);
}
}
$(window).scroll(function() {
const counterNumbers = $(".number").toArray();
counterNumbers.filter(isVisible).map(Counter);
});
$(window).trigger("scroll");
.number {
display: block;
font-size: 6rem;
line-height: 6.5rem;
}
.number *+* {
margin-top: 0;
}
.digit-con {
display: inline-block;
height: 6.5rem;
overflow: hidden;
vertical-align: top;
}
.digit-con span {
display: block;
font-size: 6rem;
line-height: 6.5rem;
position: relative;
text-align: center;
top: 0;
width: 0.55em;
}
.month {
height: 100vh;
}
<h1>Scroll</h1>
<div class="number">$2,350,354.43</div>
<div class="month">March</div>
<div class="number">$6,350,354.43</div>
<div class="month">March</div>
<div class="number">$8,500,435.33</div>
<div class="month">April</div>
<div class="number">$3,500,435.53</div>
<div class="month">May</div>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js'></script>

Your issue is a something similar to FOUC - Flash of Unstyled Content - where what's originally in the HTML is displayed before it can be updated.
This can be fixed by changing the html and showing the value you want to display on load, while storing the required number in a data- attribute, eg:
<div class="number" data-number="$2,350,354.43">$0,000,000.00</div>
with a small change to your existing code to read the data- instead of text, from
var number = obj.text();
obj.attr("data-number", number); // this is never used
to
var number = obj.data("number");
If you can't change the html (or don't want to) then you can have an initialisation script run before your first scroll initialisation:
$(".number").each((i,e) => {
var obj = $(e);
var number = obj.text();
obj.data("number", number);
obj.text(number.replace(/\d/g, "0"));
});
You will still get FOUC on the very first counter if it's already visible because that's how javascript works: to keep things simple/basic: the page is rendered, then js runs. So there's a short time before the js runs where it's parsing/processing the js ready to run - how long this will be depends on how much js you have (including libraries) / whether it's cached / how much initialisation code there is.
Generally better to output your HTML as you want it displayed rather than rely on JS to update it, but that's not always possible.
Updated snippet:
function isVisible(el) {
const element = $(el);
var WindowTop = $(window).scrollTop();
var WindowBottom = WindowTop + $(window).height();
var ElementTop = element.offset().top;
//var ElementBottom = ElementTop + element.height();
var ElementBottom = ElementTop + 20;
return ElementBottom <= WindowBottom && ElementTop >= WindowTop;
}
function Counter(el) {
obj = $(el);
if (obj.hasClass("ms-animated")) {
return;
}
obj.addClass("ms-animated");
// get the number
//var number = obj.text();
//obj.attr("data-number", number);
var number = obj.data("number");
// clear the HTML element
obj.empty();
// create an array from the text, prepare to identify which characters in the string are numbers
var numChars = number.split("");
var numArray = [];
var setOfNumbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
// for each number, create the animation elements
for (var i = 0; i < numChars.length; i++) {
if ($.inArray(parseInt(numChars[i], 10), setOfNumbers) != -1) {
obj.append(
'<span class="digit-con"><span class="digit' +
numArray.length +
'">0<br>1<br>2<br>3<br>4<br>5<br>6<br>7<br>8<br>9<br></span></span>'
);
numArray[numArray.length] = parseInt(numChars[i], 10);
} else {
obj.append("<span>" + numChars[i] + "</span>");
}
}
// determine the height of each number for the animation
var increment = obj.find(".digit-con").outerHeight();
var speed = 2000;
// animate each number
for (var i = 0; i < numArray.length; i++) {
obj
.find(".digit" + i)
.animate({
top: -(increment * numArray[i])
},
Math.round(speed / (1 + i * 0.333))
);
}
}
$(window).scroll(function() {
const counterNumbers = $(".number").toArray();
counterNumbers.filter(isVisible).map(Counter);
});
$(".number").each((i,e) => {
var obj = $(e);
var number = obj.text();
obj.data("number", number);
obj.text(number.replace(/\d/g, "0"));
});
$(window).trigger("scroll");
.number {
display: block;
font-size: 6rem;
line-height: 6.5rem;
}
.number *+* {
margin-top: 0;
}
.digit-con {
display: inline-block;
height: 6.5rem;
overflow: hidden;
vertical-align: top;
}
.digit-con span {
display: block;
font-size: 6rem;
line-height: 6.5rem;
position: relative;
text-align: center;
top: 0;
width: 0.55em;
}
.month {
height: 100vh;
}
<h1>Scroll</h1>
<div class="number">$2,350,354.43</div>
<div class="month">March</div>
<div class="number">$6,350,354.43</div>
<div class="month">March</div>
<div class="number">$8,500,435.33</div>
<div class="month">April</div>
<div class="number">$3,500,435.53</div>
<div class="month">May</div>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js'></script>

Related

Prevent block from touching the containers borders

I have this little block that I move around using javascript code. It works all good except if I keep moving it, it can easily get out of the box where it is supposed to be.
Can I prevent this somehow? So no matter how far I want to move it, it will stay stuck inside of the container/box ?
Here's my snippet code:
/// store key codes and currently pressed ones
var keys = {};
keys.UP = 38;
keys.LEFT = 37;
keys.RIGHT = 39;
keys.DOWN = 40;
/// store reference to character's position and element
var character = {
x: 100,
y: 100,
speedMultiplier: 2,
element: document.getElementById("character")
};
var is_colliding = function(div1, div2) {
var d1_height = div1.offsetHeight;
var d1_width = div1.offsetWidth;
var d1_distance_from_top = div1.offsetTop + d1_height;
var d1_distance_from_left = div1.offsetLeft + d1_width;
var d2_height = div2.offsetHeight;
var d2_width = div2.offsetWidth;
var d2_distance_from_top = div2.offsetTop + d2_height;
var d2_distance_from_left = div2.offsetLeft + d2_width;
var not_colliding =
d1_distance_from_top <= div2.offsetTop ||
div1.offsetTop >= d2_distance_from_top ||
d1_distance_from_left <= div2.offsetTop ||
div1.offsetLeft >= d2_distance_from_left;
return !not_colliding;
};
/// key detection (better to use addEventListener, but this will do)
document.body.onkeyup =
document.body.onkeydown = function(e){
if (e.preventDefault) {
e.preventDefault();
}
else {
e.returnValue = false;
}
var kc = e.keyCode || e.which;
keys[kc] = e.type == 'keydown';
};
/// character movement update
var moveCharacter = function(dx, dy){
character.x += (dx||0) * character.speedMultiplier;
character.y += (dy||0) * character.speedMultiplier;
character.element.style.left = character.x + 'px';
character.element.style.top = character.y + 'px';
};
/// character control
var detectCharacterMovement = function(){
if ( keys[keys.LEFT] ) {
moveCharacter(-5, 0);
}
if ( keys[keys.RIGHT] ) {
moveCharacter(5, 0);
}
if ( keys[keys.UP] ) {
moveCharacter(0, -5);
}
if ( keys[keys.DOWN] ) {
moveCharacter(0, 5);
}
};
/// update current position on screen
moveCharacter();
/// game loop
setInterval(function(){
detectCharacterMovement();
}, 1000/24);
body{
display: flex;
justify-content: center;
align-items: center;
}
#character {
position: absolute;
width: 42px;
height: 42px;
background: red;
z-index:99;
}
#container{
width: 400px;
height: 400px;
background: transparent;
border:5px solid rgb(0, 0, 0);
position: relative;
overflow: hidden;
}
<div id="container">
<div id="character"></div>
</div>
PS: You can move the box using keyboard arrows.
Get the container width and height into variable and set a condition on your move
var moveCharacter = function(dx, dy){
let div_width = document.getElementById('container').clientWidth;
let div_height = document.getElementById('container').clientHeight;
if((div_width - character.x) < 50 ){ // 50 = width of character and padding
character.x = div_width - 50;
}
if(character.x < 10){ // Padding
character.x = 11;
}
if((div_height - character.y) < 50 ){
character.y = div_height - 50;
}
if(character.y < 10){
character.y = 11;
}

Add scores grid game JavaScript

I want to add 10 points when blue box goes into brown box.
I tried to set score = 0 and points to add = 10 but it doesn't work.
I alert '+10 points' and it shows me the alert so I guess the problem is the DOM ?!?
Any suggestions ?
Thanks !
let moveCounter = 0;
let score = 0;
let obs = 10;
document.getElementById('score').textContent = '0';
var grid = document.getElementById("grid-box");
for (var i = 1; i <= 49; i++) {
var square = document.createElement("div");
square.className = 'square';
square.id = 'square' + i;
grid.appendChild(square);
}
var obstacles = [];
while (obstacles.length < 10) {
var randomIndex = parseInt(49 * Math.random());
if (obstacles.indexOf(randomIndex) === -1) {
obstacles.push(randomIndex);
var drawObstacle = document.getElementById('square' + randomIndex);
$(drawObstacle).addClass("ob")
}
}
var playerOne = [];
while (playerOne.length < 1) {
var randomIndex = parseInt(49 * Math.random());
if (playerOne.indexOf(randomIndex) === -1) {
playerOne.push(randomIndex);
var drawPone = document.getElementById('square' + randomIndex);
$(drawPone).addClass("p-0")
}
}
var addPoints = $('#score');
$('#button_right').on('click', function() {
if ($(".p-0").hasClass("ob")) {
alert('add +10 points !!!')
addPoints.text( parseInt(addPoints.text()) + obs );
}
moveCounter += 1;
if ($(".p-0").hasClass("ob")) {
}
$pOne = $('.p-0')
$pOneNext = $pOne.next();
$pOne.removeClass('p-0');
$pOneNext.addClass('p-0');
});
#grid-box {
width: 400px;
height: 400px;
margin: 0 auto;
font-size: 0;
position: relative;
}
#grid-box>div.square {
font-size: 1rem;
vertical-align: top;
display: inline-block;
width: 10%;
height: 10%;
box-sizing: border-box;
border: 1px solid #000;
}
.ob {
background-color: brown;
}
.p-0 {
background-color: blue;
}
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<div id="grid-box">
</div>
<div class="move">
<button id="button_right">right</button><br>
</div>
<div id="score">
</div>
Thank you very much! I am new to JavaScript/ JQuery
Thank you very much!
You are trying to change the HTML inside of the div with id "score".
Selecting the css element using $("#id") retrieves the DOM element and not its contents so adding the score directly to it has no consequences.
What you want to do is: update the score variable and then set the HTML inside the div to the score value.
So instead of just:
addPoints += obs
you should
score += obs
addPoints.html(score)

How to get element attribute based on highest z-index

I can't figure out how to acheive this, I have some elements with common_class class name, I want to get the ID of highest z-index element, is it possible?
function findHighestZIndex(elem)
{
var elems = document.getElementsByClassName(elem);
var highest = 0;
for (var i = 0; i < elems.length; i++)
{
var id = document.getElementsByClassName(elem);
id.getAttribute("id");
console.log(id);
var zindex=document.defaultView.getComputedStyle(elems[i],null).getPropertyValue("z-index");
var ElementDisplay = document.defaultView.getComputedStyle(elems[i],null).getPropertyValue("display");
if ((zindex > highest) && (zindex != 'auto') && (ElementDisplay == 'block'))
{
highest = zindex;
}
}
Here's a short, working implementation of a getHighest(selector) function, along with an example snippet that uses this function to retrieve id values (click the boxes to increment their z-index).
(The significant portion is the first three functions; they could be compressed into one function if needed.)
function getHighest(selector) {
// Return the element that matches selector having the largest z index
return Array.from(document.querySelectorAll(selector)).reduce((a, b) => getZIndex(a) >= getZIndex(b) ? a : b);
}
function getZIndex(el) {
// Return the z-index of el, or 0 if none is set.
return parseInt(getCssProperty(el, "z-index")) || 0;
}
function getCssProperty(el, prop) {
// Return the computed value of the css property prop for the element el
return document.defaultView.getComputedStyle(el, null).getPropertyValue(prop);
}
// -------------------------------------------------------------------------
// additional code for demo below
// -------------------------------------------------------------------------
function updateHighest() {
let highest = getHighest(".box");
document.querySelector("#highest").textContent = `#${highest.id} (${getZIndex(highest)})`;
document.querySelector("#highest").style.color = getCssProperty(highest, "background-color");
}
function setContentToZIndex(el) {
el.textContent = getZIndex(el);
}
Array.from(document.querySelectorAll(".box")).forEach(b => {
b.onclick = () => {
b.style.zIndex = getZIndex(b) + 1;
setContentToZIndex(b);
updateHighest();
};
setContentToZIndex(b);
updateHighest();
});
.box {
width: 100px;
height: 100px;
display: block;
background: grey;
position: absolute;
color: white;
font-size: 2rem;
text-align: center;
line-height: 100px;
user-select: none;
font-family: sans-serif;
}
#b1 {
background: #ff268a;
left: 0px;
top: 0px;
}
#b2 {
background: #242792;
left: 50px;
top: 50px;
}
#b3 {
background: #0ac3d6;
left: 25px;
top: 75px;
}
p {
margin-left: 200px;
font-family: sans-serif;
font-size: 1.2rem;
}
<div class="box" id="b1"></div>
<div class="box" id="b2"></div>
<div class="box" id="b3"></div>
<p>highest z-index: <span id="highest"></span></p>
You could modify the function to return the element with the highest z-index, and then just use .id to get its id.
Another issue: You're comparing zindex and highest as strings instead of numbers. I've prefixed zindex with the unary + operator before comparing, as in your example, if you were to compare a z-index of 9 and a z-index of 1000, it would believe 9 is greater.
Example:
function findHighestZIndex(elem) {
var highest = 0;
var highestElement = null;
var elems = document.getElementsByClassName(elem);
for (var i = 0; i < elems.length; i++) {
var style = document.defaultView.getComputedStyle(elems[i], null);
var zindex = style.getPropertyValue("z-index");
var ElementDisplay = style.getPropertyValue("display");
if ((zindex != 'auto') && (+zindex > highest) && (ElementDisplay == 'block')) {
highest = zindex;
highestElement = elems[i];
}
}
return highestElement;
}
var elem = findHighestZIndex("zindex");
console.log(elem.id + " has the highest z-index.");
div.zindex {
z-index: 500;
position: absolute;
display: block;
}
<div id="first-element" class="zindex" style="z-index: 1;"></div>
<div id="second-element" class="zindex" style="z-index: 3;"></div>
<div id="third-element" class="zindex" style="z-index: 5;"></div>
<div id="fourth-element" class="zindex" style="z-index: 100;"></div>
<div id="fifth-element" class="zindex" style="z-index: 99;"></div>
If you are referring to not getting the id value here:
var elems = document.getElementsByClassName(elem);
var highest = 0;
for (var i = 0; i < elems.length; i++)
{
//This is all wrong here, commenting it out
//var id = document.getElementsByClassName(elem); //You already have this collection
//id.getAttribute("id"); //The above returns a collection so this would fail, you'd need to use an index of the collection
//console.log(id);
//You already have the elements you want, just use the i index to grab the element
//and it's id
console.log(elems[i].id);
You can use these functions:
function isNumeric(val) {
return !isNaN(parseFloat(val)) && isFinite(val);
}
function findHighestZIndex(className) {
let queryObject = document.getElementsByClassName(className);
let childNodes = Object.keys(queryObject).map(key => queryObject[key]);
let highest = 0;
var highestElem;
childNodes.forEach((node) => {
// Get the calculated CSS z-index value.
let cssStyles = document.defaultView.getComputedStyle(node);
let cssZIndex = cssStyles.getPropertyValue('z-index');
// Get any inline z-index value.
let inlineZIndex = node.style.zIndex;
// Coerce the values as integers for comparison.
cssZIndex = isNumeric(cssZIndex) ? parseInt(cssZIndex, 10) : 0;
inlineZIndex = isNumeric(inlineZIndex) ? parseInt(inlineZIndex, 10) : 0;
// Take the highest z-index for this element, whether inline or from CSS.
let currentZIndex = cssZIndex > inlineZIndex ? cssZIndex : inlineZIndex;
if ((currentZIndex > highest)) {
highest = currentZIndex;
highestElem = node;
}
});
var obj = {highestZIndex: highest, elem: highestElem};
return obj;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<html>
<body>
<div class="test" style="z-index: 100;" id="x">1</div>
<div class="test" style="z-index: 10;">2</div>
<div class='test' id="test">3</div>
<script>
function isNumeric(val) {
return !isNaN(parseFloat(val)) && isFinite(val);
}
function findHighestZIndex(className) {
let queryObject = document.getElementsByClassName(className);
let childNodes = Object.keys(queryObject).map(key => queryObject[key]);
let highest = 0;
var highestElem;
childNodes.forEach((node) => {
// Get the calculated CSS z-index value.
let cssStyles = document.defaultView.getComputedStyle(node);
let cssZIndex = cssStyles.getPropertyValue('z-index');
// Get any inline z-index value.
let inlineZIndex = node.style.zIndex;
// Coerce the values as integers for comparison.
cssZIndex = isNumeric(cssZIndex) ? parseInt(cssZIndex, 10) : 0;
inlineZIndex = isNumeric(inlineZIndex) ? parseInt(inlineZIndex, 10) : 0;
// Take the highest z-index for this element, whether inline or from CSS.
let currentZIndex = cssZIndex > inlineZIndex ? cssZIndex : inlineZIndex;
if ((currentZIndex > highest)) {
highest = currentZIndex;
highestElem = node;
}
});
var obj = {highestZIndex: highest, elem: highestElem};
return obj;
}
console.log(findHighestZIndex('test').elem.id);
</script>
</body>
</html>
</body>
</html>

Scrolling marquee w/ repeating text

I want to have a scrolling marquee that never ends, and with that, I mean that there will never be a blank space in the marquee.
So when, for example, all text has been in the screen (viewport) and the latest words are marquee'ing, the marquee will repeat without first ending the marquee (meaning: all text has gone away into the left side [marquee: right -> left]). With repeat I mean that the text will just start over right behind where the marquee is
So when I have the marquee text " Hello poeple of the earth •", and that is here:
_ = blank
! = Char of first run of marquee
^ = char of second run of marquee
& = char of third run of marquee
________!!!!!!!!!!!!!!!!!!!!!!!!!!!!****************************^^^^^^^^^^^^^^^^^^^^^^^^^^^^&&&&&&&&
Ofcourse I need it to be smooth. Something like this answer, but without the blank spaces. The use of libraries doesn't matter.
Can anyone help me?
You can use marque plugin to achieve this
$('.marquee').marquee({
//speed in milliseconds of the marquee
duration: 5000,
//gap in pixels between the tickers
gap: 0,
//time in milliseconds before the marquee will start animating
delayBeforeStart: 0,
//'left' or 'right'
direction: 'left',
//true or false - should the marquee be duplicated to show an effect of continues flow
duplicated: false
});
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type='text/javascript' src='//cdn.jsdelivr.net/jquery.marquee/1.3.1/jquery.marquee.min.js'></script>
<body>
<div class="marquee">stuff to say 1|</div>
<div class="marquee">stuff to say 2|</div>
<div class="marquee">stuff to say 3|</div>
<div class="marquee">stuff to say 4|</div>
<div class="marquee">stuff to say 5</div>
</body>
I think this is what you want :)))
function start() {
new mq('latest-news');
mqRotate(mqr);
}
window.onload = start;
function objWidth(obj) {
if (obj.offsetWidth) return obj.offsetWidth;
if (obj.clip) return obj.clip.width;
return 0;
}
var mqr = [];
function mq(id) {
this.mqo = document.getElementById(id);
var wid = objWidth(this.mqo.getElementsByTagName("span")[0]) + 5;
var fulwid = objWidth(this.mqo);
var txt = this.mqo.getElementsByTagName("span")[0].innerHTML;
this.mqo.innerHTML = "";
var heit = this.mqo.style.height;
this.mqo.onmouseout = function () {
mqRotate(mqr);
};
this.mqo.onmouseover = function () {
clearTimeout(mqr[0].TO);
};
this.mqo.ary = [];
var maxw = Math.ceil(fulwid / wid) + 1;
for (var i = 0; i < maxw; i++) {
this.mqo.ary[i] = document.createElement("div");
this.mqo.ary[i].innerHTML = txt;
this.mqo.ary[i].style.position = "absolute";
this.mqo.ary[i].style.left = wid * i + "px";
this.mqo.ary[i].style.width = wid + "px";
this.mqo.ary[i].style.height = heit;
this.mqo.appendChild(this.mqo.ary[i]);
}
mqr.push(this.mqo);
}
function mqRotate(mqr) {
if (!mqr) return;
for (var j = mqr.length - 1; j > -1; j--) {
maxa = mqr[j].ary.length;
for (var i = 0; i < maxa; i++) {
var x = mqr[j].ary[i].style;
x.left = parseInt(x.left, 10) - 1 + "px";
}
var y = mqr[j].ary[0].style;
if (parseInt(y.left, 10) + parseInt(y.width, 10) < 0) {
var z = mqr[j].ary.shift();
z.style.left = parseInt(z.style.left) + parseInt(z.style.width) * maxa + "px";
mqr[j].ary.push(z);
}
}
mqr[0].TO = setTimeout("mqRotate(mqr)", 20);
}
.marquee {
position: relative;
overflow: hidden;
text-align: center;
margin: 0 auto;
width: 100%;
height: 30px;
display: flex;
align-items: center;
white-space: nowrap;
}
#latest-news {
line-height: 32px;
a {
color: #555555;
font-size: 13px;
font-weight: 300;
&:hover {
color: #000000;
}
}
span {
font-size: 18px;
position: relative;
top: 4px;
color: #999999;
}
}
<div id="latest-news" class="marquee">
<span style="white-space:nowrap;">
<span> •</span>
one Lorem ipsum dolor sit amet
<span> •</span>
two In publishing and graphic design
<span> •</span>
three Lorem ipsum is a placeholder text commonly
</span>
</div>
Thank You sire.....I get it....What I need....
function start() {
new mq('latest-news');
mqRotate(mqr);
}
window.onload = start;
function objWidth(obj) {
if (obj.offsetWidth) return obj.offsetWidth;
if (obj.clip) return obj.clip.width;
return 0;
}
var mqr = [];
function mq(id) {
this.mqo = document.getElementById(id);
var wid = objWidth(this.mqo.getElementsByTagName("span")[0]) + 5;
var fulwid = objWidth(this.mqo);
var txt = this.mqo.getElementsByTagName("span")[0].innerHTML;
this.mqo.innerHTML = "";
var heit = this.mqo.style.height;
this.mqo.onmouseout = function () {
mqRotate(mqr);
};
this.mqo.onmouseover = function () {
clearTimeout(mqr[0].TO);
};
this.mqo.ary = [];
var maxw = Math.ceil(fulwid / wid) + 1;
for (var i = 0; i < maxw; i++) {
this.mqo.ary[i] = document.createElement("div");
this.mqo.ary[i].innerHTML = txt;
this.mqo.ary[i].style.position = "absolute";
this.mqo.ary[i].style.left = wid * i + "px";
this.mqo.ary[i].style.width = wid + "px";
this.mqo.ary[i].style.height = heit;
this.mqo.appendChild(this.mqo.ary[i]);
}
mqr.push(this.mqo);
}
function mqRotate(mqr) {
if (!mqr) return;
for (var j = mqr.length - 1; j > -1; j--) {
maxa = mqr[j].ary.length;
for (var i = 0; i < maxa; i++) {
var x = mqr[j].ary[i].style;
x.left = parseInt(x.left, 10) - 1 + "px";
}
var y = mqr[j].ary[0].style;
if (parseInt(y.left, 10) + parseInt(y.width, 10) < 0) {
var z = mqr[j].ary.shift();
z.style.left = parseInt(z.style.left) + parseInt(z.style.width) * maxa + "px";
mqr[j].ary.push(z);
}
}
mqr[0].TO = setTimeout("mqRotate(mqr)", 20);
}
.marquee {
position: relative;
overflow: hidden;
text-align: center;
margin: 0 auto;
width: 100%;
height: 30px;
display: flex;
align-items: center;
white-space: nowrap;
}
#latest-news {
line-height: 32px;
a {
color: #555555;
font-size: 13px;
font-weight: 300;
&:hover {
color: #000000;
}
}
span {
font-size: 18px;
position: relative;
top: 4px;
color: #999999;
}
}
<div id="latest-news" class="marquee">
<span style="white-space:nowrap;">
<span> •</span>
one Lorem ipsum dolor sit amet
<span> •</span>
two In publishing and graphic design
<span> •</span>
three Lorem ipsum is a placeholder text commonly
</span>
</div>

Javascript Adding pixels to current position of div

When the right arrow key is pressed I would like to increment the left position of a div by 10px using the style property. Here is my script and what I've tried so far:
document.onkeydown = KeyPressed;
function KeyPressed(k) {
var LeftBtn = 37;
var RightBtn = 39;
var UpBtn = 38;
var DownBtn = 40;
if (k.keyCode == RightBtn) {
document.getElementById("test").style.left = document.getElementById("test").style.left + 10px;
}
}
#test {
position: relative;
left: 0px;
width: 25px;
height: 80px;
background-color: black;
}
<div id="test"></div>
The style property of a DOM element is essentially a dictionary with string key-value pairs. It expects a CSS key, and a proper string value.
Your current code comes out as left: 10px10px and that doesn't make much sense for CSS.
In order for this to work, you'd have to regard the px.
document.onkeydown = KeyPressed;
function KeyPressed(k) {
var LeftBtn = 37;
var RightBtn = 39;
var UpBtn = 38;
var DownBtn = 40;
if (k.keyCode == RightBtn) {
var moveEl = document.getElementById("test"),
currLeft = parseInt(moveEl.style.left || 0);
moveEl.style.left = (currLeft + 10) + 'px';
}
}
#test {
position: relative;
left: 0px;
width: 25px;
height: 80px;
background-color: black;
}
<div id="test"></div>
Further reading and examples - HTMLElement.style
Remove px from 10.
if (k.keyCode == RightBtn) {
document.getElementById("test").style.left = document.getElementById("test").style.left + 10;
}
Try following way:
document.onkeydown = KeyPressed;
function KeyPressed(k) {
var LeftBtn = 37;
var RightBtn = 39;
var UpBtn = 38;
var DownBtn = 40;
if(k.keyCode == RightBtn) {
document.getElementById("test").style.left = parseInt(document.getElementById("test").style.left || 0) + 10 + 'px';
}
}

Categories

Resources