Add multiple label dynamically in html page using javascript - javascript

I used following code for adding label dynamically.
var array_resp=[CorrectStreet,CorrectCity,CorrectState,CorrectZip];
// var stateName=map.getKey(CorrectState);
if(array_resp.length > 0) {
var answers = [];
for(var i = 0; i <= array_resp.length - 2; i++) {
answers[i] = document.createLabel({
color : '#000',
text : array_resp[i],
top : top,
left : '30 px',
width : '420 px',
height : '100 px',
visible : 'true',
backgroundColor : 'white',
font : FontNormal,
});
document.body.appendChild(answers[i]);
}
}
in html:-
<button onclick="myFunction()">Try it</button>
But it doesn't give correct output,when I am click on button.
Why it happen? Can someone help me please.

Some issues in your code:
There are no function of createLabel for creating LABEL element
To assign the style / properties in wrong way, never in object type
There is no SPACE between 30 and px for left, width & height.
Try this:
<body>
<script>
function myFunction(){
var array_resp=['CorrectStreet','CorrectCity','CorrectState','CorrectZip'];
// var stateName=map.getKey(CorrectState);
if(array_resp.length > 0) {
for(var i = 0; i <= array_resp.length - 2; i++) {
var label = document.createElement('label');
label.style.color = '#000';
label.style.top = 'top';
label.style.left = '30px';
label.style.width = '420px';
label.style.height = '100px';
label.style.visible = 'true';
label.style.backgroundColor = 'white';
label.style.font = 'FontNormal';
label.innerHTML = array_resp[i];
document.body.appendChild(label);
}
}
}
</script>
<button onclick="myFunction()">Try it</button>
</body>

Related

How to make fontSize of text area increase by 2 in javascript?

I have textarea that I want to add 2 to its text font size every time a button is clicked. I wrote this code but not working.
My HTML code is
function makebold() {
alert(document.getElementById("input-text").style.fontSize);
var currentfontsize = document.getElementById("input-text").style.fontSize;
console.log(currentfontsize);
var current = parseInt(currentfontsize);
console.log(current);
var updatedfontsize = current + 2;
console.log(updatedfontsize);
var newfont = updatedfontsize;
console.log(newfont);;
document.getElementById("input-text").style.fontSize = newfont;
}
<fieldset>
<legend>Text</legend>
<textarea name="input-text" id="input-text" cols="30" rows="4"></textarea>
</fieldset>
<fieldset>
<legend>Decoration</legend>
<button id="button1" onclick="makebold()">Bigger Decorations!</button><br>
<input type="checkbox" onclick="displayalert()" name="bling" id="bling" value="Bling">Bling
</fieldset>
Can anyone please help?
Use this way to get the font size:
var currentfontsize = window.getComputedStyle(document.getElementById("input-text")).fontSize;
And update your last line
document.getElementById("input-text").style.fontSize = newfont+'px';
You are not adding px to the font. Without px it won't work.
Working Fiddle
https://jsfiddle.net/3napv795/
function increaseFont(elem, inc) {
const val = window.getComputedStyle(elem).getPropertyValue("font-size"); // gets font-size in string format
const currentSize = parseFloat(val); // removes 'px'
elem.style.fontSize = currentSize + inc + "px"; // set new size by adding increment to current font size
}
Usage:
const button = document.getElementById("button1");
button.addEventListener("click", () => increaseFont(button, 2))
Adding an initial font-size will solve the problem:
function makebold(){
alert(document.getElementById("input-text").style.fontSize);
//add initial font-size
document.getElementById("input-text").style.fontSize = '10px';
var currentfontsize = document.getElementById("input-text").style.fontSize;
console.log(currentfontsize);
var current = parseInt(currentfontsize);
console.log(current);
var updatedfontsize = current + 2;
console.log(updatedfontsize);
var newfont = updatedfontsize;
console.log(newfont);;
document.getElementById("input-text").style.fontSize = newfont;
}
Correcting your code while updating to a newer syntax ....
JS
const textarea = document.getElementById("input-text");
function makebold() {
let fontUnit = "px"; // setting a unit for font size
let increment = 2; // increase the font size by 2 px/rem/em etc ..
// Getting current font size
let currentfontsize = window.getComputedStyle(textarea).fontSize;
currentfontsize = parseInt(currentfontsize);
// getting final value
const updatedfontsize = currentfontsize + increment + fontUnit;
textarea.style.fontSize = updatedfontsize;
}

Closure in javascript seems not working properly

