how to get clientWidth of firstChild - javascript

I want to get client width of firstChild
Css
.ot{width:100px;height:200px}
JS
var ra = document.getElementsByClassName("r")[0];
var n = ra.firstChild.clientHeight;
var ca = n ;
HTML
<div class="r"><div class="ot"></div></div>
want to get the height of ot through class r, why not ca is showing 200

Use firstElementChild instead of firstChild.

It is working. You can read more about HTML DOM Here. http://www.w3schools.com/jsref/dom_obj_all.asp
var ra = document.getElementsByClassName("r")[0];
var n = ra.firstChild.clientHeight;
var ca = n ;
alert(ca);
.ot{width:100px;height:200px}
<div class="r"><div class="ot"></div></div>

Try to add this toy your code, should show a current height of desired div:
HTML:
<p id="demo"></p>`
<button onclick="myFunction()">Try it</button>
JavaScript:
function myFunction() {
var ra = document.getElementsByClassName("r")[0];
var n = ra.firstChild.clientHeight;
document.getElementById("demo").innerHTML = n;
}
CSS:
.ot{width:100px;height:200px}

Try with the working snippet, i have modified your code , just Run this snippet , you can check with your first child height and width
var ra = document.getElementsByClassName('r')[0];
var n = ra.getElementsByTagName('div')[0];
alert( 'width is =' + n.clientWidth + ' , and height = ' + n.clientHeight );
.ot{
width:100px;
height:200px
}
<div class="r">
<div class="ot"></div>
</div>

Related

More efficient way to create a new element JS(Dunno what the title should called)

Im new to JavaScript, I'm using vanilla js , html and css to survey website where user can add question, and option as well, when they click a button it will create a container which they can fill with the 'tag:textarea'. I'm using the 'createElement()', 'setAttribute()' method for creating a new container. But since each container has so many nested nodes or components, I have write a tons of boilerplate code to create a container, plus I have to change the id of some element with the nested 'Hell' , It become so hard to managed. My html code is Below:
<div id="create-question-container-id" class="create-question-container" >
<div id="create-question-textarea-container-id_0" class="create-question-textarea-container">
<textarea id="create-question-textarea-id"
name="textareaquestion" class="create-question-textarea"
cols="50" row="1" style="font-size: 20pt;">
Untitled Question
</textarea>
<div id="create-answer-textarea-container-id-0" class="create-answer-textarea-container">
<div id="create-answer-N-container-id-0-0" class="create-answer-N-container">
<div class="create-qeuestion-radio-outer-circle" >
<div class="create-qeuestion-radio-innner-circle"></div>
</div>
<textarea id="opt1" name="textareaopt" class="create-answer-textarea"
placeholder="opt1" style="font-size: 14pt;">
</textarea>
</div>
</div>
<button onclick="addOption()" class="create-add-answer-btn" >
Add Option
</button>
</div>
</div>
<div class="create-main-container-submit-button">
<button onclick="clonecontainer()" class="create-main-submit-btn" >
Submit
</button>
</div>
And this is the Javascript Code from hell:
var answer_container = document.getElementsByClassName('create-answer-textarea-container');
//increment this one
var answer_container_id = document.getElementById('create-answer-textarea-container-id-0');
var lastChildAnswer = answer_container[answer_container.length - 1];
var asnwer_container_list = answer_container_id.childNodes[answer_container.length];
//id of container wrapping around the question and the options named questionasnwcontain(this need to increment id)
var question_answer_container_list = document.getElementById('create-question-textarea-container-id_0')
//id of container wrapping around the questionasnwcontain(main container)
var all_question_asnwer_container = document.getElementById('create-question-container-id');
var all_question_asnwer_container_class_Name = document.getElementsByClassName('create-question-container');
var all_counter = all_question_asnwer_container.childElementCount -1;
function clonecontainer() {
var dashed_delimeter = '-';
var lastChildContainer = answer_container_id.lastElementChild.getAttribute('id')
var trimlastChild = answer_container_id.lastElementChild.lastElementChild.getAttribute('id')
var delimeter = 't'
var trimlastChildSubString = trimlastChild.split(delimeter);
var lastChildString = trimlastChildSubString[1]
//split lastChildContainer
var splitted_lastChildContainer = lastChildContainer.split(dashed_delimeter)[5];
var new_id_spliited_lastChildContainer = 'create-answer-N-container-id-' + ((parseInt(splitted_lastChildContainer)) + (all_question_asnwer_container.childElementCount -1) ) + '-0';
//get the cloned container's child id for incremental
var last_main_container_child = all_question_asnwer_container.lastElementChild.getAttribute('id');
var trimlast_id = seperateWithDelimeter(last_main_container_child);
var trimlast_new_id ='_' + (parseInt(trimlast_id[1]) + (all_question_asnwer_container.childElementCount -1) );
console.log(trimlast_new_id)
//(fixed)
var last_cloned_delimeter = '_';
var last_cloned_container = all_question_asnwer_container.childNodes[all_question_asnwer_container_class_Name.length].getAttribute('id')
var splitted_cloned_container = last_cloned_container.split(last_cloned_delimeter);
var new_splitted_cloned_container_id = 'create-answer-textarea-container-id-' + ((parseInt(splitted_cloned_container[1])) + (all_question_asnwer_container.childElementCount )) ;
console.log(new_splitted_cloned_container_id)
//new div fr asnwer container
var new_div_fr_answer_container_id = document.createElement('div');
new_div_fr_answer_container_id.setAttribute('class' , 'create-question-textarea-container');
new_div_fr_answer_container_id.setAttribute('id' ,'create-question-textarea-container-id' + trimlast_new_id)
console.log(new_div_fr_answer_container_id)
//new question text area
var new_textarea_fr_create_question_textarea_id = document.createElement('textarea');
new_textarea_fr_create_question_textarea_id.setAttribute('class' , 'create-question-textarea');
new_textarea_fr_create_question_textarea_id.setAttribute('id' , 'create-question-textarea-id')
new_textarea_fr_create_question_textarea_id.setAttribute('cols' , 50);
new_textarea_fr_create_question_textarea_id.setAttribute('row' , 1);
new_textarea_fr_create_question_textarea_id.style.fontSize = '20pt';
//new for option text area wrrapeer
var new_option_text_area_wrapper = document.createElement('div');
new_option_text_area_wrapper.setAttribute('class' , 'create-answer-textarea-container');
new_option_text_area_wrapper.setAttribute('id' , new_splitted_cloned_container_id);
var new_option_N_text_area_wrapper = document.createElement('div');
new_option_N_text_area_wrapper.setAttribute('class' , 'create-answer-N-container');
new_option_N_text_area_wrapper.setAttribute('id', new_id_spliited_lastChildContainer);
var new_checkbox_inner = document.createElement('div');
new_checkbox_inner.setAttribute('class' , 'create-qeuestion-radio-inner-circle');
//create Element for checkBox outerCircle
var new_checkbox = document.createElement('div');
new_checkbox.setAttribute('class' , 'create-qeuestion-radio-outer-circle');
//append innerCircle
new_checkbox.appendChild(new_checkbox_inner);
var new_answer = document.createElement('textarea');
new_answer.setAttribute('name' , 'textareaopt');
new_answer.setAttribute('id' , 'opt'+ (parseInt(lastChildString) + 1));
new_answer.setAttribute('class' , 'create-answer-textarea');
new_answer.setAttribute('placeholder' , 'opt'+ (parseInt(lastChildString) + 1))
new_answer.style.fontSize = "14pt";
new_option_N_text_area_wrapper.appendChild(new_checkbox);
new_option_N_text_area_wrapper.appendChild(new_answer);
new_option_text_area_wrapper.appendChild(new_option_N_text_area_wrapper);
new_div_fr_answer_container_id.appendChild(new_textarea_fr_create_question_textarea_id);
new_div_fr_answer_container_id.appendChild(new_option_text_area_wrapper);
all_question_asnwer_container.appendChild(new_div_fr_answer_container_id);
}
All of them are just the repetitive methods. So my question is, is there a more efficient way of doing this or is there like a class that I can use to make it more manageable.
You have several options, two of which are:
If you don't mind parsing HTML each time (and parsing HTML is really fast on modern browser), you can use insertAdjacentHTML instead, perhaps with a template literal so you can embed newlines easily and use ${x} syntax for embedded values:
all_question_asnwer_container.insertAdjacentHTML("beforeend", `<div>
(etc.)
</div>`);
You can use a template element in your HTML that you clone (via cloneNode) as needed. Here's the cloning part of MDN's example from the linked page
var tbody = document.querySelector("tbody");
var template = document.querySelector('#productrow'); // The template element
// Clone the new row and insert it into the table
var clone = template.content.cloneNode(true);
var td = clone.querySelectorAll("td");
td[0].textContent = "1235646565";
td[1].textContent = "Stuff";
tbody.appendChild(clone);
const
btAdd = document.querySelector('button#bt-add')
, container = document.querySelector('div#container')
, builder =
{ ref_id : 0
, newDiv()
{
let sub_id = 0
, div = document.createElement('div')
;
div.id = ++this.ref_id
div.innerHTML = `
<div id="bla-bla-id_${this.ref_id}" class="xxzw">
<em> text areas: </em><br>
<textarea id="opt${this.ref_id}-${++sub_id}" placeholder="txt-area ${this.ref_id}-${sub_id} "></textarea><br>
<textarea id="opt${this.ref_id}-${++sub_id}" placeholder="txt-area ${this.ref_id}-${sub_id} "></textarea>
</div>`
container.appendChild(div)
}
}
btAdd.onclick = e =>
{
builder.newDiv()
}
div#container {
margin : 1em;
width : 20em;
}
div#container > div {
margin : .8em 0;
padding : .2em;
border : 1px solid lightblue;
}
em {
font-size : .7em;
font-weight : bold;
}
textarea {
width : 90%;
}
<button id="bt-add">add</button>
<div id="container"> </div>

Scaling image using variables

Im trying to scale an image using variables rather than a set in stone scale. I know using "scale(0.5,0.5)" works but I want to do something like "scale(x,y)" so the scale factor changes depending on what variables x and y are, However when I try doing this, the image will no longer scale like it did when it had a set scale factor. How can I solve this? Thanks for any help. Here's an example of what I mean.
<!DOCTYPE html>
<html>
<body>
<img id="myImg" src="img_pulpit.jpg">
<button onclick="myFunction()">Try it</button>
<script>
var a = document.getElementById("myImg");
var d = 5
var e = 10
var f = d/e
var g = 10
var h = 30
var i = g/h
function myFunction() {
document.getElementById("myImg").style.WebkitTransform = "scale(f, i)";
}
</script>
</body>
</html>
Just use string concatenation ("scale(" + f + ", " + i + ")") or string interpolation (`scale(${f}, ${i})`).
function myFunction() {
document.getElementById("myImg").style.WebkitTransform = "scale(" + f + "," + i + ")";
}
You need to use concat the value of f and i
document.getElementById("myImg").style.WebkitTransform = "scale("+f+","+i+")";
<!DOCTYPE html>
<html>
<body>
<img id="myImg" src="https://lh3.googleusercontent.com/gN6iBKP1b2GTXZZoCxhyXiYIAh8QJ_8xzlhEK6csyDadA4GdkEdIEy9Bc8s5jozt1g=w300">
<button onclick="myFunction()">Try it</button>
<script>
var a = document.getElementById("myImg");
var d = 5
var e = 10
var f = d/e
var g = 10
var h = 30
var i = g/h
function myFunction() {
document.getElementById("myImg").style.WebkitTransform = "scale("+f+","+i+")";
}
</script>
</body>
</html>

What's wrong with this code to move css elements with javascript?

I am trying to move an element with javascript. I searched for a while and I think that this code should do the trick... but it does not, and I get no errors in the Console... anybody can help?
<html><body>
<script>
function move1(){
var cusid_ele = document.getElementsByClassName('zzz');
for (var i = 0; i < cusid_ele.length; ++i) {
var item = cusid_ele[i];
var x=item.style.top;
x+=10;
item.style.top=x;
}
}
function move2(){
var cusid_ele = document.getElementsByClassName('zzz');
for (var i = 0; i < cusid_ele.length; ++i) {
var item = cusid_ele[i];
var x=item.style["top"];
x+=10;
item.style["top"]=x;
}
}
function move3(){
var cusid_ele = document.getElementsByClassName('zzz');
for (var i = 0; i < cusid_ele.length; ++i) {
var item = cusid_ele[i];
var x=item.style["top"];
x+=10;
item.style["top"]=x+'px';
}
}
</script>
<input type=button onclick="move1();" value="Move (1st way, with .top=x)!">
<input type=button onclick="move2();" value="Move (2nd way, with [top]=x)!">
<input type=button onclick="move3();" value="Move (3rd way, with [top]=xpx)!">
<h3 class=zzz >Move me! (no inline style)</h3>
<h3 class=zzz style="top: 50px;">Move me! (with inline style)</h3>
</body></html>
By the way, I tried both FF and Chrome...
-- Accepted solution, I write it here so one can have a working example (thank you Adeneo!):
<script>
function move1(){
var cusid_ele = document.getElementsByClassName('zzz');
for (var i = 0; i < cusid_ele.length; ++i) {
var item = cusid_ele[i];
var x = parseInt( item.style.top, 10 );
x+=10;
item.style.top=x+'px';
}
}
</script>
<input type=button onclick="move1();" value="Move!">
<h3 class=zzz >I cant move! (no css positioning)</h3>
<h3 class=zzz style="position: relative; top: 50px;">I can move! (with css positioning)</h3>
</body></html>
This
var x=item.style["top"];
returns the string 300px etc, so
x += 10;
ends up being
300px10
so replace
var x=item.style.top;
with
var x = parseInt( item.style.top, 10 );
the same goes for setting styles
element.style.top = x + 'px';
You'll have to use a string with units, and to make the CSS actually do something, the elements must be positioned
FIDDLE

How do i make text = integers

I have a problem that i've been trying to solve for days.
I was wondering if it was possible to let a text turn into an integer.
So everytime i write in my textarea("ALC") Load, then on the textarea("MLC") 001. And also including 1-15 to binary at the end
E.g. Load #1 will show 001 0 00001
<html>
<head>
<center><font size ="24"> Simple Assembler </font></center>
<script type="text/javascript">
var Load = "001";
var Store = "010";
var Add = "011";
var Sub = "100";
var Equal = "101";
var Jump = "110";
var Halt = "111";
var # = "1";
</script>
</head>
<body>
<form name="AssemblyLanguagecode" action="" method="">
<textarea Id="ALC" style="resize:none;width:35%;height:35%;margin-left:15%" value="">Insert Assembly Language Code</textarea>
<textarea Id="MLC" style="resize:none;width:35%;height:35%;" ReadOnly="True">Machine Language Code will be displayed here</textarea><br />
<p align="center"><input type="button" value="Assemble" onclick="ALCtoMLC()";" /></p>
</form>
<script type= "text/javascript">
function ALCtoMLC() {
var x = document.getElementById("ALC").value;
x = parseInt(x);
var bin = x.toString(2);
document.getElementById("MLC").innerHTML = bin;
}
</script>
</body>
</html>
I think I understand what you want to do. You want to use what you type into "ALC" as a key to a value. In that case, you want to use a javascript object and assign the instructions as keys, and the binary to the value. Such as
var instruction_set = {
"Load" : "001",
"Store" : "010",
"Add" : "011",
"Sub" : "100",
"Equal" : "101",
"Jump" : "110",
"Halt" : "111"
}
function ALCtoMLC() {
var x = document.getElementById("ALC").value;
x = instruction_set[x];
}
Updated:
Try this:
<html>
<head>
<center><font size ="24"> Simple Assembler </font></center>
<script type="text/javascript">
var Load = "001";
var Store = "010";
var Add = "011";
var Sub = "100";
var Equal = "101";
var Jump = "110";
var Halt = "111";
var # = "1";
</script>
</head>
<body>
<form name="AssemblyLanguagecode" action="" method="">
<textarea Id="ALC" style="resize:none;width:35%;height:35%;margin-left:15%" value="">Insert Assembly Language Code</textarea>
<textarea Id="MLC" style="resize:none;width:35%;height:35%;" ReadOnly="True">Machine Language Code will be displayed here</textarea><br />
<p align="center"><input type="button" value="Assemble" onclick="ALCtoMLC();" /></p>
</form>
<script type= "text/javascript">
var Dict = { 'Load':"001",'Store':"010"}; //example Instruction set
function ALCtoMLC() {
var x = document.getElementById("ALC").value;
var instrType = '';
for (var instr in Dict){
var ind = x.indexOf(instr);
if( ind > -1){
instrType = instrType + Dict[instr];
x = x.replace(instr,'');
}
}
console.log(instrType, "::", x);
x = parseInt(x);
var bin = x.toString(2);
bin = instrType + bin;
document.getElementById("MLC").innerHTML = bin;
}
</script>
</body>
</html>
Lets say you have a way to get the tokens. Then your function should look like this
var tokens = getTokens( document.getElementById("ALC").value ) ;
var vocabulary = { "Load" : "001" , " ... " } ;
var output = []
var i = 0;
var tokensLength = tokens.length;
for ( ; i < tokensLength; i++){
var token = tokens[i];
if ( isNaN(token) && typeof(vocabulary[token]) != "undefined" ){
output.push( vocabulary[token] );
}else if ( !isNaN(token) ){
output.push( Number(token).toString(2) );
}else{
console.log(["error : unknown token ", token]);
}
}
document.getElementById("MLC").value = output.join(" ");
I see in the question that Load translates to 0010 and not 001, so I would simply modify the vocabulary.
Explanation :
I assume you have a way to split the input to tokens. (the ALC syntax is still unclear to me).
The tokens array will contains, for example ["Load","#","15", "Load","#","16"] and so on.
Then I loop on the tokens.
If a token is a number - I turn it to binary string.
If the token is translatable by vocabulary - I switch it to its binary representation.
Otherwise I print an error.
NOTE: if output should be padded with "0" - even though it is not specified in the question, I would use "0000".substring(n.length) + n
This is how I would do it:
var opcodes = {
Load: 1,
Store: 2,
Add: 3,
Sub: 4,
Equal: 5,
Jump: 6,
Halt: 7
};
var assemblyTextarea = document.querySelector("#assembly");
var machineTextarea = document.querySelector("#machine");
document.querySelector("#assemble").addEventListener("click", function () {
var instruction = assemblyTextarea.value.split(" ");
var operand =+ instruction[1].slice(1);
var opcode = instruction[0];
var code = opcodes[opcode] * 16 + operand;
var bits = ("0000000" + code.toString(2)).slice(-8);
machineTextarea.value = bits;
}, false);
See the demo here: http://jsfiddle.net/fs5mb/1/
The input should be formatted as follows: Load #15

struggling with creating asterisks in Javascript

I've been struggling with this for some time now. What I wanted to create is to output a triangle of asterisks based on user's input. Let say user entered size 5, it would look something like this:
*
**
***
****
*****
My HTML looks like:
<p>
Size: <input type="text" id="size">
<input type="button" value="Draw" onclick="draw()">
</p>
<pre id="output">
</pre>
In my Javascript, I have:
function draw()
{
var size = customJS.get ( "size" ); //I have a custom library where it get the Id from HTML
var theTriangle = makeTriangle( size.value ); //sending in the size
customJS.set ("output", theTriangle); //will set theTriangle to display to "output" in HTML
}
function makeTriangle( theSize )
{
var allLines = ""; // an empty string to hold the entire triangle
for ( var i = 0; i <= size; i++) // this loop size times
{
var oneLine = createLine ( i <= size ); // amount of asterisks for this line
allLines += oneLine;
}
return allLines;
}
function createLine ( length )
{
var aLine = ""; // an empty string to hold the contents of this one line
for ( var j = 0; j <= i; j++ ) //this loop length times
{
aLine += '*';
}
return aLine + "<br>";
}
anyone have any tip on how I go about this? thank you so much!
Newlines in HTML normally display as spaces, but you want them to show as newlines. The pre tag makes newlines actually appear as new lines, so wrap the output in a pre tag:
customJS.set ("output", "<pre>" + theTriangle + "</pre>");
Also, you're calling createLine like this:
var oneLine = createLine ( i <= size );
i <= size yields a boolean (true or false) rather than a number. You probably mean to just pass it i:
var oneLine = createLine ( i );
Additionally, you're setting size like this:
var size = customJS.get = ( "size" );
You probably want to drop the second equals, since as is, it sets the variable size to the string "size".
And finally, you've got a few variables wrong: in makeTriangle, you're looping size times, but size is undefined; you probably meant theSize. In createLine, you're looping i times, but i is undefined; you probably meant length.
With all that, it works.
There were several bugs in your code. For example using theSize instead size as parameter in the function makeTriangle(), using i instead of length in the createLine() function in the for loop condition.
Another one was:
use
return aLine + "<br/>";
instead of
return aLine + "\n";
The working solution for your code can be found in this jsFiddle: http://jsfiddle.net/uwe_guenther/wavDH/
And below is a copy of the fiddle:
index.html
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<p>Size:
<input type="text" id="sizeTextField">
<input id='drawButton' type="button" value="Draw">
<div id='output'></div>
</p>
<script src='main.js'></script>
</body>
</html>
main.js
(function (document) {
var drawButton = document.getElementById('drawButton'),
sizeTextField = document.getElementById('sizeTextField'),
output = document.getElementById('output');
function makeTriangle(size) {
var allLines = '';
for (var i = 0; i <= size; i++) {
var oneLine = createLine(i); // amount of asterisks for this line
allLines += oneLine;
}
return allLines;
}
function createLine(length) {
var aLine = '';
for (var j = 0; j <= length; j++) {
aLine += '*';
}
return aLine + "<br/>";
}
drawButton.onclick = function () {
output.innerHTML = makeTriangle(sizeTextField.value);
};
})(document);
You can leverage some JavaScript tricks to make the code a bit more terse:
<div style="text-align: center">
<label>Size:
<input type="text" id="size" value="5">
</label> <pre id='output'></pre>
</div>
<script>
var size = document.getElementById('size'),
output = document.getElementById('output');
function update() {
var width = +size.value, // Coerce to integer.
upsideDown = width < 0, // Check if negative.
width = Math.abs(width), // Ensure positive.
treeArray = Array(width).join('0').split('0') // Create an array of 0s "width" long.
.map(function(zero, level) { // Visit each one, giving us the chance to change it.
return Array(2 + level).join('*'); // Create a string of *s.
});
upsideDown && treeArray.reverse(); // If width was negative, stand the tree on its head.
output.innerHTML = treeArray.join('\n'); // Join it all together, and output it!
}
size.onkeyup = update;
update();
size.focus();
</script>
http://jsfiddle.net/mhtKY/4/

Categories

Resources