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;
}
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 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/
Is it somehow possible to get a style property from a css class that is not used anywhere?
I'd like to read for example the color property that I want to apply to an animation with jquery ui but I want to avoid duplicating them again in the js code.
Let's say I have this:
.default-style {
color: red;
}
.disabled-style {
color: gray;
}
.current-style {}
<span class="current-style">Hello world!</span>
Now I would like to set the .default-style color to the .current-style and then animate the color from the .default-style to the .disabled-style and back on click but I don't know how to get them without creating a hidden element.
var currentColor = ""; // I'm stuck here. Get color from css class?
$("span.abc").animate({ color: currentColor });
You can cheat by creating an element, applying the class, adding the element to the document, getting its color, then removing it. If this is all done in one code block, the user will never see the element:
var div = $("<div>").addClass("default-style").appendTo(document.body);
var color = div.css("color");
div.remove();
Alternately, you can loop through document.styleSheets in the document, and loop through the rules of each stylesheet looking for the one that uses that simple class selector, then look at the styles that rule defines.
Gratuitous snippet: ;-)
var div = $("<div>").addClass("default-style").appendTo(document.body);
var color = div.css("color");
div.remove();
$("<p>The color is: " + color + " (the color of this paragraph)</p>").css("color", color).appendTo(document.body);
.default-style {
color: red;
}
.disabled-style {
color: gray;
}
.current-style {}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span class="current-style">Hello world!</span>
Side note: jQuery's animate function doesn't animate colors natively, you need to add a plugin to do it (jQuery UI bundles one, but if you're not using jQuery UI, you can just use one of the plugins that does this, such as this one, directly).
Correct Way ! Without cheating the document
var currentColor;
var styleSheets = document.styleSheets;
for(var j=0; !currentColor && j<styleSheets.length; j++)
{
var styleSheet = styleSheets[j];
var cssprops = styleSheet.cssRules || styleSheet.rules; // .rules is for older IE
for (var i = 0; i < cssprops.length; i++) {
if(cssprops[i].selectorText == '.default-style');
currentColor = cssprops[i].style.getPropertyCSSValue('color').cssText;
}
}
$("span.abc").animate({ color: currentColor });
Reference From https://developer.mozilla.org/en-US/docs/Web/API/document.styleSheets
I'm not a jquery developer and I'm not much of a javascript developer too. I'm trying a quick hack that makes my life simple. This is the page:
What I'm trying to accomplish is:
I want to add a div of mathjax_preview class after each textarea element on the page.
The inner.HTML of that div must the text inside the corresponding textarea
But it doesn't seem to work.
I've the following javascript code in js/1.js and it is being loaded when the page loads:
var preview_number = 0;
$("textarea").each(function() {
var d = $(this).next();
if (!d.hasClass("mathjax_preview")) {
preview_number++;
var d = $("<div class='mathjax_preview' " +
"style='padding: 5px; color: black; background: #eee; border: 1px solid #888;float:left;'" +
"></div>");
d.attr("id", "mathjax_preview_" + preview_number);
d.insertAfter(this);
}
d.text($(this).val());
MathJax.Hub.Queue([ "Typeset", MathJax.Hub, d.attr("id") ]);
});
EDIT:
I just inserted following snippet in the beginning of the above file:
var preview_number = 0;
var elements = document.getElementsByTagName("textarea");
alert(elements.length);
Its alerting 0. How come?
Try the following (I've not tested this as it's straight off the top of my head):
$(document).ready(function() {
var preview_number = 0;
$("textarea").each(function() {
preview_number++;
var d = document.createElement("div");
$(d).attr("id", "mathjax_preview_" + preview_number);
$(d).addClass("mathjax_preview");
$(d).css("padding", "5px");
$(d).css("color", "black");
$(d).css("background", "#eee");
$(d).css("border", "1px solid #888");
$(d).css("float", "left");
$(d).html($(this).val());
MathJax.Hub.Queue([ "Typeset", MathJax.Hub, $(d).attr("id") ]);
$(this).append(d);
});
});
The variable textarea does not exist. Use this instead:
d.insertAfter(this);
You have no textarea variable defined.
d.insertAfter(textarea);
I beleive you can use $(this) reference.
d.insertAfter($(this));
What is textarea in d.insertAfter(textarea);?
It seems to be d.insertAfter($(this));.
The alert message is showing you zero because you have not put your javascript file at the end of page nor you have used ready callback.
To use ready callback add the code as follows
$(document).ready(function() {/*add your javascript code here */});