I've the following code and it is not working properly. My aim is whenever i click the 'font size' such as 12, 14 and 16, then, the font size and its color need to change accordingly and simultaneously. But, it is not working as expected, Any help?
<body>
<p>Some paragraph text</p>
<h1>some heading 1 text</h1>
<h2>some heading 2 text</h2>
12
14
16
<script type="text/javascript">
function makeSizer(size) {
return function(oclor) {
document.body.style.fontSize = size + 'px';
document.body.style.color = oclor;
};
}
var a= "green", b= "blue", c="red";
var size12 = makeSizer(12)(a);
var size14 = makeSizer(14)(b);
var size16 = makeSizer(16)(c);
document.getElementById('size-12').onclick = size12;
document.getElementById('size-14').onclick = size14;
document.getElementById('size-16').onclick = size16;
</script>
</body>
This is where your problem is.
You're setting the variables to the result of the anonymous function. Which is undefined.
Then you're setting the onclick events to the results.
var size12 = makeSizer(12)(a);
var size14 = makeSizer(14)(b);
var size16 = makeSizer(16)(c);
document.getElementById('size-12').onclick = size12;
document.getElementById('size-14').onclick = size14;
document.getElementById('size-16').onclick = size16;
What you want is to set the variables to functions as well. Such as:
var size12 = function(){makeSizer(12)(a)};
Is there a reason why you can't do the following?
Edit: Sorry, missed the return function. Thanks for pointing that out #DanielKnippers
function makeSizer(size,oclor) {
return function () {
document.body.style.fontSize = size + 'px';
document.body.style.color = oclor;
};
}
var size12 = makeSizer(12,'green');
var size14 = makeSizer(14,'blue');
var size16 = makeSizer(16,'red');

How do you make a Variable decrease every time a button is clicked by the value of another Variable in JavaScript?

I'm trying to make a button that decreases a variable-defined number by another variable-defined number every time it's clicked.
Example:
[Button]
Number: 500
*Button Clicked
[Button]
Number: 475
*Button Clicked Again
[Button]
Number: 450
And so on..
I'd love to give code and what not but I can't even get it close to working so that would be useless..
The code could look like this:
var count = 500;
var decrementAmount = 25;
function reduceVariable() {
count -= decrementAmount;
}
Then, just call reduceVariable from your button click.
See this jsfiddle
HTML:
<div id="text">500</div>
<p><input type="button" id="button" value="Decrease me"></p>
Javascript:
var oButton = document.getElementById("button");
var oText = document.getElementById("text");
var count = 500;
oButton.addEventListener('click', function(i, a) {
oText.innerHTML = count -= 25;
}, false);
Try this as example:
HTML:
<span id="spnTest">500</span>
<button id="btnTest" >Decrease</button>
Javascript:
var ratio = 25;
var totalValue = 500;
function decrease(){
if(totalValue == 0) return;
totalValue -= ratio;
document.getElementById('spnTest').innerHTML = totalValue;
}
document.getElementById('btnTest').onclick = function(){ decrease(); }
Here is demo

how to stop moving text box at specific point?

