If.. Then in javascript - javascript

I want to change the font size of a text depending on the current font size.
Algorithm:
On clicking the text,
If font size = 35, change it to 12
else if font size = 12, change it to 35
<h2>What Can JavaScript Do?</h2>
<p id="demo" onclick="myFunction()">Click me.</p>
<script>
function myFunction() {
if (document.getElementById('demo').style.fontSize='35px') {
document.getElementById('demo').style.fontSize='12px'
} else if(document.getElementById('demo').style.fontSize='12px') {
document.getElementById('demo').style.fontSize='35x'
}
}
</script>
It changed it 12, but never changes back to 35. What did I miss here?

You have assignment in the if statement. You need to use not =, but == or better ===.
Also one note, if the font-size is defined in the css, it may return to you an empty string for the first time. In this case you need to use window.getComputedStyle to get the font-size.
function myFunction() {
const element = document.getElementById('demo');
console.log(element.style.fontSize);
const fontSize = window.getComputedStyle(element, null).getPropertyValue('font-size');
if (fontSize === '35px') {
element.style.fontSize = '12px';
} else if(fontSize === '12px') {
element.style.fontSize = '35px';
}
}
p#demo {
font-size: 12px;
}
<h2>What Can JavaScript Do?</h2>
<p id="demo" onclick="myFunction()">Click me.</p>

You're using = in if statement like if(a=b). When this code will run javascript engine will assign b to a. And that's why it will always execute the same code inside the if(a=b) block. That's how, this would be translated in machine language. If you want a comparison b/w a and b, you should use a==b or a===b. This will make the required block to get executed bases on the condition specified.

you are using '=' instead of '==' and another important thing - you should store fontsize in a variable and then do the comparision.
The optimized code will be -
<!DOCTYPE html>
<html>
<body>
<h2>What Can JavaScript Do?</h2>
<p id="demo" onclick="myFunction()">Click me.</p>
<script>
function myFunction() {
var element= document.getElementById('demo'),
fontSize=element.style.fontSize;
if (fontSize === '35px') {
element.style.fontSize='12px'
} else if(fontSize ==='12px') {
element.style.fontSize='35x'
}
}
</script>
</body>
</html>

Instead of comparison of font size you are assigning size.
document.getElementById('demo').style.fontSize='35px'
You should change it to following :
document.getElementById('demo').style.fontSize=='35px'
Same For both conditions.

Three Mistakes from your end. First one is you don't have any style tag in your html mark-up. Second one is conditional operator == you entered as =. Last mistake is typo 35x should be 35px in the second condition like below.
<p id="demo" style="font-size:35px;" onclick="myFunction()">Click me.</p>
if (document.getElementById('demo').style.fontSize=='35px') {
document.getElementById('demo').style.fontSize='12px';
} else if(document.getElementById('demo').style.fontSize=='12px') {
document.getElementById('demo').style.fontSize='35px';
}
DEMO

Try This :
<!DOCTYPE html>
<html>
<body>
<h2>What Can JavaScript Do?</h2>
<p id="demo" onclick="myFunction()">Click me.</p>
<script>
function myFunction() {
var el = document.getElementById('demo');
var style = window.getComputedStyle(el, null).getPropertyValue('font-size');
var fontSize = parseFloat(style);
if (fontSize==16) {
document.getElementById('demo').style.fontSize='12px';
} else if(fontSize==12) {
document.getElementById('demo').style.fontSize='35px';
}
}
</script>
</body>
</html>

It is exactly what Suren Srapyan has said, but here is the correct code:
<!DOCTYPE html>
<html>
<body>
<h2>What Can JavaScript Do?</h2>
<p id="demo" onclick="myFunction()">Click me.</p>
<script>
function myFunction() {
if (document.getElementById('demo').style.fontSize === '35px') {
document.getElementById('demo').style.fontSize='12px'
} else if(document.getElementById('demo').style.fontSize ==='12px') {
document.getElementById('demo').style.fontSize='35x'
}
}
</script>
</body>
</html>

Related

What language is this and how do I run it?

