hi2all i write code which change the color of webpage when the user click the div
but doesn't work here is my code what's wrong with it
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="content-type" content="text/html" />
<meta name="author" content="gencyolcu" />
<title>Untitled 1</title>
<script type="text/javascript">
var x=document.getElementById("m");
x.addEventListener("click",function{
document.body.style.backgroundColor = "red";
});
</script>
</head>
<body >
<div id="m">kfjgflg</div>
</body>
</html>
You should use something such as:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="content-type" content="text/html" />
<meta name="author" content="gencyolcu" />
<title>Untitled 1</title>
</head>
<body>
<div id="m">kfjgflg</div>
<script type="text/javascript">
var x=document.getElementById("m");
x.addEventListener("click",function(){
document.body.style.backgroundColor = "red";
});
</script>
</body>
</html>
Because you have two problems in your original code:
Is missing a important () after the token "function".
The Javascript only recognizes a element after the page or element has ready. In this case, the element only is read to be recognized if your code has after the Javascript Codes that recognizes it.
The code above fixes this.
A important observation: In some IE's, this code can not work, because of the use of x.addEventListener, in this case, you can transform the anonymous function in a normal function (with a name) and listen with addEventListener (if available) and onclick (recommended for old IE's).
In this way,the code looks like:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="content-type" content="text/html" />
<meta name="author" content="gencyolcu" />
<title>Untitled 1</title>
</head>
<body>
<div id="m">kfjgflg</div>
<script type="text/javascript">
function changeColor(){
document.body.style.backgroundColor = "red";
}
var x=document.getElementById("m");
if(!!x.addEventListener){ //If exists
x.addEventListener("click", changeColor);
}
x.onclick = changeColor; //It's a property, and ALWAYS can be set (but in some cases is not recognized)
</script>
</body>
</html>
Here is a working example with this code: http://jsfiddle.net/fjorgemota/qCXH3/
If you had opened your JavaScript error console it would have told you that you cannot access the property/method addEventListener of undefined.
You need to look for the element m after the DOM tree has been built. Either place into a function which gets called on DOMContentLoaded:
document.addEventListener('DOMContentLoaded', function() {
/* ... */
}, false);
or place your script at the end of your <body>.
Related
I have a html file (converted from docx) and it does not have any class names or ids. How can I style it using JS? For example, if I need to change the color of the heading for the below file HTML
<!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" />
<script src="./script.js"></script>
<title>Document</title>
</head>
<body>
<h1>This is the heading</h1>
<p>Hello, my name is xyz and this is a para</p>
</body>
</html>
This is what I tried, but document.getElementByTagName() does not return the element like document.getElementById()
console.log('hello world');
Heading = document.getElementsByTagName('h1');
console.log(Heading);
Heading.style.color = 'blue';
Edit:
I tried the below code, but it returns undefined
console.log('hello world');
Heading = document.getElementsByTagName('h1')[0];
console.log(Heading);
Heading.style.color = 'blue';
You can try document.querySelector() as well.
<!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>
<h1>This is the heading</h1>
<p>Hello, my name is xyz and this is a para</p>
</body>
<script type="text/javascript">
const header = document.querySelector('h1');
console.log(header);
header.style.color = 'blue';
</script>
</html>
One other thing to note is - we need to wait for the page to load, otherwise your javascript code runs first and returns undefined.
You can ensure javascript to run after page load using any of the below ways -
Add an event listener – document.addEventListener("load", FUNCTION);
Add onload to the body tag – <body onload="FUNCTION()">
Defer the script – <script src="SCRIPT.js" defer>
Lastly, place the script at the very bottom of the page – Although this is not quite “after page load”.
The issue in your code is that getElementsByTagName returns an array, but you're using is as if it were a single element.
Try this:
window.addEventListener('load', () => {
const heading = document.querySelector('h1');
heading.style.color = 'blue';
});
<h1>This is the heading</h1>
<p>Hello, my name is xyz and this is a para</p>
Please update your code like this. you imported the script before html.
There are two solutions. first you have to import script after html or use
window.addEventListener
window.addEventListener('load', () => {
const heading = document.querySelector('h1');
heading.style.color = 'blue';
});
<h1>This is the heading</h1>
<p>Hello, my name is xyz and this is a para</p>
I have the following code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<button onclick="this.innerHTML=Date()">The time is?</button>
</body>
</html>
This is working fine.
But if I try to do the same thing by creating a separate JavaScript function, the code is not working.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<button onclick=displayDate()>The time is?</button>
<script>
function displayDate(){
this.innerHTML=Date();
}
</script>
</body>
</html>
What is the reason for this?
Your this isn't refer to the button itself, when it is in the function scope. You can achieve to the desired result with many approaches.
1) You can pass this to the function as a parameter
function displayDate(context){
context.innerHTML = Date();
}
<button onclick="displayDate(this)">The time is?</button>
2) Using explicit bindings, like call or apply
function displayDate(){
this.innerHTML = Date();
}
<button onclick="displayDate.call(this)">The time is?</button>
You can try to do something like this
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<button id="test" onclick=displayDate()>The time is?</button>
<script>
function displayDate(){
document.getElementById("test").innerHTML=Date();
}
</script>
</body>
</html>
This is the simple html file for reading an xml
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>simple script javascript</title>
<script src="scripts/jquery-3.2.1.min.js"></script>
<script src="scripts/lector.js"> </script>
</head>
<body>
<h1>"web is running"</h1>
<input type="file" id="file-input" />
<h3>Contenido del archivo:</h3>
<pre id="contenido-archivo"></pre>
</body>
and the lector.js is as follows:
function leerArchivo(e) {
var archivo = e.target.files[0];
if (!archivo) {
return;
}
var lector = new FileReader();
lector.onload = function(e) {
var contenido = e.target.result;
mostrarContenido(contenido);
};
lector.readAsText(archivo);
}
function mostrarContenido(contenido) {
var elemento = document.getElementById('contenido-archivo');
elemento.innerHTML = contenido;
}
document.getElementById('file-input')
.addEventListener('change', leerArchivo, false);
document.getElementById('file-input').addEventListener('change', leerArchivo, false);
console.log(contenido);
returning this error:
Cannot read property 'addEventListener' of null
What´s wrong ?
This is returning null:
document.getElementById('file-input')
Because the code is executing before the element exists on the page. JavaScript is processed in the order it's found in the HTML document, even before the full document is finished loading.
You can move the JavaScript to the end of the page:
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>simple script javascript</title>
<script src="scripts/jquery-3.2.1.min.js"></script>
</head>
<body>
<h1>"web is running"</h1>
<input type="file" id="file-input" />
<h3>Contenido del archivo:</h3>
<pre id="contenido-archivo"></pre>
<script src="scripts/lector.js"></script>
</body>
(The jQuery library can still load at the beginning of the page if you want because it doesn't immediately try to interact with the page, it just initializes itself. But since your script tries to interact with the page, it needs to wait until the page loads.)
Alternatively, since you're loading jQuery anyway, you can use it to easily wait until the document is ready. Something like this:
$(function () {
document.getElementById('file-input').addEventListener('change', leerArchivo, false);
document.getElementById('file-input').addEventListener('change', leerArchivo, false);
console.log(contenido);
});
the following code should display the word Test...but instead the message TypeError: document.getElementById(...) is displayed.
I can't figure out why:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Testtree</title>
</head>
<script>
document.getElementById("kaptree").innerHTML="TEST";
</script>
<body>
<div id="kaptree"></div>
</body>
</html>
Can anyone help me to open my eyes?
You're trying to access the kaptree element before it's loaded. Run your script after loading the DOM.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Testtree</title>
</head>
<body>
<div id="kaptree"></div>
<script>
document.getElementById("kaptree").innerHTML = "TEST";
</script>
</body>
</html>
You should place your scripts after your html elements.
The element with the id "kaptree" is not available at this place. Move the script block below the body and it works.
Otherwise you have to wait for the document-ready state.
If you move the body section with the DIV setup to the top it works.
It runs sequentially so it can't assign the inner.html before the DIV is defined
Because your JS code is called before HTML.
Solution 1: Add JS right before </body> tag
Example:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Testtree</title>
</head>
<body>
<div id="kaptree"></div>
</body>
<script>
document.getElementById("kaptree").innerHTML+="TEST";
</script>
</html>
Solution 2: Execute JS code inside window.load function
Example:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Testtree</title>
<script>
window.onload = (function(){
document.getElementById("kaptree").innerHTML+="TEST";
});
</script>
</head>
<body>
<div id="kaptree"></div>
</body>
</html>
Your script is defined before the element that you try to reference.
Move it after :
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Testtree</title>
</head>
<body>
<div id="kaptree"></div>
</body>
<script>
document.getElementById("kaptree").innerHTML="TEST";
</script>
</html>
Or more readable and maintainable solution, use a function :
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Testtree</title>
<script>
function changeValue(){
document.getElementById('kaptree').innerHTML='TEST';
}
</script>
</head>
<body>
<div id="kaptree"></div>
<script>changeValue()</script>
</body>
</html>
A. Put the script inside head or body.
B. Either put the script after #kaptree, or add a document ready statement. You try to call something that isn't there yet.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Testtree</title>
<script>
document.addEventListener('DOMContentLoaded', function(){
document.getElementById("kaptree").innerHTML="TEST";
}, false);
</script>
</head>
<body>
<div id="kaptree"></div>
</body>
</html>
Sometimes the solution is so simple.
I will put the function call into a:
$( document ).ready(function() {
});
How can I pass argument to function redirect in JavaScript
Here is my code:
<script type="text/javascript">
<!--
function redirectlink(text){
window.location = "index.php?keyName="+ text;
}
//-->
</script>
<form>
<button type="button" id="butt_1" onclick="redirectlink(KEY_POWER)"> 1 </button>
Thank you in advance.
This can be done either by using getElementById and addEventListener
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<button id="foo">Click</button>
<script type="text/javascript">
document.getElementById("foo").addEventListener("click", function(){
window.location.replace("http://stackoverflow.com/q/36933820/5526354")
})
</script>
</body>
</html>
either onclick
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<button id="foo" onclick="action()">Click</button>
<script type="text/javascript">
function action(){
window.location.replace("http://stackoverflow.com/q/36933820/5526354")
}
</script>
</body>
</html>
Using onclick is deprecated.
With just only JavaScript (without jQuery / Angular etc.) you can use addEventListener on click event.
for example:
var btn = document.getElementById('butt_1');
btn.addEventListener('click', function(e) {
// your code
});
In this function you can for example get value/txt from this button element and something else which you want.