Creating a css class with a Javascript object or var [duplicate] - javascript

This question already has answers here:
How to dynamically create CSS class in JavaScript and apply?
(17 answers)
Closed 5 years ago.
Is it possible to create a css class based on a javascript object or variable?
An example would be if you had an input where you can enter a hex code. I can extract the value using javascript and set it to a var.
I can then use this var to set inline styles with javascript thus changing the color of text on the page. However is there a way I could use this var and create a css class? Rather than go through all the elements of the page and set the color, I'd rather add a class on one element of the page that then have the styles nested within that class to cascade to other elements.

Lots of ways to dynamically alter css styling after page load.
If you want to make a change that is applied as if it was a normal css script you can add a style tag to the header via javascript.
eg.
var color = "blue" ; // from your input
var element = document.createElement("style");
element.id = "myStyleId" ; // so you can get and alter/replace/remove later
element.innerHTML = ".myClass {color:" + color + ";}" ; // css rule
var header = document.getElementsByTagName("HEAD")[0] ;
header.appendChild(element) ;

Something like this buddy?
https://jsfiddle.net/BillyG83/hcek46a1/2/
made just for you, happy Friday
here is the code
<!DOCTYPE html>
<html>
<head>
<title>Test HTML</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<input type="text" id="textBox"/>
<input type="button" id="submit" value="Go"/>
</body>
<script type="text/javascript">
$("#submit").click(function(){
var textBoxValue = $("#textBox").val();
if (textBoxValue.length == 0) {
alert("you didnt enter a value");
} else if (textBoxValue.length < 6) {
alert("you only entered " + textBoxValue.length + " chacters, a HEX code needs 6");
} else if (textBoxValue.length == 6) {
var newHEXcode = "#" + textBoxValue;
alert("new HEX code = " + newHEXcode)
} else {
alert("you only entered " + textBoxValue.length + " chacters, thats too many, a HEX code needs 6");
}
});
</script>
</html>

