I have a JavaScript function which changes the border radius and the opacity of an image based on user's input.
Here is the JavaScript:
<script>
var input = document.getElementById('opc');
var text = document.getElementById('main');
function changeOpacity(event) {
if ( event.keyCode === 13 ) {
var value = input.value;
var parts = value.split(' ');
text.style.opacity = '0.' + value;
}
}
input.addEventListener('keyup', changeOpacity);
</script>
<script>
var input = document.getElementById('modell');
var text = document.getElementById('image');
function changeBorderRadius(event) {
//works with spacebar
if ( event.keyCode === 32 ) {
var value = input.value;
var parts = value.split(' ');
text.style.borderRadius = '5' + value;
}
}
input.addEventListener('keyup', changeBorderRadius);
</script>
And here is the HTML:
<div id = "main"><img id="image" src = "flag.gif" alt = "Flag" style = "left:0; top: 0;" /></div>
<br/>
<table border="1" style="background-color: #CCFFCC">
<tr>
<td>
Opacity Value (1 - 9)
</td>
<td>
<input type="text" id="opc" />
</td></tr>
<tr>
<td>
Border Radius (px / %)
</td>
<td>
<input type="text" id="modell" />
</td></tr>
</table>
</body>
I got the opacity thing working with the help of this Stack Overflow. :D
I tried to add another function (border function) which worked fine for me, but the opacity thing stopped working after adding this border function.
Can someone tell me what am I missing here or what is the issue?
You have to modify your javascript a bit.
Here is a jsfiddle of it working
<script>
function changeBorderRadius(e) {
var key = e.which || e.keyCode || 0;
//works with space
if ( key == 32 ) {
var value = inputBoarder.value;
var parts = value.split(' ');
textBoarder.style.borderRadius = parts[0] + "px";
}
}
function changeOpacity(e) {
var key = e.which || e.keyCode || 0;
if ( key == 32 ) {
var value = inputOPC.value;
textOPC.style.opacity = '0.' + value;
}
}
var inputOPC = document.getElementById('opc');
var textOPC = document.getElementById('main');
inputOPC.addEventListener('keyup', changeOpacity);
var inputBoarder = document.getElementById('modell');
var textBoarder = document.getElementById('image');
inputBoarder.addEventListener('keyup', changeBorderRadius);
</script>
Rename variable in either script tag.
Something like input to input1
Values of variable are getting overridden
Related
I am making a little project for my self. So basically its main function is to create a base counter for each game.
For example: If there are two players it should create three bases. (This is for the card game "smash up" if that helps you understand better.) But when the Buttons populate they all only effect the last input. I can not figure out how to make them effect their respective inputs.
The problem I am having is that every button I click only effects the last input.
<html>
<title> Base Maker </title>
<body>
<div>
<hl> Score Keeper </h1>
<hr>
<input type = "text" placeholder = "How many players?">
<button id = "enter" onclick = "baseMaker()">
Enter
</button>
</div>
<p></p>
</body>
</html>
var parent = document.querySelector("p");
var input = document.querySelector("input");
var enter = document.getElementById("enter");
function baseMaker()
{
for(var i = 0; i <= input.value; i++)
{
//base
var base = document.createElement("p");
base.textContent = "Base " + (i + 1) + ":";
//score
var score = document.createElement( "input");
score.setAttribute("id", "score" + i);
score.value = 20;
//upbutton
var upButton = document.createElement( "button");
upButton.textContent = "+";
upButton.setAttribute("id", "upButton" + i)
upButton.addEventListener('click', function() {
score.value++; });
//downbutton
var downButton = document.createElement( "button");
downButton.textContent = "-";
downButton.setAttribute("id", "downButton" + i)
downButton.addEventListener('click', function() {
score.value--; });
//populate data
parent.appendChild(base);
parent.appendChild(score);
parent.appendChild(upButton);
parent.appendChild(downButton);
}
input.value = "";
}
This is a common thing to run into especially when not using a framework in javascript.
I am not sure why this happens but when a function is defined directly in a loop, the closure for these created functions becomes whatever it is after the last iteration. I believe it is because the closure for each callback function is only "sealed up" (for lack of a better word) at the end of the loop-containing-function's execution which is after the last iteration. It's really beyond me, though.
There are some easy ways to avoid this behavior:
use bind to ensure a callback gets called with the correct input (used in solution at bottom)
create a function which creates a handler function for you and use that in the loop body
function createIncrementHandler(input, howMuch){
return () => input.valueAsNumber += howMuch;
}
/// then in your loop body:
downButton.addEventListener('click', createIncrementHandler(score, 1));
get the correct input by using the event parameter in the handler
downButton.addEventListener('click', (event) => event.target.valueAsNumber += 1);
make the entire body of the loop into a function, for example:
function createInputs(i) {
//base
var base = document.createElement("p");
base.textContent = "Base " + (i + 1) + ":";
//score
var score = document.createElement("input");
score.type = "number";
score.setAttribute("id", "score" + i);
score.value = 20;
//upbutton
var upButton = document.createElement( "button");
upButton.textContent = "+";
upButton.setAttribute("id", "upButton" + i)
upButton.addEventListener('click', function() {
score.value++; });
//downbutton
var downButton = document.createElement( "button");
downButton.textContent = "-";
downButton.setAttribute("id", "downButton" + i)
downButton.addEventListener('click', function() {
score.value--; });
//populate data
parent.appendChild(base);
parent.appendChild(score);
parent.appendChild(upButton);
parent.appendChild(downButton);
}
Here is a full example of one of the possible fixes.
<html>
<title> Base Maker </title>
<body>
<div>
<hl> Score Keeper </h1>
<hr>
<input type="text" placeholder="How many players?">
<button id="enter" onclick="baseMaker()">
Enter
</button>
</div>
<p></p>
<script>
var parent = document.querySelector("p");
var input = document.querySelector("input");
var enter = document.getElementById("enter");
function incrementInput(input, byHowMuch) {
input.valueAsNumber = input.valueAsNumber + byHowMuch;
}
function baseMaker() {
for (var i = 0; i <= input.value; i++) {
//base
var base = document.createElement("p");
base.textContent = "Base " + (i + 1) + ":";
//score
var score = document.createElement("input");
score.type = "number";
score.setAttribute("id", "score" + i);
score.value = 20;
//upbutton
var upButton = document.createElement("button");
upButton.textContent = "+";
upButton.setAttribute("id", "upButton" + i)
upButton.addEventListener('click', incrementInput.bind(null, score, 1));
//downbutton
var downButton = document.createElement("button");
downButton.textContent = "-";
downButton.setAttribute("id", "downButton" + i)
downButton.addEventListener('click', incrementInput.bind(null, score, -1));
//populate data
parent.appendChild(base);
parent.appendChild(score);
parent.appendChild(upButton);
parent.appendChild(downButton);
}
input.value = "";
}
</script>
</body>
</html>
I will do that this way :
const
AllBases = document.querySelector('#bases')
, bt_Start = document.querySelector('#game-go')
, bt_newGame = document.querySelector('#new-game')
, playerCount = document.querySelector("#play-start > input")
;
playerCount.value = ''
playerCount.focus()
playerCount.oninput = () =>
{
playerCount.value.trim()
bt_Start.disabled = (playerCount.value === '' || isNaN(playerCount.value))
playerCount.value = (bt_Start.disabled) ? ''
: (playerCount.valueAsNumber > playerCount.max) ? playerCount.max
: (playerCount.valueAsNumber < playerCount.min) ? playerCount.min
: playerCount.value
}
bt_newGame.onclick = () =>
{
playerCount.value = ''
playerCount.disabled = false
bt_Start.disabled = true
bt_newGame.disabled = true
AllBases.innerHTML = ''
playerCount.focus()
}
bt_Start.onclick = () =>
{
playerCount.disabled = true
bt_Start.disabled = true
bt_newGame.disabled = false
for(let i = 0; i <= playerCount.valueAsNumber; i++)
{
let base = document.createElement('p')
base.countValue = 20 // create a counter property on <p>
base.innerHTML = `Base ${i+1} : <span>${base.countValue}</span> <button>+</button> <button>−</button>\n`
AllBases.appendChild(base)
}
}
AllBases.onclick = ({target}) =>
{
if (!target.matches('button')) return // verify clicked element
let countElm = target.closest('p')
if (target.textContent==='+') countElm.countValue++
else countElm.countValue--
countElm.querySelector('span').textContent = countElm.countValue
}
#bases p span {
display : inline-block;
width : 6em;
border-bottom : 2px solid aqua;
padding-right : .2em;
text-align : right;
margin : 0 .3em;
}
#bases p button {
width : 2em;
margin : 0 .1em;
cursor : pointer;
}
<hr>
<hl> Score Keeper </h1>
<hr>
<div id="play-start" >
<input type="number" placeholder="How many players?" min="2" max="4">
<button id="game-go" disabled> Enter </button>
<button id="new-game" disabled> new </button>
</div>
<hr>
<div id="bases"></div>
If it helps, I can add more explanations
I'm trying to calculate the width of block, id="titleText" I am getting some luck, although it calculates incorrectly.
For example, when empty it still shows pixels (by default, it should be one), yet 18px remains in this example:
(using onkeydown)
(using onkeyup)
and...
Triggering my style logic before the number I specified, which is 585.
My HTML is:
<input type="text" autocomplete="off" id="serpTitle"
onkeydown="checkTitleValue()" class="form-control" />
<p class="d-block" id="titleText"></p>
and the Javascript
function checkTitleValue() {
var fontSize = 12;
var measureTitle = document.getElementById("titleText");
measureTitle.style.fontSize = fontSize;
var height = (measureTitle.clientHeight + 1) + "px";
var width = (measureTitle.clientWidth + 1) + "px"
var inputTitle = document.getElementById("serpTitle").value;
document.getElementById("titleText").innerText = inputTitle;
document.getElementById("titlePixels").innerText = width;
if (measureTitle.clientWidth + 1 > 585) {
document.getElementById("titlePixels").style.color = "red";
}
else if (measureTitle.clientWidth + 1 < 585)
{
document.getElementById("titlePixels").style.color = null;
}
}
Could you please try this code snippet. I don't get the point of this measureTitle.clientWidth + 1 or measureTitle.clientWidth + 1 < 585
const FONT_SIZE = 12;
const MAX_LENGTH = 585;
var serpTitle = document.getElementById('serpTitle');
var mesured = document.getElementById('measured');
var maxLength = document.getElementById('max-length');
var measureCont = document.getElementById('mesure-cont');
function init() {
measureCont.style.fontSize = FONT_SIZE;
maxLength.innerHTML = MAX_LENGTH + 'px';
updateMesure();
}
function updateMesure() {
measureCont.innerHTML = serpTitle.value;
mesured.innerHTML = measureCont.clientWidth;
}
function checkTitleValue() {
updateMesure();
if (measureCont.clientWidth > MAX_LENGTH) {
measured.style.color = 'red';
} else {
measured.style.color = null;
}
}
init();
<div>
<input type="text" autocomplete="off" id="serpTitle" onkeyup="checkTitleValue()"
class="form-control" />
<span id="measured"></span>/<span id="max-length"></span>
</div>
<div>
<span style="display: inline-block" id="mesure-cont">aaaaa</span>
</div>
You should probably try calling the function on keyup instead of keydown.
Since each keystroke is ACTUALLY executed in the input box at keyup: Meaning.. (after) the key has been "pressed".
So your HTML code probably should go like:
<input type="text" autocomplete="off" id="serpTitle"
onkeyup="checkTitleValue()" class="form-control" />
<p class="d-block" id="titleText"></p>
one of the issue, regarding changing color, is that you first updating color then calculating it. So swap
if (measureTitle.clientWidth > 585) {
document.getElementById("titlePixels").style.color = "red";
}
else if (measureTitle.clientWidth < 585)
{
document.getElementById("titlePixels").style.color = null;
}
document.getElementById("titleText").innerText = inputTitle;
document.getElementById("titlePixels").innerText = width;
I have 2 html textbox for users to enter numbers. To sum those numbers, I am passing the values to JavaScript variable and after addition displaying the result to html div section
<div class="input-left"><span><input class="textbox" id="left" name="count" type="text" size="5" value="" /></span></div>
<div class="input-right"><span><input class="textbox" id="right" name="count" type="text" size="5" value="" /></span></div>
<div id="result"> </div>
javascript:
document.getElementById('left').onkeyup = function() {
var a = parseFloat(this.value);
}
document.getElementById('right').onkeyup = function() {
var b = a + parseFloat(this.value);
document.getElementById("result").innerHTML = b || 0 ;
}
But I have an issue with JavaScript. It not displaying the result. How to add both functions in same onkeyup function.
FIDDLE SETUP
Try this:
window.onload = function(){
var left = document.getElementById('left');
var right = document.getElementById('right');
var result = document.getElementById("result");
left.onkeyup = calc;
right.onkeyup = calc;
function calc() {
var a = parseFloat(left.value) || 0;
var b = parseFloat(right.value) || 0;
result.innerHTML = a + b ;
}
}
JSFiddle: http://fiddle.jshell.net/gYV8Z/3/
Update: To hide the result in case the sum equals zero , change the last line like this:
result.innerHTML = ( a + b ) || "";
JSFiddle: http://fiddle.jshell.net/gYV8Z/4/
document.getElementById('left').onkeyup = function() {
var a = parseFloat(this.value);
}
document.getElementById('right').onkeyup = function() {
var b = a + parseFloat(this.value);
document.getElementById("result").innerHTML = b || 0 ;
}
it your code, var a is local variable. make it global variable.
but i would use this code.
function add(){
return parseFloat(document.getElementById('left').value) + parseFloat(document.getElementById('right').value);
}
document.getElementById('left').onkeyup = function() {
document.getElementById("result").innerHTML = add();
}
document.getElementById('right').onkeyup = function() {
document.getElementById("result").innerHTML = add();
}
please be nice. I'm trying to create a page which sets limit and cut the excess (from the specified limit). Example: Limit is 3. then, I'll input abc if I input d it must say that its limit is reached and the abc will remain. My problem is that it just delete my previous input and make new inputs. Hoping for your great cooperation. Thanks.
<html>
<script type="text/javascript">
function disable_btn_limit(btn_name)
{
/* this function is used to disable and enable buttons and textbox*/
if(btn_name == "btn_limit")
{
document.getElementById("btn_limit").disabled = true;
document.getElementById("ctr_limit_txt").disabled = true;
document.getElementById("btn_edit_limit").disabled = false;
}
if(btn_name == "btn_edit_limit")
{
document.getElementById("btn_limit").disabled = false;
document.getElementById("ctr_limit_txt").disabled = false;
document.getElementById("btn_edit_limit").disabled = true;
}
}
function check_content(txtarea_content)
{
/*This function is used to check the content*/
// initialize an array
var txtArr = new Array();
//array assignment
//.split(delimiter) function of JS is used to separate
//values according to groups; delimiter can be ;,| and etc
txtArr = txtarea_content.split("");
var newcontent = "";
var momo = new Array();
var trimmedcontent = "";
var re = 0;
var etoits;
var etoits2;
//for..in is a looping statement for Arrays in JS. This is similar to foreach in C#
//Syntax: for(index in arr_containter) {}
for(ind_val in txtArr)
{
var bool_check = check_if_Number(txtArr[ind_val])
if(bool_check == true)
{
//DO NOTHING
}
else
{
//trim_content(newcontent);
newcontent += txtArr[ind_val];
momo[ind_val] = txtArr[ind_val];
}
}
var isapa = new Array();
var s;
re = trim_content(newcontent);
for(var x = 0; x < re - 1; x++){
document.getElementById("txtarea_content").value += momo[x];
document.getElementById("txtarea_content").value = "";
}
}
function trim_content(ContentVal)
{
//This function is used to determine length of content
//parseInt(value) is used to change String values to Integer data types.
//Please note that all value coming from diplay are all in String data Type
var limit_char =parseInt(document.getElementById("ctr_limit_txt").value);
var eto;
if(ContentVal.length > (limit_char-1))
{
alert("Length is greater than the value specified above: " +limit_char);
eto = limit_char ;
etoits = document.getElementById("txtarea_content").value;
//document.getElementById("txtarea_content").value = "etoits";
return eto;
//for(var me = 0; me < limit_char; me++)
//{document.getElementById("txtarea_content").value = "";}
}
return 0;
}
function check_if_Number(ContentVal)
{
//This function is used to check if a value is a number or not
//isNaN, case sensitive, JS function used to determine if the values are
//numbers or not. TRUE = not a number, FALSE = number
if(isNaN(ContentVal))
{
return false;
}
else
{ alert("Input characters only!");
return true;
}
}
</script>
<table>
<tr>
<td>
<input type="text" name="ctr_limit_txt" id="ctr_limit_txt"/>
</td>
<td>
<input type="button" name="btn_limit" id="btn_limit" value="Set Limit" onClick="javascript:disable_btn_limit('btn_limit');"/>
</td>
<td>
<input type="button" name="btn_edit_limit" id="btn_edit_limit" value="Edit Limit" disabled="true" onClick="javascript:disable_btn_limit('btn_edit_limit');"/>
</td>
</tr>
<tr>
<td colspan="2">
<textarea name="txtarea_content" id="txtarea_content" onKeyPress="javascript:check_content(this.value);"></textarea>
<br>
*Please note that you cannot include <br>numbers inside the text area
</td>
</tr>
</html>
Try this. If the condition is satisfied return true, otherwise return false.
<html>
<head>
<script type="text/javascript">
function check_content(){
var text = document.getElementById("txtarea_content").value;
if(text.length >= 3){
alert('Length should not be greater than 3');
return false;
} else {
return true;
}
}
</script>
</head>
<body>
<div>
<textarea name="txtarea_content" id="txtarea_content" onkeypress=" return check_content();"></textarea>
</div>
</body>
</html>
Instead of removing the extra character from the text area, you can prevent the character from being written in the first place
function check_content(event) { //PARAMETER is the event NOT the content
txtarea_content = document.getElementById("txtarea_content").value; //Get the content
[...]
re = trim_content(newcontent);
if (re > 0) {
event.preventDefault(); // in case the content exceeds the limit, prevent defaultaction ie write the extra character
}
/*for (var x = 0; x < re - 1; x++) {
document.getElementById("txtarea_content").value += momo[x];
document.getElementById("txtarea_content").value = "";
}*/
}
And in the HTML (parameter is the event):
<textarea ... onKeyPress="javascript:check_content(event);"></textarea>
Try replacing with this:
for(var x = 0; x < re - 6; x++){
document.getElementById("txtarea_content").value += momo[x];
document.getElementById("txtarea_content").value = "";
}
Any reason why the maxlength attribute on a text input wouldn't work for so few characters? In your case, you would have:
<input type="text" maxlength="3" />
or if HTML5, you could still use a textarea:
<textarea maxlength="3"> ...
And then just have a label that indicates a three-character limit on any input.
What is the javascipt code that will edit a text on double click. The process is I have a text and if I double click it, a text box will appear, and if I press enter the word will change depends on what you've type.
Sample
This is sample text. $nbsp;$nbsp; --> if I double click it a textbox will appear.
<input type="text" value="This is sample text." name="" />
Sorry for asking this. I am a newbie in javascript
Here is a great example.
I'm going to paste in the script from that example so that it's preserved in case that link goes away, but you should follow the link -- the article does a great job of breaking the script down line by line and explaining what it does. A great learning opportunity for javascript.
var editing = false;
if (document.getElementById && document.createElement) {
var butt = document.createElement('BUTTON');
var buttext = document.createTextNode('Ready!');
butt.appendChild(buttext);
butt.onclick = saveEdit;
}
function catchIt(e) {
if (editing) return;
if (!document.getElementById || !document.createElement) return;
if (!e) var obj = window.event.srcElement;
else var obj = e.target;
while (obj.nodeType != 1) {
obj = obj.parentNode;
}
if (obj.tagName == 'TEXTAREA' || obj.tagName == 'A') return;
while (obj.nodeName != 'P' && obj.nodeName != 'HTML') {
obj = obj.parentNode;
}
if (obj.nodeName == 'HTML') return;
var x = obj.innerHTML;
var y = document.createElement('TEXTAREA');
var z = obj.parentNode;
z.insertBefore(y,obj);
z.insertBefore(butt,obj);
z.removeChild(obj);
y.value = x;
y.focus();
editing = true;
}
function saveEdit() {
var area = document.getElementsByTagName('TEXTAREA')[0];
var y = document.createElement('P');
var z = area.parentNode;
y.innerHTML = area.value;
z.insertBefore(y,area);
z.removeChild(area);
z.removeChild(document.getElementsByTagName('button')[0]);
editing = false;
}
document.onclick = catchIt;
I wanted to know how it works as I have seen it on many websites. And I build it using jQuery
$(document).dblclick(function(event) {
var id = event.target.id; //id
// var id = $(this).attr('id');
if (id == "") {
console.log("nope");
} else {
id = "#" + id + "";
console.log(typeof(id)); //concatenated with #
text = $(id).text().trim();
console.log(text); //asscociated text
$(id).html('<textarea name="" id="tex" cols="10" rows="1" onkeypress="myFunction(event)">' + text + '</textarea>');
// alert(id);
}
})
function myFunction(event) {
var x = event.code;
var id = $(this).attr('id');
parentId = event.path[1].id;
parentId = "#" + parentId + "";
if (x == 'Enter') {
name = $('#tex').val();
$(parentId).text(name);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container mt-3">
<h2>Striped Rows</h2>
<p>The .table-striped class adds zebra-stripes to a table:</p>
<table class="table table-striped">
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr>
<td id="name1" class="name">
john
</td>
<td id="sirname1">Doe</td>
<td id="email1">john#example.chdm som</td>
</tr>
<tr>
<td id="name2" class="name">Mary</td>
<td id="sirname2">Moe</td>
<td id="email2">mary#example.com</td>
</tr>
<tr>
<td id="name3" class="name">July</td>
<td id="sirname3">Dooley</td>
<td id="email3">july#example.com</td>
</tr>
</tbody>
</table>
</div>