I'm trying to simulate a game through JS and HTML. My problem is that when I try and make it add the values it won't process it and change the value.
http://jsfiddle.net/rwybp41e/1/
I am trying to add all the Points and place them in the div with a class TotalPoints.
I have also tried using:
var div = document.getElementsByClassName('TotalPoints');
div.innerHTML = sum;
Thanks in advance
You can use each to loop over all the .Points and set the value inside .TotalPoints using text.
var total = 0;
$('.Points').each(function() {
total += parseInt($(this).text(), 10);
});
$('.TotalPoints').text(total);
Demo: https://jsfiddle.net/tusharj/rwybp41e/2/
Your targetting the wrong ID's and classes in your fiddle and you didn't include the jQuery library.
HTML:
<div id="TotalPoints"></div>
<div class="total-points">0</div>
CSS:
.total-points {
padding: 8px;
//background: blue;
width: 20px;
float:right;
margin-top: 4px;
}
Javascript:
// Add all "Points" class together
var sum = 0;
$('.Points').each(function () {
sum += parseFloat($(this).text());
});
$('.total-points').text(sum);
Here is a working demo:
http://jsfiddle.net/rwybp41e/3/
Since the data you're interested in is a reduction of a collection of points to a single total, you can calculate the total more functionally using Array.reduce:
$('.TotalPoints').text($('.Points')
.toArray()
.reduce(function (agg, point) {
return agg + parseInt($(point).text(), 10);
}, 0));
Working example: https://jsfiddle.net/rwybp41e/4/
Related
I've been trying to create a list of tags and separate them using commas. I'm using Webflow and sadly it's not possible in their cms.
I thought of a workaround where I would replace the commas with code using JavaScript.
Here's the code:
function tags() {
var tag = document.getElementById("tag__wrap").innerHTML;
str = tag.replace(/,/g, '</p><p class="tag__wrap">');
}
tags();
console.log(str);
For some reason the code works fine when I look it up in the console, but doesn't actually show anything on the actual website.
Any thoughts?
If your goal is to create multiple elements in place of the single element (that has the comma separated tags), then you need to manipulate the DOM. It is not enough to assign HTML to a string variable.
There are many ways to do this. Here is one:
function tags() {
var elem = document.getElementById("tag__wrap");
var tags = elem.textContent.match(/[^,\s]+/g) || [];
elem.textContent = tags.shift();
for (let text of tags) {
var newElem = elem.cloneNode();
newElem.textContent = text;
elem.insertAdjacentElement("afterend", newElem);
elem = newElem;
}
}
// Delay the change, so you can see before & after in the snippet
setTimeout(tags, 1000);
#tag__wrap {
background: lightblue;
display: inline-block;
margin: 5px;
padding: 3px 8px;
border-radius: 4px;
}
<p id="tag__wrap">algorithm,javascript,html,css</p>
My demo in JS Fiddle https://jsfiddle.net/dineshkanivu/5fp2sjgb/2/
I want to add content Dynamically to the id="myNote" in its 4th line.
click the button lines , you can see total number of lines. i want to add some html content after 4th line. How can i do this using jQuery
Snippet :
$(function() {
$("#getLines").click(function() {
var myheight = $("#myNote").height();
parseFloat($("#myNote").css("line-height"));
//$('#myNote').after('<button>button</button>');
alert(myheight);
});
});
#myNote {
width: 300px;
line-height: 1;
height: auto;
text-align: justify;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myNote">
Finally, designing the last sentence in this way has the added benefit of seamlessly moving the reader to the first paragraph of the body of the paper. In this way we can see that the basic introduction does not need to be much more than three or four
sentences in length. If yours is much longer you might want to consider editing it down a bit! Here, by way of example, is an introductory paragraph to an essay in response to the following question:
</div>
<button id="getLines">lines</button>
According to this post I wrote a little function to do this.
Surely there a more efficent way. But it works fine.
I wrap every word in an own span. After that I check the positions of all spans, get the line number and add a class with this line number to the span.
function insertTextAtLine(target,lineNumber,textInsert){
var words = target.text().split(' ');
var text = '';
$.each(words, function(i, w){
if($.trim(w)) text = text + '<span>' + w + '</span> ';
});
target.html(text);
var line = 0;
var prevTop = - parseFloat($("#myNote").css("line-height"));
$('span', target).each(function(){
var word = $(this);
var top = word.offset().top;
if(top != prevTop){
prevTop = top;
line++;
}
word.attr('class', 'line' + line);
});
var insert=$('<span />').text(textInsert);
target.find('.line'+lineNumber).first().prepend(insert);
};
Fiddle:https://jsfiddle.net/tye3czva/4/
I'm trying to do something which I thought was quite extremely simple, but not having much luck. I have two long lists of scores to compare, each pair sits in its own div. I'm on the lookout for a function which I could specify the div IDs, and have the different reflected in the third div. If the figure is positive, apply one class, and if negative, apply another.
<style>
.positive {
color: green;
}
.negative {
color: red;
}
</style>
<div id = "score">50</div>
<div id = "benchmark">30</div>
<div id = "diff"></div>
and in my javascript:
$(window).ready(function() {
$('#diff').html(diff);
});
var diff = calc("score", "benchmark");
function calc(divID1, divID2) {
div1 = document.getElementById(divID1);
metric = div1.innerHTML;
div2 = document.getElementById(divID2);
benchmark = div2.innerHTML;
c = Math.abs(a) - Math.abs(b);
// this is the difference here
return String(c);
};
I have D3 and JQuery loaded up. The numbers within the columns of divs are dynamically generated through other functions, so I can't hard code the styling.
You have some errors in your code. You can call calc function when the document is ready and handle the result there. I sum it up to this:
$(document).ready(function() {
//get the result of your calc function
var diff = calc("score", "benchmark");
//display the result and add class depend of the returning value
$('#diff').html(diff).attr("class", diff > 0 ? "positive" : "negative");
});
function calc(divID1, divID2) {
//get first number
var div1Num = parseInt($("#" + divID1).text(), 10);
//get second number
var div2Num = parseInt($("#" + divID2).text(), 10);
//make the calculation
var result = div1Num - div2Num;
//return the result
return result;
};
.positive {
color: green;
}
.negative {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="score">50</div>
<div id="benchmark">30</div>
<div id="diff"></div>
Another example with negative result:
$(document).ready(function() {
//get the result of your calc function
var diff = calc("score", "benchmark");
//display the result and add class depend of the returning value
$('#diff').html(diff).attr("class", diff > 0 ? "positive" : "negative");
});
function calc(divID1, divID2) {
//get first number
var div1Num = parseInt($("#" + divID1).text(), 10);
//get second number
var div2Num = parseInt($("#" + divID2).text(), 10);
//make the calculation
var result = div1Num - div2Num;
//return the result
return result;
};
.positive {
color: green;
}
.negative {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="score">10</div>
<div id="benchmark">30</div>
<div id="diff"></div>
Edit: You can replace parseInt with parseFloat according to your needs.
References
.attr()
You cannot calc() the diff between values of 2 elements when the DOM is not ready yet.
(Your current ready handler isn't performing the actual calculation but only appending the already miscalculated value to some element).
Try this instead:
$(document).ready(function() {
var diff = Math.abs($("#score").text()) - Math.abs($("#benchmark").text());
$('#diff').html(diff).addClass(diff > 0 ? 'positive' : 'negative');
});
Also, I changed your $(window).ready() to $(document).ready() instead.
You can use following statement in js to get expected output.
score = jQuery('#score').text();
benchmark = jQuery('#benchmark').text();
if(Math.abs(score) > Math.abs(benchmark))
{
jQuery('#diff').text('Positive');
jQuery('#diff').addClass('positive');
}
else
{
jQuery('#diff').text('Negative');
jQuery('#diff').addClass('negative');
}
You can check example on this link- http://jsfiddle.net/o3k6u99p/1/
I'm new to Javascript and I'm building a connect four game to learn about javascript. The problem is that I am unable to add margins between the 'o' so they all look clumped together.
I would like help adding margins or padding between the 'o's. Some thoughts are that I may need to add each row of 'o' in a table. However, I'm updating it through the javascript function. How do I get around that?
My javascript file
var first_row = ['o','o','o','o','o','o','o'];
onload = function ()
{
document.getElementById("row1").innerHTML = first_row;
}
HTML file
<h1 class="space" id="row1"></h1>
In pure javascript (not using jquery) with a for in loop than append spans with the '0's for styling.
var first_row = ['o','o','o','o','o','o','o'];
var row = document.getElementById('row1');
for (var i in first_row) {
var span = document.createElement('span');
span.innerHTML = first_row[i];
row.appendChild(span);
}
See here: http://jsfiddle.net/95JqK/17/
You'll have to encapsulate them into tags and put css rules on them.
A simple solution would be:
var first_row = ['<span>o</span>','<span>o</span>','<span>o</span>','<span>o</span>','<span>o</span>','<span>o</span>','<span>o</span>'];
onload = function ()
{
document.getElementById("row1").innerHTML = first_row;
}
And in a css file:
span {
margin: 0 10px 0 10px;
}
Perhaps you could use CSS on the class="space" elements
.space{
padding: 8px;
}
I have a bunch of divs on the screen.
What I want to do is, when I select any div, I want its zIndex to be always higher than all other divs.
In my application, i will need to do this repeatedly whenever I select a div, put it on top of others.
Is this possible using Javascript?
In some cases, you can bring an element to top without using CSS directly. If you place your DIVs to the body tag or under another parent element, you can re-append itself to the parent. JavaScript will move it to the last position in the child list which will bring the element in a "natural" way to the top.
Example:
myElement.parentNode.appendChild(myElement);
I used this trick for my custom context menu. Works without zIndex.
Yes, very much so.
HTML:
<div>foo</div>
<div>bar</div>
<div>bas</div>
Javascript:
//Collect all divs in array, then work on them
var all = document.selectElementsByTagName("div");
var prev = false;
for(i = 0; i < all.length; i++) {
all[i].onclick = function() {
all[i].style.position = 'relative'; //necessary to use z-index
if (prev) { prev.style.zIndex = 1; }
this.style.zIndex = 1000;
prev = this;
}
}
}
//Edit: Sorry, forgot a brace. Corrected now.
I recommend setting a variable at the beginning and incrementing that.
var top_z = 10;
function bringToTop(element)
{
element.style.zIndex = ++top_z;
}
(++top_z increments and then returns top_z)
I would do something like that:
var my_index = 100; //global var on page
function sendontop(div_id) {
if (typeOf(div_id)=="string") {
div_id=document.getElementById(div_id);
}
div_id.style.zIndex = my_index++;
}
on the object
<div id="bringmeup" onclick="sendontop(this);" >somecontent</div>
or otherwise you can also use
sendontop("bringmeup");
i came across this problem and solved like that
Hope it helps!
document.getElementById("mainactiondiv").firstElementChild.appendChild(bubble);
This worked for me (a modified version of Ben's solution, because it generated so many errors).
When you click the element, it should go to the top.
Hope it helps!
var allDivs = document.getElementsByTagName("div"); //Changed variable name to 'allDivs' because the name 'all' generated an error.
var prev = false;
for(ii = 0; ii < allDivs.length; ii++) { // changed the for variable to 'ii' instead of 'i' so i can find it easier (searching for 'i' will return avery instance of the letter i, even inside words, not just the variable, whereas ii is unique).
allDivs[ii].onclick = function() {
this.style.position = 'absolute'; //You have to have a position type defined. It doesn't matter what type, you just have to. If you define it elsewhere in your styles you can remove this.
if (prev) { prev.style.zIndex = 1; }
this.style.zIndex = 1000;
prev = this;
}
}
div {
padding:20px;
border:2px solid black;
border-radius:4px;
}
#d4 {
background-color:lightblue;
position:absolute;
top:30px;
left:20px;
}
#d3 {
background-color:lightgreen;
position:absolute;
top:70px;
left:20px;
}
#d2 {
background-color:yellow;
position:absolute;
top:30px;
left:70px;
}
#d1 {
background-color:pink;
position:absolute;
top:70px;
left:70px;
}
<html>
<div id="d1">div1</div>
<div id="d2">div2</div>
<div id="d3">div3</div>
<div id="d4">div4</div>
</html>
This is what worked for me. It traverses all elements on the page and increases the max z-index by 1.
Note that this method still works when there have been dynamically increased z indices on the page as well:
function bring_to_front(target_id) {
const all_z = [];
document.querySelectorAll("*").forEach(function(elem) {
all_z.push(elem.style.zIndex)
})
const max_index = Math.max.apply(null, all_z.map((x) => Number(x)));
const new_max_index = max_index + 1;
document.getElementById(target_id).style.zIndex = new_max_index;
}
Simply pass-in the id of the element you wish to bring to the front.