Take a look at this example code, which doesn't work:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
<!--
function moveMe() {
document.getElementById('moveme').top = 200;
document.getElementById('moveme').style.backgroundcolor = 'green';
document.getElementById('writeme').innerHtml = 'abc';
alert('called!');
}
// -->
</script>
<style type="text/css">
.moveable {
position: absolute;
top: 30px;
left: 200px;
width: 100px;
height: 100px;
background-color: yellow;
}
#writeme {
background-color: red;
color: white;
}
</style>
</head>
<body>
<div id="moveme" class="moveable" onClick="moveMe()">
<p id="writeme">Hello!</p>
</div>
</body>
</html>
When I click on the text the alert is displayed, but nothing is changed in the document. The paragraph text is not overwritten, the div is not moved... tested it in FF and IE, also checked the DOM via Firebug: strange thing is that the new values are written to the nodes, but they are displayed in bold, and the old values are still there. WTF?
I guess I'm missing something fundamental here.
Non-zero lengths require units, "200" is missing its unit
JavaScript is case sensitive: backgroundColor and innerHTML
Since you appear to be using XHTML, your script is commented out
document.getElementById('moveme').top = 200;
needs to be
document.getElementById('moveme').style.top = "200px";
I think; and
document.getElementById('writeme').innerHtml = 'abc';
needs to become
document.getElementById('writeme').innerHTML = 'abc';
and it's backgroundColor with a capital C as #David spotted first.
Try this:
<script type="text/javascript">
function moveMe() {
document.getElementById('moveme').style.top = '200px';
document.getElementById('moveme').style.backgroundColor = 'green';
document.getElementById('writeme').innerHTML = 'abc';
alert('called!');
}
window.onload = moveMe;
</script>
Additionally to what the others said: Drop the <?xml version='1.0' encoding='UTF-8' ?>
, because that puts IE in Quirksmode.
Related
I have a standalone HTML page (no webserver) and I'm after some javascript code that will display the contents of a .csv file in the page.
The .csv file contains a list of usernames that I would like to be displayed. I'm doing it this way as the people that need to update the list know nothing of HTML and initially thought this would be an easier way to do it.
All the code snippets that I have found either try to upload a file and then only display the contents till you reload the page again or I don't have enough knowledge to tweak the code to work.
Any help appreciated & TYIA
Andy
#Barthy code that is very close to what I would like is this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
table {
border-collapse: collapse;
border: 2px black solid;
font: 12px sans-serif;
}
td {
border: 1px black solid;
padding: 5px;
}
</style>
</head>
<body>
<div id='container'></div>
<script type="text/javascript"charset="utf-8">
var data = 'heading1,heading2,heading3,heading4,heading5\nvalue1_1,value2_1,value3_1,value4_1,value5_1\nvalue1_2,value2_2,value3_2,value4_2,value5_2';
var lines = data.split("\n"),
output = [],
i;
for (i = 0; i < lines.length; i++)
output.push("<tr><td>"
+ lines[i].slice(0,-1).split(",").join("</td><td>")
+ "</td></tr>");
output = "<table>" + output.join("") + "</table>";
var div = document.getElementById('container');
div.innerHTML = output;
</script>
</body>
</html>
but would like to get data from CSV file
#cars10 example of what is in the csv file:
Heading_1,Heading_2,Heading_3,Heading_4
John, Smith, 29, Male
Andy, Jones, 32, Male
Abbey, Stewart, 35, Female
if that helps
Solution so far:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
table {
border-collapse: collapse;
border: 2px black solid;
font: 12px sans-serif;
}
td {
border: 1px black solid;
padding: 5px;
}
</style>
<script>
window.onload=function(){ with (new XMLHttpRequest()) {
onreadystatechange=cb; open('GET','data.csv',true); responseType='text';send();
}}
function cb(){if(this.readyState===4)document.getElementById('main')
.innerHTML=tbl(this.responseText); }
function tbl(csv){ // do whatever is necessary to create your table here ...
return csv.split('\n')
.map(function(tr,i){return '<tr><td>'
+tr.replace(/\t/g,'</td><td>')
+'</td></tr>';})
.join('\n'); }
</script>
</head>
<body>
<h2>Hey, this is my fabulous "dynamic" html page!</h2>
<table id="main"></table>
</body>
</html>
Here is a complete working example (works even on a local directory, i.e. no web server at all!). This is a plain JavaScript solution. Personally, I would always use jquery, but in this simple case you can do without it.
The page expects the csv-file ("csv.txt") in the same directory. But it is up to you to specify another (relative) path in the oReq.open() line.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script>
window.onload=function(){ with (new XMLHttpRequest()) {
onreadystatechange=cb; open('GET','csv.txt',true); responseType='text';send();
}}
function cb(){if(this.readyState===4)document.getElementById('main')
.innerHTML=tbl(this.responseText); }
function tbl(csv){ // do whatever is necessary to create your table here ...
return csv.split('\n')
.map(function(tr,i){return '<tr><td>'
+tr.replace(/\t/g,'</td><td>')
+'</td></tr>';})
.join('\n'); }
</script>
</head>
<body>
<h2>Hey, this is my fabulous "dynamic" html page!</h2>
<table id="main"></table>
</body>
</html>
I got my inspiration from here: Javascript - read local text file .
I have tried hours to get the results, but failed, below, I will post all I have done, hope I can get some tips, BTW,Thanks.
from the error message, yeah It's cssRules is null, surely error!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="index.css">
<title>css style</title>
<style type="text/css">
#demo {
font-size: 10px; /*first css rule */
}
p {
border: 1px solid green; /*second one*/
}
</style>
</head>
<body>
<div id="demo" style="color: red;">
<p>how to access of document's css!</p>
</div>
</body>
external css
#demo {
font-weight: 900;
}
p {
padding: 20px;
}
Javascript
<script>
/*1,to get the inline style, this maybe the most easy one*/
var cssInline = document.getElementById('demo').style;
var cssInText = cssInline.cssText, cssColor = cssInline.color;
console.log(cssInText, cssColor);
/*2.a to get the style in head*/
var cssInHeada = document.getElementById('demo');
// using the computed css of inline
var cssHeadText = getComputedStyle(cssInHeada, null);
console.log(cssHeadText);
// 2.b to get the style directly
var cssInHeadb = document.getElementsByTagName('style')[0];
console.log(cssInHeadb.textContent);
// 2.c or like this
var cssInHeadc = document.styleSheets[1];
console.log(cssInHeadc.cssRules[0].cssText); //per rule
/*3, but I cant get the extenal style*/
var cssExtenal = document.styleSheets[0];
console.log(cssExtenal.cssRules[0].cssText);
</script>
Thank your guys!
I suspect your JavaScript is running before the stylesheet is loaded. Try this:
document.addEventListener('DOMContentLoaded', function () {
var cssExtenal = document.styleSheets[0];
console.log(cssExtenal.cssRules[0].cssText);
}, false);
Or if you happen to be using jQuery, this is more universal:
$('document').ready(function(){
var cssExtenal = document.styleSheets[0];
console.log(cssExtenal.cssRules[0].cssText);
});
Update: another possibility is that you're using Chrome and either loading the CSS cross-domain or using the file:// protocol. This appears to be a known issue and is not considered a bug.
As the title suggest, I'm trying to change my css background-color using javascript function. To simplify the problem, I write a new code here.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Potato</title>
<style>
#item {
background-color:blue;
color:red;
}
</style>
<script type="text/javascript">
function changeBG(id,color) {
var id = id;
var color = color;
document.getElementById(id).style.background-color = color;
}
</script>
</head>
<body>
<script type="text/javascript">changeBG(item,green)</script>
<div id="item">I am a potato</div>
</body>
</html>
The default background-color is red (as suggested by CSS), then I want to change it to green before I print it. But the code doesn't work. I don't know where the mistake is.
First item needs to be made first:
<div id="item">I am a potato</div>
<script>
//...stuff....
</script>
Then we need to use strings:
changeBG("item","green")
And finally in JavaScript we say backgroundColor other than background-color.
#media print {
#item {
background-color:green;
}
}
Include this in your css. This will solves your problem while printing.
All css properties in javascript are camelCased rather than spinal-cased
document.getElementById('youElement').style.backgroundColor = 'color';
Use jQuery
$("#item").css("background-color", "green");
Documentation
Or pure JavaScript
document.getElementById("item").style.backgroundColor = "green";
Documentation
I want to change the background color if width is bigger than 100.
This is my code but it doesn't work.
Thanks for any help!
<html>
<head>
<style type="text/css">
div#mydiv {
width: 200px;
height: 100px;
background-color: red;
}
</style>
<script language="JavaScript">
function () {
var mydiv = document.getElementById("mydiv");
var curr_width = parseInt(mydiv.style.width);
if (curr_width > 100) {
mydiv.style.BackgroundColor = "blue";
}
}
</script>
</head>
<body>
<div id="mydiv" style=""></div>
</body>
</html>
Change
parseInt(mydiv.style.width);
mydiv.style.BackgroundColor = "blue";
To
mydiv.offsetWidth
mydiv.style.backgroundColor = "blue";
use
var curr_width = mydiv.offsetWidth;
instead
var curr_width = parseInt(mydiv.style.width);
Change:
var curr_width = parseInt(mydiv.style.width);
mydiv.style.BackgroundColor = "blue";
to:
var curr_width = mydiv.offsetWidth;
mydiv.style.backgroundColor = "blue";
I have set up a fiddle here.
Also notice I took it out of the function because it looked like it wasn't being called anywhere. You should also move the script out of the head to the bottom of the body tag or use window.onload.
UPDATE
Another fiddle with everything together
I assume this is a duplicate question.
Anyway, your intialization of curr_width need not include parseInt.
parseInt is for converting a value to integer type and here you doesnt require it.
Your code can be re-written as
<html>
<head>
<style type="text/css">
div#mydiv {
width: 200px;
height: 100px;
background-color: red;
}
</style>
<script language="JavaScript">
function () {
var mydiv = document.getElementById("mydiv");
var curr_width = mydiv.offsetWidth;
if (curr_width > 100) {
mydiv.style.BackgroundColor = "blue";
}
}
</script>
</head>
<body>
<div id="mydiv" style=""></div>
</body>
</html>
Assuming your function to be called onload. Here's the code:
<html>
<head>
<style type="text/css">
#mydiv {
width: 200px;
height: 100px;
background-color: red;
}
</style>
<script language="JavaScript">
function load(){
var mydiv = parseInt(document.getElementById("mydiv").offsetWidth);
if (mydiv > 100) {
document.getElementById("mydiv").style.backgroundColor = "blue";
}
}
</script>
</head>
<body onload="load();">
<div id="mydiv" style=""></div>
</body>
</html>
Changes:
Use offsetWidth to get the width of the div.
Use backgroundColor instead of BackgroundColor.
To get a proper computed width, you need to use the (not enough used) method getBoundingClientRect() https://developer.mozilla.org/en-US/docs/Web/API/element.getBoundingClientRect
Latest browsers have .width property, otherwise you just need to take right - left to get it.
Some comments:
- language="JavaScript" is useless. Like type="text/javascript". It's the default behavior. Seriously.
- you need to execute your code after the div has been created. So using onload or just by calling the code after in the html (like in my example)
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#mydiv {
width: 200px;
height: 100px;
background-color: red;
}
</style>
</head>
<body>
<div id="mydiv"></div>
<script>
/* run the code after the creation of #mydiv */
var mydiv = document.getElementById("mydiv");
var clientRect = mydiv.getBoundingClientRect()
var curr_width = clientRect.width || (clientRect.right - clientRect.left);
if (curr_width > 100) {
mydiv.style.backgroundColor = "blue";
}
</script>
</body>
</html>
Here is a working example http://jsbin.com/xapet/1/edit
Warning: to do this properly it's recommended that you execute this code each time the browser is resized.
Maybe you can take a look to the "element queries" thing, that will be a nice workaround according to media queries limitations.
https://encrypted.google.com/search?hl=en&q=element%20queries%20css
The following code shows what I expect in Firefox and Chrome:
a small white square in a big green rectangle.
I don't see the small square in IE7.
How can I make it appear?
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript">
<!--
function start()
{
var g_Div = document.getElementById("bigdiv");
var littleDiv = document.createElement('div');
littleDiv.setAttribute('style',
'position:absolute;'+
'left:300px;'+
'top:300px;'+
'width:5px;'+
'height:5px;'+
'clip:rect(0pt,5px,5px,0pt);'+
'background-color: rgb(255, 255, 255);');
g_Div.appendChild(littleDiv);
}
//-->
</script>
</head>
<body>
<div
id="bigdiv"
style="border: 1px solid ; margin: auto; height: 600px; width: 800px; background-color: green;"
>
</div>
<script type="text/javascript">
<!--
start();
//-->
</script>
</body>
</html>
This should do what you want, and should work across the major browsers:
function start()
{
var g_Div = document.getElementById("bigdiv");
var littleDiv = document.createElement('div');
littleDiv.style.background = 'rgb(255, 255, 255)';
littleDiv.style.width = '5px';
littleDiv.style.height = '5px';
littleDiv.style.left = '300px';
littleDiv.style.top = '300px';
littleDiv.style.position = 'absolute';
g_Div.appendChild(littleDiv);
}
Use this approach to changing the style on the element:-
littleDiv.style.cssText = 'position:absolute;'+
'left:300px;'+
'top:300px;'+
'width:5px;'+
'height:5px;'+
'clip:rect(0pt,5px,5px,0pt);'+
'background-color: rgb(255, 255, 255)';
setAttribute is pretty useless in IE, especially for the style attribute.
You may have to use a class or element.style."propertyName"
quirksmode compatibility chart