In this example if you enter hex value like FFFF00 or 800000 or FF0000 then it will change the background css of the text Hello Pratik Ghag!.
$("#txtInput").change(function(){
var color = "#"+$("#txtInput").val();
$(".spnMessage").css("background",color);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Enter hex color code:</p>
<input id="txtInput" /><br>
<span class="spnMessage">Hello Pratik Ghag!</span>

Related

Basic JavaScript how to call a function from the HTML page

I have just started JavaScript basics and I'm struggling with this:
HTML page has the following:
<body>
<p id="number">5</p>
<button id="buttonX" onclick="calcSquare()">Click here!</button>
</body>
This page should call the function calcSquare(), which fetches the value of the element, calculate its square, and print in the console: The square of 5 is 25. The HTML page loads the code, so I can refer to the page with the document keyword. My js code is following:
function calcSquare() {
var number = document.getElementById("number").value;
console.log("The square of" + number + "is" number*number);
}
Can someone tell me what is wrong with it? Thank you so much! Beginners struggles...
The problem is with your function itself.
Keep in mind that .value is used with an input element. So you can use .innerHTML or .textContent.
You forgot also the sign + after "is".
Look at this code snippet .
function calcSquare() {
var numbElementcontent = document.querySelector('#number').innerHTML;
numbElementcontent = parseInt(numbElementcontent);
console.log("The square of " + numbElementcontent + " is " + numbElementcontent * numbElementcontent);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<p id="number">5</p>
<button id="buttonX" onclick="calcSquare()">Click here!</button>
<script>
function calcSquare() {
var numbElementcontent = document.querySelector('#number').innerHTML;
numbElementcontent = parseInt(numbElementcontent);
console.log("The square of " + numbElementcontent + " is " + numbElementcontent * numbElementcontent);
}
</script>
</body>
</html>
Instead of .value use .innerHTML, and you are missing sign + after "is"
You need to get textContent, and make some changes in your function calcSquare()
function calcSquare() {
var number = document.getElementById("number");
var number = number.textContent;
console.log("The square of" , number , "is" , number*number);
}
<body>
<p id="number">5</p>
<button id="buttonX" onclick="calcSquare()">Click here!</button>
</body>
And if you are use an input-field you make it more dynmaic :) and if the is target an input you can use the .value
Be sure you cast every time your vars into the right type before do math (parseInt, parseFloat etc)
And because you are new on JS please deal with JS Security - it is very important for your future dev..
https://snyk.io/learn/javascript-security/
https://glebbahmutov.com/blog/disable-inline-javascript-for-security/
Try this . Foe elements such as P or Div You have to ue textContent or innerHTML to get the data inside the tag. You missed string concatenation after "is" too
function calcSquare() {
var number = document.getElementById("number").textContent;
console.log("The square of" + number + "is" +number*number);
}
<body>
<p id="number">6</p>
<button id="buttonX" onclick="calcSquare()">Click here!</button>
</body>
<script>

I'm trying to increase a value when clicking and value returning NaN [duplicate]

This question already has answers here:
why the result is NaN?
(4 answers)
Closed 1 year ago.
I've tried a lot of stuff, however I don't know any JavaScript. All of the JavaScript in the code is copied from stack overflow and other sources. The only thing I know how to use is HTML and I'm still very new. (it might also include some CSS which I also don't know at all)
The <!--<button id="bigButton" onclick="bigBottlePress()"><img src="Images/BigBottle.png"></button>--> is a failed thing so ignore it lol.
<html>
<head>
<meta charset="utf-8">
<title>Bottle Clicker</title>
</head>
<body>
<img src="Images/BigBottle.png" height="500">
<!--<button id="bigButton" onclick="bigBottlePress()"><img src="Images/BigBottle.png"></button>-->
<br>
<br>
<input type="text" id="hydrationLevelDisplay" placeholder="Hydration Level: " disabled style= text-align:center>
<script>
var hydrationLevel = 0
function bigBottlePress() {
var hydrationLevel = hydrationLevel + 1
document.getElementById("hydrationLevelDisplay").value = "Hydration Level: " + hydrationLevel;
document.title = "Hydration Level: " + hydrationLevel;
}
</script>
</body>
</html>
You have already declared hydrationLevel outside function, so don't need to redclare it. Just change,
var hydrationLevel = hydrationLevel + 1
to
hydrationLevel = hydrationLevel + 1
create a button -> id:btn
create a result div or p or h1 -> id:hydrationLevel
select the button, add event listener
document.getElementById('btn').addEventListener('click', incrementLevel)
let hydrationCount = 0;
function incrementLevel() {
hydrationCount += 1;
document.getElementById('hydrationLevel').textContent = hydrationCount;
}
I'd encourage you to use event listeners this way. not inline that's why I provided this solution.

How do I get text in HTML and replace it in my Javascript variable? [duplicate]

This question already has answers here:
How do I replace a bit of text with string variable in javascript?
(2 answers)
Closed 7 years ago.
On click I'm getting text in HTML. I have a variable in Javascript called content I want to get the text input and change a part of the Javascript variable.
HTML CODE:
<html>
<head>
<link href="latent.css" rel="stylesheet">
</head>
<body>
<button onclick="makePage()">Generate Link</button>
Image link: <input type="text" name="img" id = "img"><br>
Content: <input type="text" name="content" id = "content"><br>
<script src="makePage.js">
</script>
<script>
var img = document.getElementById("img").value;
var content = document.getElementById("content").value;
</script>
</script>
</body>
</html>
JAVASCRIPT CODE:
function makePage(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200)
alert("webpage " + xmlhttp.responseText + " was successfully created!");
}
var content = '<html><head><meta name="something:something" content=""></head><body></body></html>';
xmlhttp.open("GET","http://ahansabharwal.com/makePage.php?content=" + content, true);
xmlhttp.send();
}
In the variable called content I want to replace the image link in the content of the twitter:image
meta name="twitter:image" content="http://graphics8.nytimes.com/images/2012/02/19/us/19whitney-span/19whitney-span-articleLarge.jpg"
AND
I would like to replace the content of the meta name="twitter:description" content="NEWARK - The guest list and parad[....]
with the content inputted by the user.
I solved it by using replace();
What I did was:
var contentJS = document.getElementById('contentInput').value;
var contentNew = content.replace("info", contentJS);
I replaced the context to just info. Now it stores the value of the user input, then searches for the value of 'info' in the string. When it finds it, it simply gets replaced with the user input (contentJS)

How can I use html tag in this javascript? [duplicate]