i'm developing a web site i want a div to move when a user click on the text box and i need to stop that div below the clicked text box. i have tried
var index = event.target.id
but it didn't work i 'm using flowing javascript function
<script type="text/javascript">
var cmdStr = window.location.search;
cmdStr = (cmdStr.indexOf("menu_id")>-1)?cmdStr.substring(cmdStr.indexOf("=")+1,cmdStr.length):"";
var isNS6 = (navigator.userAgent.indexOf("Mozilla")>-1 && navigator.userAgent.indexOf("Gecko")>-1)?true:false;
var isIE = (navigator.userAgent.indexOf("MSIE")>-1 && navigator.userAgent.indexOf("Opera")==-1)?true:false;
var isOp = (navigator.userAgent.indexOf("Opera")>-1)?true:false;
function init(){
// if(isIE){
// document.getElementById("msg_scroller").style.position="relative";
// }
}
var incrementVal = 2;
var timer;
var flag;
function scroll(flag){
var obj = document.getElementById("movingDiv");
var isIE6 = (document.documentElement.clientHeight)? true : false;`
var Y = parseInt(obj.style.top);
var cY = (isIE6)?document.documentElement.clientHeight-173 :((document.all)? document.body.clientHeight-173:window.innerHeight - 173);
if(flag==1 && Y<cY){
obj.style.top = (Y+incrementVal)+"pt";
timer = setTimeout("scroll(1)",incrementVal*20);
}else if(flag==-1 && Y>0){
obj.style.top = (Y-incrementVal)+"pt";
timer = setTimeout("scroll(-1)",incrementVal*20);
}else{
clearTimeout(timer);
}
}
</script>
and my html is
<div id="movingDiv" style="position:absolute;left:100pt;top:150pt;border:1px;width:160px;background-color:lightyellow;font-weight:bold;" >
<textarea style="font-size: 10pt; font-family: Potha, Malithi Web , Arial Unicode MS;
width: 600px;" rows="7"></textarea>
<text></div>
i know to stop this i have to get x,y cordinates but how i get this ?? can some one help me?

javascript not working when page is loaded qtip2

I wrote a nice heatmap in javascript, and that worked pretty nice so far. The heatmap is basically a table with a coloring variation, based on the threshold of the value displayed in the table. I used JavaScript to create the table, and to set up the colors. However, I wanted to show a nice pop up window, so when the user hover over the table's cell, some additional information is displayed. I found this library qTip2
$(document).ready(function(){
$('#mytable td').qtip({
overwrite : false, // make sure it can't be overwritten
content : {
text : function(api){
return "Time spent: " + $(this).html();
}
},
position : {
my : 'top left',
target : 'mouse',
viewport : $(window), //keep it on-screen at all time if possible
adjust : {
x : 10, y : 10
}
},
hide : {
fixed : true // Helps to prevent the tooltip from hiding occassionaly when tracking!
},
style : 'ui-tooltip-tipsy ui-tooltip-shadow'
});
});
This function creates the heatmap:
function makeTable(data)
{
var row = new Array();
var cell = new Array();
var row_num = 26;
var cell_num = 44;
var tab = document.createElement('table');
tab.setAttribute('id', 'mytable');
tab.border = '1px';
var tbo = document.createElement('tbody');
for(var i = 0; i < row_num; i++){
row[i] = document.createElement('tr');
var upper = (i+1)*44;
var lower = i*44;
for(var j = lower; j < upper; j++){
cell[j] = document.createElement('td');
//cell[j].setAttribute('class', 'selector');
if(data[j] != undefined){
var count = document.createTextNode(data[j].diff);
cell[j].appendChild(count);
var index = parseInt(data[j].diff);
/* specify which color better suits the heatmap */
if(index >= 0 && index <= 100){
cell[j].style.backgroundColor = '#00BFFF';
}
else if(index > 100 && index <= 1000){
cell[j].style.backgroundColor = "#6495ED";
}
else if(index > 1000 && index <= 4000){
cell[j].style.backgroundColor = "#4682B4";
}
else if(index > 4000 && index <= 6000){
cell[j].style.backgroundColor = "#0000FF";
}
else{
cell[j].style.backgroundColor = "#00008B";
}
row[i].appendChild(cell[j]);
}
}
tbo.appendChild(row[i]);
}
tab.appendChild(tbo);
document.getElementById('mytable').appendChild(tab);
}
Inside of my <body> tag I have:
<div id="body">
<div id="mytable"></div>
</div>
However, when I load the page, I expect to see the pop up box when I hover the mouse over the table's cell, however something happens. Also, when I execute that $(document).ready part from firebug's terminal, then the program starts to execute as suppose to. I also made sure the library is being loaded into my page before I used it. I also don't see any errors in the firebug's terminal.
<script src="http://localhost/heatmap/javascript/jquery.qtip.js">
Could someone please give me a clue why is this happening?
The main function of my javascript is
function OnLoad() {
$.post('index.php/heatmap/getDatalines',
function(answer){
var data = eval('(' + answer + ')');
var list = [];
makeTable(data);
});
}
Thanks
whis is called on load: google.setOnLoadCallback(OnLoad);
You need to create the qtip after you have loaded the table like this:
function OnLoad() {
$.post('index.php/heatmap/getDatalines',
function(answer){
var data = eval('(' + answer + ')');
var list = [];
makeTable(data);
$('#mytable td').qtip({
overwrite : false, // make sure it can't be overwritten
content : {
text : function(api){
return "Time spent: " + $(this).html();
}
},
position : {
my : 'top left',
target : 'mouse',
viewport : $(window), // keep it on-screen at all time if possible
adjust : {
x : 10, y : 10
}
},
hide : {
fixed : true // Helps to prevent the tooltip from hiding occassionaly when tracking!
},
style : 'ui-tooltip-tipsy ui-tooltip-shadow'
});
});
}

Categories