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>
Related
So I am currently trying to find out how to select text between two characters(for the example I will use a slash / )
Here is what I have so far.
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function startWhenLoaded() {
var text = $("p").text();
var secondStartingPoint, startPointOne, startPointTwo;
if (text.indexOf("/", 0) !== -1) {
//I did -1 because indexOf returns -1 if nothing is found.
/*Also, the second argument in indexOf() acts as my starting
point for searching.*/
secondStartingPoint = text.indexOf("/") + 1;
startPointOne = text.indexOf("/") + 1;
if (text.indexOf("/", secondStartingPoint) !== -1) {
startPointTwo = text.indexOf("", secondStartingPoint) + 1;
var selectedText = slice(startPointOne, startPointTwo);
$("body").append("<p>" + selectedText + "</p>");
//but nothing happens.
}
}
</script>
</head>
<body onload="startWhenLoaded()">
<p>/can I select and duplicate this?/</p>
</body>
</html>
But it doesn't do anything.
It could be achieved simply by using a regex like :
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function startWhenLoaded() {
var text = $("p").text();
var extracted = text.match(/\/(.*)\//).pop();
alert('The extracted text is :'+extracted);
}
</script>
</head>
<body onload="startWhenLoaded()">
<p>Some text here in the start /can I select and duplicate this?/ Some extra text at the end</p>
</body>
</html>
Regex is simplest and easiest way to get your solution.
use exec() function to get text between '/';
console.log(/^\/(.*)\/$/.exec('/some text, /other example//'))
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>
Thank You. I had previously done it like many of you have suggested but the issue I had/have is that my project is a text based game changing according to my choices(Option 1 or Option 2), I attempted to use If statements so that the code would run from one option to the next, with If statements within each other until the end, each option contained within what option you pressed to trigger it. Perhaps that is not the way to got about it.
<!DOCTYPE html>
<head>
<link rel="stylesheet" type="text/css" href="dungeonStyle.css">
</head>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
function codeAddress() {
document.getElementById("gameText").style.visibility = "hidden";
document.getElementById("optionOne").style.visibility = "hidden";
document.getElementById("optionTwo").style.visibility = "hidden";
document.getElementById("bTEXT").style.visibility = "hidden";
document.getElementById("bTEXT2").style.visibility = "hidden";
}
window.onload = codeAddress;
</script>
</head>
<body>
<div id="startup">
<div class="header">
<h1>DUNGEON DUELER</h1>
</div>
<p id="subtitle">The Interactive Novel</p>
<p id="gameDescription">Your choices forge your destiny</p>
<button id = "startButton" onclick="startGame()">Click to begin!
</button>
<p id="gameText">
You're in search of gold and glory. Conquer this dungeon and it shall be yours!
</p>
<button id = "optionOne" onclick="One()">Option One</button>
<button id = "optionTwo" onclick="Two()">Option Two</button>
<p2 id = "bTEXT">Begin </p2>
<p3 id = "bTEXT2">stuff</p3>
<Script>
function startGame() {
document.getElementById("startButton").style.visibility = "hidden";
document.getElementById("subtitle").style.visibility = "hidden";
document.getElementById("gameDescription").style.visibility = "hidden";
document.getElementById("gameText").style.visibility = "visible";
document.getElementById("optionOne").style.visibility = "visible";
document.getElementById("optionTwo").style.visibility = "visible";
document.getElementById("bTEXT").style.visibility = "visible";
document.getElementById("bTEXT2").style.visibility = "visible";
}
</Script>
the issue
if (function one.onclick){
var str = document.getElementById("gameText").innerHTML;
var txt = str.replace("You're in search of gold and glory. Conquer this dungeon and it shall be yours!","blah blah blah");
document.getElementById("gameText").innerHTML = txt;
}
</script>
</div>
</body>
</html>
css is on separate file .
I'll attempt to explain myself the best I can. I'm making a text based game with two button that determine the results. I am trying so that If option one is pressed run the code (change the text thats displayed and hp system) else do other code/option.
My first upload, apologies for any errors. Newbie.
You need to define the Event handlers for the onclick events One and Two.
In the functions One and Two you can define the logic which needs to be implemented. The event handler can be either a function Expression or a function declaration. In your case it is a function Declaration. Also, you can pass the MouseEvent Object in the parameters which contains the information of the event encapsulated in the object, which can provide helpful information about the event.
Change the Script to script
function One(){
var str = document.getElementById("gameText").innerHTML;
var txt = str.replace("You're in search of gold and glory. Conquer this dungeon and it shall be yours!","blah blah blah");
document.getElementById("gameText").innerHTML = txt;
}
function Two(){
// The other logic
}
<!DOCTYPE html>
<head>
<link rel="stylesheet" type="text/css" href="dungeonStyle.css">
</head>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
function codeAddress() {
document.getElementById("gameText").style.visibility = "hidden";
document.getElementById("optionOne").style.visibility = "hidden";
document.getElementById("optionTwo").style.visibility = "hidden";
document.getElementById("bTEXT").style.visibility = "hidden";
document.getElementById("bTEXT2").style.visibility = "hidden";
}
window.onload = codeAddress;
</script>
</head>
<body>
<div id="startup">
<div class="header">
<h1>DUNGEON DUELER</h1>
</div>
<p id="subtitle">The Interactive Novel</p>
<p id="gameDescription">Your choices forge your destiny</p>
<button id = "startButton" onclick="startGame()">Click to begin!
</button>
<p id="gameText">
You're in search of gold and glory. Conquer this dungeon and it shall be yours!
</p>
<button id = "optionOne" onclick="One()">Option One</button>
<button id = "optionTwo" onclick="Two()">Option Two</button>
<p2 id = "bTEXT">Begin </p2>
<p3 id = "bTEXT2">stuff</p3>
<script>
function startGame() {
document.getElementById("startButton").style.visibility = "hidden";
document.getElementById("subtitle").style.visibility = "hidden";
document.getElementById("gameDescription").style.visibility = "hidden";
document.getElementById("gameText").style.visibility = "visible";
document.getElementById("optionOne").style.visibility = "visible";
document.getElementById("optionTwo").style.visibility = "visible";
document.getElementById("bTEXT").style.visibility = "visible";
document.getElementById("bTEXT2").style.visibility = "visible";
}
</script>
if (function one.onclick){
should be
function One(){
Two things here. First, i didn't saw the opening script tag in your code (and the first script tag, change Script to script :
<script>
if (function one.onclick){
var str = document.getElementById("gameText").innerHTML;
var txt = str.replace("You're in search of gold and glory. Conquer this
dungeon and it shall be yours!","blah blah blah");
document.getElementById("gameText").innerHTML = txt;
}
</script>
Second, and most important, the IF condition:
<script>
function one() {
var str = document.getElementById("gameText").innerHTML;
var txt = str.replace("You're in search of gold and glory. Conquer this
dungeon and it shall be yours!","blah blah blah");
document.getElementById("gameText").innerHTML = txt;
}
</script>
Try to always use the console.log(), it is your friend always, hehe!
<!DOCTYPE>
<html>
<script>
var btn = document.createElement("BUTTON");
var txt = document.createTextNode("Text");
btn.appendChild(txt);
document.body.appendChild(btn);
</script>
</html>
I just started learning HTML and JavaScript.
I was expecting the above code to output a button with a word "text" in it.
Unfortunately, the output was blank. Can someone explain to me why this code didn't work?
your script won't do anything because it in head so your script run before body you need use window.onload function like this
<!DOCTYPE>
<html>
<script>
window.onload = function(){
var btn = document.createElement("BUTTON");
var txt = document.createTextNode("Text");
btn.appendChild(txt);
document.body.appendChild(btn);
}
</script>
</html>
jsve is close. You need to make sure the code isloaded when the body loads. This is done by calling the body's onload function, like this...
<!doctype html>
<html>
<head>
<script>
function init(){
var btn = document.createElement("BUTTON");
var txt = document.createTextNode("Text");
btn.appendChild(txt);
document.body.appendChild(btn);
}
</script>
</head>
<body onload="init()"></body>
</html>
You need to run that code after the body is loaded:
<!doctype html>
<html>
<head>
<script>
function addBtn() {
var btn = document.createElement("button");
var txt = document.createTextNode("Text");
btn.appendChild(txt);
document.body.appendChild(btn);
}
</script>
</head>
<body onload="addBtn()"></body>
</html>
A few more comments:
You also need to update your DOCTYPE to <!doctype html> as I show above.
Wrap your <script> tag inside of a <head> tag.
No need to capitalize button.
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