This question already has answers here:
How do I change the background color with JavaScript?
(22 answers)
Closed 2 years ago.
I'm trying to make a string in JavaScript that can be changed through a button later on. I want this string to contain colors for my index.html to use to change the background. How do I call the variable from JavaScript into HTML while still keeping the ability to change the variable at anytime and having the webpage update to display the changes. (sorry if this is confusing)
example:
script.js
var color = "";
index.html
<!DOCTYPE html>
<html>
<head>
<title>Type</title>
</head>
<body style="background-color:"color";">
<h1><center>Type</center></h1>
<p><center>This is a test sentence</center></p>
</body>
<script src="script.js"></script>
</html>
You could try something like this:
/* This is script.js */
var color = "black";
body {
color: white;
}
<!DOCTYPE html>
<html>
<head>
<title>Type</title>
</head>
<body onload="document.body.style.backgroundColor = color;">
<h1>
<center>Type</center>
</h1>
<p>
<center>This is a test sentence</center>
</p>
</body>
<script src="script.js"></script>
</html>
This sets the color inline, which is (sort of?) what I believe you wanted, except you just use the onload attribute instead of using the style attribute.
You want to bind the background-color CSS property to the JavaScript color variable, but there's no direct way to do that. Instead of updating a JavaScript variable, just update the background-color of the body element.
document.querySelector('body').style.backgroundColor = 'red';
There are a lot of JavaScript frameworks that support binding JavaScript data to DOM elements, but at the end of the day, they're all just copying values from JavaScript into the DOM, the same as we're doing here.
If you really want to have a JavaScript variable, you can have it, then call some function like updateBackgroundColor, that copies the color from the variable into the DOM.
Related
This question already has answers here:
Get a CSS value with JavaScript
(8 answers)
Closed 2 years ago.
console.log(document.querySelector(".green").style.backgroundColor);
// gives an empty string as a result in console
.green {
width: 200px;
height: 200px;
background-color: green;
}
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="src/styles.css">
</head>
<body>
<div class="green"></div>
<script src="src/index.js">
</script>
</body>
</html>
I know that I can also use
window.getComputedStyle(document.querySelector(".green")).backgroundColor;
which is mentioned in this answer
but I want to know the reason behind this that why it is giving an empty string as a result.
.style contains only inline styles (set via that property, or the HTML attribute with the same name). It's not affected by style sheets at all. getComputedStyle gets you the current effective value for that property, regardless of where it came from.
You want the computed element style:
console.log(getComputedStyle(document.querySelector(".green"), null).getPropertyValue("background-color"));
As is stated in the MDN Page for the element.style property:
The style property is used to get as well as set the inline style of an element.
Your element does not have a style attribute in which the background color is set-- as such, <yourelement>.style.backgroundColor returns an empty string. This is why getComputedStyle exists-- to allow you to interrogate the actual final/applied styles on an element, not merely those that might be inline on the element as a style attribute.
In my project i have a javascript file that contain a variable like this one:
var htmlcode = "<html><body><h1>My First Web Page</h1><p>My first paragraph.</p></body></html>"
i would to know if in javascript exist a command for render my htmlcode variable ina real html page, i think to use a button for open that page.
So many thanks in advance
Using jQuery, you can use $('html') to select the HTML tag, and change its content using $('html').html("some new content"):
$("#changeHTML").click(function() {
$('html').html("<body><div style='color:red;'>New sample text</div></body>");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<body>
Sample text
<button id="changeHTML">Click me</button>
</body>
</html>
Using plain Javascript, you can use document.documentElement to select the document's HTML tag (source), and changing this variable's innerHTML should do the trick.
I don't know how to declare a variable here in javascript. I have an example situation that if the paragraph is equals to a, the alert will popup.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<p id="sample">a</p>
</body>
</html>
<script type="text/javascript">
var sample = getElementById('sample');
if (sample == "a") {
alert("Correct")
};
</script>
You're declaring your variable just fine, however if you want the text within the element, you also need to use the innerHTML property. And when you use the getElementById method, you need to use it on the document object like document.getElementById:
var sample = document.getElementById('sample');
if (sample.innerHTML == "a") {
alert("Correct")
};
<p id="sample">a</p>
sample is a variable and you are correct but it is storing a reference to a DOM Element with id sample. To get the inner html of that you need
var sample = getElementById('sample').innerHTML;
Also, use === over == for no casting etc. Refer here
I will recommend you to have a quick look at JS from w3schools and then move to MDN. Nobody will report you here if you show your efforts, so relax :).
Your declaration is fine, but the assignment part is missing document as the object which has the .getElementById method. Then, once you have the reference to the element, you then need to access its content with .textContent (you can't compare the entire element to a value that the element might contain). As a side note on this, when the string you wish to set/get doesn't contain any HTML, you should use .textContent so that the browser doesn't parse the string for HTML unnecessarily. Often, people will suggest that the content of an element should be gotten/set using .innerHTML and, while that will work, it's wasteful if the string doesn't contain any HTML.
Also, the <script> must be located within the head or the body, not outside of them. I would suggest placing it just prior to the closing body tag so that by the time the processing reaches the script, all of the HTML elements have been parsed into memory and are available.
Lastly (and this is really just a side point), an HTML page also needs the title element to have something in it, otherwise it won't be valid. While browsers don't actually do HTML validation, it's important to strive for valid HTML so that you can be sure that your pages will work consistently across all devices. You can validate your HTML at: http://validator.w3.org.
<!DOCTYPE html>
<html>
<head>
<title>Something Here</title>
</head>
<body>
<p id="sample">a</p>
<script type="text/javascript">
var sample = document.getElementById('sample');
if (sample.textContent == "a") {
alert("Correct")
};
</script>
</body>
</html>
<html>
<body style="background-color: returnBlue()">
<em>Boy, I sure do wish I existed on something that was blue.</em>
</body>
</html>
The style doesn't make the body blue
function returnBlue()
{
return 'blue';
}
How can I make the returnBlue() function run and return to an attribute? Thanks!
In short, you can't. The style attribute is parsed as CSS and what you're trying to execute is a JavaScript function. There's no way to call JS from CSS.
What you can do, is get a reference to the element in your script and change it manually.
var body = document.body;
body.style.backgroundColor = returnBlue();
However, rather than trying to style your nodes manually with JavaScript you're probably better defining your styles in CSS classes.
/* style.css */
.blue-bg {
background-color: blue;
}
Then use the class on your <body> tag.
<!-- index.html -->
<head>
<link rel="stylesheet" href="style.css" />
</head>
<body class="blue-bg"></body>
If you really want to derive your styles programmatically, then you're best off taking a look at a language like SCSS which supports functions.
You can't do this in CSS, you can only do it with JS.
document.body.style.backgroundColor = returnBlue();
Also, why use returnBlue(); when you are trying to set it to blue? If you want to change the background color using JS just do
document.body.style.backgroundColor = color;
UPDATE:
If you wanted to, you could use JQuery's .css() method and do $("body").css("background-color: blue;")
This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Creating a page that updates without reloading
I want to get the content of an HTML page from it's URL and put it somehwere in the current document. The pseudo-code below shows the approach I want to take:
<!DOCTYPE html>
<html>
<body>
<p id="text"></p>
<script type="text/javascript">
function getPageText(htmlPage)
{
//comment: How do I get innerHTML?
var text = htmlPage.body.innerHTML;
//comment: How do I have to return?
return text;
}
document.getElementById("text").innerHTML=getPageText("https://google.com");
</script>
</body>
</html>
The name of the technique you are looking for is AJAX --- You need to download the remote page (and it has to allow you to) in order for javascript to get the content of the page.
see another answer for an overview of that technique --- https://stackoverflow.com/a/10168402/473914
you need to extract content from google and then you could use innerHtml. Alternatively you can use iframe and wrap scr dynamically or statically. code for wraping scr dynamically is as follow.
a.html
<html>
<head>
<script>
function getPageText(url){
document.getElementById("container").setAttribute("src",url);
}
getPageText("https://www.google.com");
</script>
</head>
<body>
<iframe id='container'></iframe>
</body>
</html>