I'm doing one of those codding maze challenges and I got stuck as I decoded a base64 image which contained a code block that i need to use to progress though, I'm not sure how to use it.(I know nothing about frontend languages so I assume its some form of js or api call)
function solutionChecker(url, queryParams, method, headers){
var a = headers[queryParams.b];
var altwo = a < 2;
if(!alttwo){
headers.clue="output";
}
return a == c && method === "PATCH";
}
Seems like javascript.
You can embed in a simple html and try it.
NOTE: Supply valid parameters to run the function properly...
<!DOCTYPE html>
<html>
<head>
<script>
function otherFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
function solutionChecker(url, queryParams, method, headers){
var a = headers[queryParams.b];
var altwo = a < 2;
if(!alttwo){
headers.clue="output";
}
return a == c && method === "PATCH";
}
</script>
</head>
<body>
<h2>JavaScript in Head</h2>
<p id="demo">A Paragraph.</p>
<button type="button" onclick="solutionChecker('someUrl',params,'METOD',headers)">Try it</button>
</body>
</html>

My label is not counting up

Why is this code not working? So far I have only got it to work as an input. I need it to work as a label or span. I need the label to count up 1 number on every click.
<html>
<head>
<script type="text/javascript">
var a = 1;
function increase () {
document.getElementById("text").value=a;
a=a+1;
}
</script>
</head>
<body>
<button type="button" onclick="increase()">show</button>
<label type="text" id="text">0</label>
</body>
​
Your increase() function should look like this:
function increase() {
a++;
document.getElementById("text").innerHTML = a;
}
The reason its not working is that label or span doesn't have value attribute. You should use innerHTML instead.
Value attribute is present only on <input> tags. For every other tag (like <span>, <div>, <label>) you should use innerHTML.
Edit
To add clarity, the above code is only the increment() function. The entire code should look like this:
var a = 0;
function increase() {
a++;
document.getElementById("text").innerHTML = a;
}
Considering John Hascall comment, a++ can be placed after document.getElementById("text").innerHTML = a.
var a = 0;
function increase() {
a++;
document.getElementById("text").innerHTML = a;
}
<button onclick="increase()">Click</button>
<label id="text">0</label>
try this fiddle
i have tried parseInt()
var a = parseInt(document.getElementById("text").innerHTML);
a++;
console.log(a);
document.getElementById("text").innerHTML = a;
You need to use document.getElementById("text").innerHTML=a, because the value of a <label> does not define its inside text.
Your example would then look like this:
<html>
<head>
<script type="text/javascript">
var a = 1;
function increase() {
a++;
document.getElementById("text").innerHTML = a;
}
</script>
</head>
<body>
<button type="button" onclick="increase()">show</button>
<label type="text" id="text">0</label>
</body>

JavaScript - How can I 'translate' the input to something different

I'm trying to make a program where if you for example type in "less" in the textarea the output should show "<". What is the best way to do this?
This is how far I've gotten:
<!doctype html>
<html lang="en">
<head>
<title>Group 7 - Deckcode to JavaScript</title>
</head>
<body>
<h1>Group 7 - Deckcode to JavaScript</h1>
<p>Input your deckode below:</p>
<textarea id="myTextarea"></textarea>
<button type="button" onclick="myFunction()">Translate</button>
<p id="demo"></p>
<script>
function myFunction() {
var input
if (myTextarea == "less") {
console.log("<");
}
}
</script>
</script>
</body>
</html>
You're trying to fish values out of the DOM incorrectly. Use document.getElementById to locate the element in the DOM, and take its value for the value you require.
function myFunction() {
var textAreaValue = document.getElementById("myTextarea").value;
if (textAreaValue == "less") {
console.log("<");
}
}
I suggest using an object like this:
var translations = {};
translations["less"] = "<";
translations["greater"] = ">";
And then in your function you do like this:
function myFunction() {
var value = document.getElementById("myTextarea").value;
console.log(translations[value] ? translations[value] : "No translation found");
}
It would also be easy to add more translations e.g. based on data from a database or similar.
as and alternative to IF-condition, you can use
if (textAreaValue.indexOf("less") > -1) {
console.log("<");
}
so if the text area contains "less" text then the console prints "<"
indexOf method

Simple javascript onClick Text change