This question already has answers here:
Changing the way a JavaScript Alert() or Prompt() looks
(4 answers)
Closed 8 years ago.
How can I use html tag in this javascript?
First of all, why <br> doesn't work in prompt. Secondly, why can't I use tags for this code (poundOne.pound) to make the font larger by using css or html code such as <h1>, <h2>, <h3>... or <div style="......">?
<html>
<head>
<script type="text/javascript">
function poundToKgConvertor( pound ){
this.pound = pound;
this.convertorDon = convertor;
}
function convertor(){
var convert = this.pound * 0.453592;
return convert;
}
var poundOne = new poundToKgConvertor(prompt ("Convert Pound to Kilogram!<br> Please insert your number of pound!"));
</script>
</head>
<body>
<script type="text/javascript">
document.write(poundOne.pound + " Pound = " + poundOne.convertorDon() + " <b>Kilogram</b>");
</script>
</body>
</html>
You can't use HTML in prompt/alert dialogs. However you can use new line characters:
prompt ("Convert Pound to Kilogram!\n Please insert your number of pound!");

How to get substring using Dojo and javascript

Good Day,
I am a newbie learning Javascript & Dojo and I typically learn by picking apart other parts of running code.
I am confused as to how to get a substring value from the following code (from the ArcGIS Sandbox):
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=7, IE=9, IE=10">
<!--The viewport meta tag is used to improve the presentation and behavior of the samples
on iOS devices-->
<meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no">
<title>Query State Info without Map</title>
<script src="http://js.arcgis.com/3.6/"></script>
<script>
dojo.require("esri.tasks.query");
dojo.require("esri.map");
var queryTask, query;
require([
"esri/tasks/query", "esri/tasks/QueryTask",
"dojo/dom", "dojo/on", "dojo/domReady!"
], function(
Query, QueryTask,
dom, on
){
queryTask = new QueryTask("http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Demographics/ESRI_Census_USA/MapServer/5");
query = new Query();
query.returnGeometry = false;
query.outFields = ["SQMI","STATE_NAME","STATE_FIPS","SUB_REGION","STATE_ABBR","POP2000","POP2007","POP00_SQMI","POP07_SQMI","HOUSEHOLDS","MALES","FEMALES","WHITE","BLACK","AMERI_ES","ASIAN","OTHER","HISPANIC","AGE_UNDER5","AGE_5_17","AGE_18_21","AGE_22_29","AGE_30_39","AGE_40_49","AGE_50_64","AGE_65_UP"];
on(dom.byId("execute"), "click", execute);
function execute(stateName) {
query.text = dom.byId("stateName").value;
//execute query
queryTask.execute(query, showResults);
}
function showResults(results) {
var s = "";
for (var i=0, il=results.features.length; i<il; i++) {
var featureAttributes = results.features[i].attributes;
for (att in featureAttributes) {
s = s + "<b>" + att + ":</b> " + featureAttributes[att] + "<br>";
}
s = s + "<br>";
}
dom.byId("info").innerHTML = s;
}
});
</script>
</head>
<body>
US state name :
<input type="text" id="stateName" value="California">
<input id="execute" type="button" value="Get Details">
<br />
<br />
<div id="info" style="padding:5px; margin:5px; background-color:#eee;">
</div>
</body>
</html>
All I would like to do is pick apart the input (in this case the id="stateName" which is the word California).
So a silly example would be substituting the following code to get the first 10 characters of when someone types in 'California is on the west coast'
query.text = dom.byId("stateName").substring(0,10);
This is really so I can support other queries but I figured if I can do a substring on this input then it is really the same anytime when I query other attributes.
Thanks in advance for a newbie !
You need to get the innerHTML of your DOM element
query.text = dom.byId("stateName").value.substring(0, 10);
As Thomas Upton correctly pointed out the correct form would be:
dom.byId("stateName").value.substring(0, 10);
apparently the following also works
dom.byId("stateName").value.substr(0, 10);
As noted in comments, a call to .value will deliver what you need. Substring is a method on the string prototype See here. However, dom.byId returns a domNode. You don't want the substring of the domNode itself, you want the substring of the text value of the domNode. On inputs this is easily done with .value and is commonly done with .textContent and .innerHTML as well.

Categories

Resources