Toggle Elements FontWeight - Javascript - javascript

I'm trying to make it so that the text inside a text area can be toggled to be bold or not, by pressing a button. I have the following code:
function bold()
{
var ta = document.getElementById("textArea");
if(ta.style.fontWeight == "normal"){
ta.style.fontWeight = "bold";
}
else{
ta.style.fontWeight = "normal";
}
}
When the I press the button, nothing happens the first time. But I press it a second time and it runs perfectly. Running it through a debugger, the variable "ta" becomes equal to "" the first time, and then "normal" the second time, despite the text area being set to normal in the css.
Any ideas?
Thanks

So the reason this is happening is because ta.style is accessing the style attribute of the textarea element, which will not have any information about styles coming from CSS. You could write your textarea like this, and it should work with what you have:
<textarea id="textArea" style="font-weight:normal"></textarea>
But, I'd recommend you do something along these lines in your js:
function bold()
{
var ta = document.getElementById("textArea");
if(ta.style.fontWeight !== "bold"){
ta.style.fontWeight = "bold";
}
else{
ta.style.fontWeight = "normal";
}
}
Might also be helpful to rename your function to toggleBold ;)

Instead of trying to fight it, just change your condition:
if (ta.style.fontWeight == "normal" || ta.style.fontWeight === '') {

Related

How to make a Javascript form validation with coloured textbox (red/green) without using inline css?

So I have made a Javascript form validation where I get an alert message if nothing is written in the form. Instead of an alert message I want a coloured (red/green) textbox. When you don't write anything in it and try to submit it, you get a red box with a message. When you write down what you need to write and submit it, you get a green box.
function validateFormC() {
let x = document.forms["contactForm"]["name_contact"].value;
if (x === "") {
alert("Don't forget to write down your name!");
return false;
}
I already know how to make coloured checkboxes with html. I need to know how to do it with Javascript for a school project. But it's important that I don't use inline css. Any help would be appreciated, thanks.
You can create a class selector in CSS:
.red-input {
border: 1px solid red;
}
then in your JavaScript you can select the element and add that class to it:
// With Vanilla JavaScript
document.getElementById('input_id').classList.add('red-input');
// With jQuery
$('#input_id').addClass('red-input')
You need something along the lines of:
var warnMessage = document.createElement("div");
warnMessage.innerHTML = "Don't forget to write down your name!";
warnMessage.setAttribute('class', 'warnMessage');
document.body.appendChild(warnMessage);
Then create a matching CSS style : warnMessage probably with bgcolor:red;
Same again for your success message, but green.
Try something like this. You can change borderColor to backgroundColor if you prefer.
function validateFormC() {
var x = document.forms["contactForm"]["name_contact"];
if (x.value === "") {
alert("Don't forget to write down your name!");
x.style.borderColor = 'red';
return false;
}
else
x.style.borderColor = 'green';
}

Simple Javascript text box verification error

I'm trying to check whether the length of characters typed into the text box is less than 6, and if it is, I want its background to be red. Unfortunately, I can't seem to figure out where I'm going wrong with this simple problem.
var textBox = getElementsByName('random');
function checkLength() {
if (textBox.value.length < 6) {
textBox.style.backgroundColor = "red";
}
}
<input type="text" name="random" onfocus="checkLength();">
A few issues in your code:
you need to put <script> code at the end, so that DOM is loaded and ready before you access elements in it.
getElementsByName('random') needs to document.getElementsByName('random'), which will actually return a list so you need to get first element from the list.
Also logically, you need to remove the red background once the text
length in input exceeds 6 and it would be better if you attach function to oninput event.
<input type="text" name="random" oninput="checkLength();">
<script type="text/javascript">
var textBox = document.getElementsByName('random')[0];
function checkLength() {
if (textBox.value.length < 6) {
textBox.style.backgroundColor = "red";
} else {
textBox.style.backgroundColor = "white";
}
}
</script>
When the page first loads, the element with a name of random doesn't exist.
You will need to initialise your textBox global after the page loads.
You can do this by replacing
var textBox = document.getElementsByName("random")[0]
with
var textBox;
window.onload = function() {
textBox = document.getElementsByName("random")[0]
}
Try this
// add an id of "random" to your input
function checkLength() {
const textBox = document.getElementById("random")
if (textBox.value.length < 6) {
textBox.style.backgroundColor = "red";
} else {
textBox.style.backgroundColor = "white";
}
}
Working example: http://jsbin.com/caseqekusi/1/edit?html,js,output
Note: If you want the box to be red right away, you'll have to modify it a bit, let me know if you have questions.
I would suggest to use oninput as well, so it updates as you type and marks the field as "valid" as soon as you have reached a certain length.
You could also get rid of var textbox = ... by using document.activeElement. It makes your function reusable for other input fields. And it no longer matters when your code is loaded.
function checkLength() {
// Get current focused element
const textBox = document.activeElement;
if ( !textBox.value || textBox.value.length < 6 ) {
textBox.style.backgroundColor = "red";
}
else {
textBox.style.backgroundColor = "#fff";
}
}
<input type="text" name="random" onfocus="checkLength()" oninput="checkLength()">

Adding and deleting a paragraph, displaying text briefly

After clicking on a specific place in an image map, the function add() should be run, a paragraph should be created, one should see "not available yet" in red for five seconds, and the paragraph should be deleted again.
function add() {
var x = document.createElement("P");
var t = document.createTextNode("This is a paragraph.");
x.appendChild(t);
document.body.appendChild(x);
setTimeout ( "del()", 5000 );
}
function del() {
removeChild() }
So there are a couple of things which are not correct.
1: how do you change the text to red? And to another font?
2: the del()function should remove the paragraph, but I don't know what to place there. Just removeChild(P) ? Wait... P isn't even a Child...
Could anyone help me with getting the desired result? (I mean, this: one should see 'not available yet' in red for five seconds, afterwards the paragraph should disappear.
to change the text to red using JavaScript:
para.style.fontFamily = 'Arial'
para.style.color = 'red'
to change the text to red using CSS:
CSS:
.mypara {
color: red;
font-family: Arial;
}
JS:
para.className = 'mypara'
to remove the paragraph:
var para = document.createElement("P");
function add() {
var t = document.createTextNode("This is a paragraph.");
para.appendChild(t);
document.body.appendChild(para);
setTimeout (del, 5000);
}
function del() {
para.parentNode.removeChild(para);
// or if you just need to empty the paragraph
// para.innerHTML = '';
}
To make that text red: There are two ways. Either you write:
x.style.color = '#ff0000';
Or you give it a class:
x.className = 'red_text'
... and define the style for that class in a stylesheet.
To remove the paragraph, just do the reverse of what you did to add it:
document.body.removeChild(x)
Take a look to this example.
1: how do you change the text to red? And to another font?
I suggest to use CSS for everything regarding style and simply assign the right class to the element. You can specify whatever you need. For example also use CSS for a fade in effect.
2: the del()function should remove the paragraph, but I don't know what to place there. Just removeChild(P) ?
I suggest to use a closure and pass parent and child in order to use parent.removeChild(child);. If you do not need nothing else you even could avoid to define another function.

Typewriter Script Stops Functioning after Run Once

I've been trying to get this typewriter function to run (please refer to JSFiddle below).
I set up an if-else statement so that when the user clicks on Biography the biography text is active and types itself out, and upon second click, the text becomes inactive and is erased. Ideally on a third click, the biography text will show up again, unfortunately this is when my code falls apart. It only runs once, and the text no longer shows up.
I tried console.logs and know that the DOM is registering when #bio has the class "active" attached to it, and when it does not, so I'm not sure why the typewriter script is not working the second time around.
var str = "<p>This is biography text.</p>",
i = 0,
isTag, text;
$('#biog').click(function () {
if ($("#bio").hasClass("active")) {
$("#bio").removeClass("active");
$("#bio").detach();
} else {
$("#bio").addClass("active");
(function type() {
text = str.slice(0, ++i);
if (text === str) return;
document.getElementById('bio').innerHTML = text;
var char = text.slice(-1);
if (char === '<') isTag = true;
if (char === '>') isTag = false;
if (isTag) return type();
setTimeout(type, 1);
}());
}
});
.active {
}
<div id="biog"><a>Biography</a>
</div>
<div id="bio"></div>
JSFiddle: http://jsfiddle.net/droogist/20L8088r/1/
There are two mistakes in you code.
You are detaching element after one use, because of that the second time you try accessing it, it is not there.
You are not resetting the variable i after one use.
So, use $("#bio").html(''); instead of $("#bio").detach();
And also, add i = 0; in else part of your code.
Here is the updated JSFiddle,
http://jsfiddle.net/20L8088r/2/

Getting Text out of HTML into Javascript as a Function with Input Changing IDs

I am trying to create an if/else statement that checks the text of a button that the user presses. If there is no text in that button, it continues the function, if there is pre-existing text then it gives an alert stating that there is already an entry there.
Essentially, the user clicks a button and the code checks to see if that button is empty or not. However, since the button's ID is constantly changing, I don't know how to tell the code to check the pressed button. I feel that using 'this' is part of the solution to this problem, but I am too new to JavaScript to use it correctly.
This is my entire JavaScript code, off it works fine except for the two lines that have comments in them. I am trying to make the variable "inSquare" to equal the text from the button that triggered the function. Then it goes on to check the text of the variable, but currently all it does is fail the if and head straight to the else.
var turnNumber = 9;
var whoseTurn;
var inSquare;
function currentTurn(id) {
inSquare = this.innerHTML; /*This Line*/
if (inSquare === "") { /*This Line*/
if (whoseTurn === 0) {
id.innerHTML = "X";
turnNumber -= 1;
whoseTurn = turnNumber % 2;
} else {
id.innerHTML = "O";
turnNumber -= 1;
whoseTurn = turnNumber % 2;
}
} else {
window.alert("Something is already in that square!");
}
}
Also, here is an example of what the HTML buttons look like. (There are nine total, but they are all formatted the same).
<button id="topLeft" onclick="currentTurn(this)"></button>
<button id="topMid" onclick="currentTurn(this)"></button>
<button id="topRight" onclick="currentTurn(this)"></button>
inSquare = this.innerHTML; should be inSquare = id.innerHTML;
this in your function refers to the window object, but you want to refer to the element you passed, which you provided as the id argument of the function.

Categories

Resources