I am new to StackExchange. I have very basic question in JavaScript.
I have created simple JavaScript function changing the color of the text using onClick in that same function i want to change the last word
Here is the example
<!doctype html>
<head>
<title>
Sample Javascript
</title>
<script type="text/javascript">
function colorchange(myid)
{
x = document.getElementById('sample_text');
x.style.color = "red";
x.style.fontWeight = "bold";
text = document.getElementById('sample_text1');
}
</script>
</head>
<body>
<div id="sample_text" onClick="colorchange(1)">Welcome to <span onClick="colorchange(2)" id="sample_text1">Mahaweb</span></div>
</body>
</html>
Kindly help me I want to change the span inner content with the same function.
<!doctype html>
<head>
<title>
Sample Javascript
</title>
<script type="text/javascript">
function colorchange()
{
x = document.getElementById('sample_text');
x.style.color = "red";
x.style.fontWeight = "bold";
document.getElementById('sample_text1').innerHTML = "text";
}
</script>
</head>
<body>
<div id="sample_text" onClick="colorchange()">Welcome to <span onClick="colorchange()" id="sample_text1">Mahaweb</span></div>
</body>
</html>
<script type="text/javascript">
function colorchange(myid)
{
x = document.getElementById('sample_text');
x.style.color = "red";
x.style.fontWeight = "bold";
text = document.getElementById('sample_text1');
if(myid==2){
text.innerHTML="YOUR TEXT HERE";
}
}
</script>
If I understand you correctly, you want to change the span's inner text. As you have already selected the span (var text), try:
text.innerHTML="desiredText";
You can achieve this by changing the property "innerHTML" of your text Element.
Something like:
text.innerHTML = "your_change";
But this is pretty basic stuff. Make sure to checkt out some documentations ;)
I believe this is what you are after (I am using jQuery, a javascript library, which makes this sort of thing much easier)
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$('#sample_text').click(function(){
$(this).find('span').css('color', 'red').css('font-weight', 'bold');
});
</script>

How do I control the font weight of any text within a paragraph (<p> tag) within braces or curly brackets { } using JavaScript

I would like to be able to control the font-weight of text if bracketed inside a p tag using JavaScript.
For instance:
The cow jumped over the {moon}. font-weight within {} would be increased.
This so the end user can type this into a text area and on submit the would print to page altering the font-weight within the braces or curly brackets.
Any help on this would be great.
Here is how you can do this:
var ps = document.getElementsByTagName('p');
foreach = Array.prototype.forEach;
foreach.call(ps, function (p) {
var content = p.innerHTML;
p.innerHTML = content.replace(/\{(.*?)\}|\((.*?)\)/g, function (m) {
return '<span style="font-weight: bold;">' + m + '</span>';
});
});
​
And of course a fiddle.
For the example you need just pure JavaScript, no additional libraries.
Edit:
If you don't want to see the brackets in the result you can use:
var ps = document.getElementsByTagName('p');
foreach = Array.prototype.forEach;
foreach.call(ps, function (p) {
var content = p.innerHTML;
p.innerHTML = content.replace(/\((.*?)\)|\{(.*?)\}/g, function (m) {
return '<span style="font-weight: bold;">' + m.replace(/[\(\)\{\}]/g, '') + '</span>';
});
});
Fiddle: http://jsfiddle.net/ma47D/4/
​
Best regards!
You can do it with mootools like this:
window.addEvent('domready', function()
{
$$('P').each(function(p)
{
p.set('html', p.get('text').replace(/{([^\}]*)*}/g,"<b>$1</b>"));
});
});​
domready is important because it must be done after page is completely loaded. converting to jquery would not be so hard.
http://jsfiddle.net/Smw7Q/1/
Locally you can handle it like this:
<!DOCTYPE html>
<html>
<head>
<script>
function transfer(){
document.getElementById("result").innerHTML=document.getElementById("demo").value.replace(/{/g,'<strong>').replace(/}/g,'</strong>');
}
</script>
</head>
<body>
Input: <input type="text" name="input" id="demo"><br>
<input type="button" value="Submit" onclick="transfer();">
<p id="result"></p>
</body>
</html>
If you submit the text to server, the magic can be done similarly at server side.
My suggestion
<!DOCTYPE html>
<html>
<head>
<style>
p span {
font-size:1.5em;
}
</style>
<script>
function regex(){
document.getElementById("output").innerHTML=
document.getElementById("input").value.replace(/{(.*?)}/g, "<span>$1</span>");
};
</script>
</head>
<body>
<p id="output"></p>
<textarea id="input" rows="30" cols="80"></textarea>
<input type="button" value="Input" onclick="regex();"/>
</body>
<html>
Of course, prior to submitting, you need to sanitize your data.
If tried something, but I'm sure there are more elegant solutions.
http://jsfiddle.net/xT7Fg/
$(document).ready(function(){
$(tb).blur(function(){
var str = '';
var nextFont = 0;
$.each($(tb).val(),function(i,char){
if(nextFont == 0){
if(char == '{'){
if($(tb).val().indexOf(i,'}')){
str += '<font size="15">';
nextFont = $(tb).val().indexOf('}', i);
} else {
str += char;
}
} else {
str += char;
}
} else if (nextFont === i) {
str += '</font>';
nextFont = 0;
} else {
str += char;
}
});
$("#txt").html(str);
});
});

Categories

Resources