I am trying to make another div right under the existing div in the HTML
<html>
<head>
<title>
Media Player
</title>
<script src="script.js"></script>
</head>
<script>
makeOscarPlayer(document.getElementById("my-video"))
</script>
<body>
<div class="my-player">
Hello!
</div>
</body>
</html>
function makeOscarPlayer(){
var div = document.createElement("div");
div.innerHTML = `
hello
`
}
can someone explain to me what I am doing wrong? I am a self-taught developer sorry if my code is not perfectly organized still learning
You are calling the makeOscarPlayer() function before you are creating it.
You need to wrap the makeOscarPlayer() function declaration in a script tag.
You are passing in document.getElementById("my-video") as a parameter to makeOscarPlayer(), but there is no HTML element with an id of 'my-video'. You are giving the function a parameter of null, while the function declaration has no parameters.
You need to tell the script where to put the new element. To do that, you grab an existing element and use parentNode and insertBefore
Here is a barebones version that I got working for your reference:
<html>
<head>
<title>
Media Player
</title>
</head>
<script>
</script>
<body>
<div id="my-player">
Hello!
</div>
</body>
</html>
<script type="text/javascript">
function makeOscarPlayer(){
var div = document.createElement("div");
div.innerHTML = `hello`;
// This grabs the element that you want to create a new element by
var existingDiv = document.getElementById("my-player");
// This tells the script where to put the new element
existingDiv.parentNode.insertBefore( div, existingDiv.nextSibling);
}
// Must be called in the same script block or after the script holding the function declaration is loaded
makeOscarPlayer();
</script>
For more information on how parentNode and insertBefore work, see this Stack Overflow question
You need to append that new element to a specific parent, in your case to my-video.
The function appendChild appends the new element to a parent element.
function makeOscarPlayer(parent) {
var div = document.createElement("div");
div.innerHTML = 'Hello from Ele';
parent.appendChild(div);
}
makeOscarPlayer(document.getElementById("my-video"))
#my-player {
border: 1px dashed green;
padding: 5px;
margin: 5px;
width: 300px;
background-color: #f1f1f1
}
#my-video div {
border: 1px dashed green;
padding: 5px;
margin: 5px;
width: 200px;
font-weight: 700;
}
<div id="my-player">
Hello!
<div id="my-video">
</div>
</div>
It's a good start, but you're calling the function incorrectly and your function isn't adding anything to the page.
we use appendChild to add a node to the page.
In your function you create and add text to a div, but you don't return the node you made(and also you didn't close your line of code with a semi-colon so I added that too) but this should work:
<html>
<head>
<title>
Media Player
</title>
</head>
<body>
<div class="my-player">
Hello!
</div>
<script>
function makeOscarPlayer() {
var div = document.createElement("div");
div.innerHTML = `hello`;
return div;
}
document.getElementById("my-video").appendChild(makeOscarPlayer())
</script>
</body>
</html>
function makeOscarPlayer() {
var div = document.createElement("div");
div.innerHTML = `hello`;
return div;
}
document.getElementById("my-video").appendChild(makeOscarPlayer())
<html>
<head>
<title>
Media Player
</title>
</head>
<body>
<!-- added my-video div -->
<div id="my-video"></div>
<div class="my-player">
Hello!
</div>
</body>
</html>
Related
I am making a very simple page that just counts how many seconds the user has had the tab open. In the console the seconds update, but on the page in the browser, it ain't.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Counter</title>
<script type="text/javascript">
window.seconds = document.getElementById('counts');
var count = setInterval('counter()', 1000);
function counter(){
console.log(seconds)
document.getElementById('counts').innerHTML = window.seconds + 1;
}
</script>
<style>
h2 {
text-align:center;
color:#032441;
font-family:monospace;
}
div {
text-align:center;
color:#032441;
font-size:70px;
font-family:monospace;
}
</style>
</head>
<body>
<script>
document.body.style.backgroundColor = "#EBE9BD"
</script>
<h2>
You have been on this page for
</h2>
<div id="counts">
0
</div>
<h2>
seconds.
</h2>
</body>
</html>
What is the problem?
The variable seconds is declared too soon before the element is even rendered, that's why I added the window.onload wrapper to your code.
You need to use innerHTML to change the content of a div element.
Not related, but you can also style the body tag via CSS rule.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Counter</title>
<script type="text/javascript">
window.onload = function () {
var seconds = document.getElementById('counts');
var count = setInterval(counter, 1000);
function counter(){
var newCount = Number(seconds.innerHTML) + 1
console.log(newCount);
seconds.innerHTML = newCount;
}
}
</script>
<style>
body {
backgroundColor: "#EBE9BD";
}
h2 {
text-align: center;
color: #032441;
font-family: monospace;
}
div {
text-align: center;
color: #032441;
font-size: 70px;
font-family: monospace;
}
</style>
</head>
<body>
<h2>
You have been on this page for
</h2>
<div id="counts">
0
</div>
<h2>
seconds.
</h2>
</body>
</html>
You could use the following:
<script type="text/javascript">
window.seconds = document.getElementById('counts');
setInterval('counter()', 1000);
function counter(){
console.log(seconds.innerHTML);
window.seconds.innerHTML++;
}
</script>
Bare in mind that 'counts' is not yet defined as soon as the script runs.
To access the "body" of an Element you have to access it via element.innerHTML which in your case would look like window.seconds.innerHTML = window.seconds.innerHTML + 1
EDIT: But that won't fix your problem.
Your script does not detect the <div id="counts"> element, since it has not been loaded yet, you can fix this by moving the script after the div
Since innerHTML returns a string, performing + will attach both strings and your seconds will look like 011111111 So you'll have to parse it to a string via parseInt(window.seconds.innerHTML)
So changing
window.seconds = window.seconds + 1
to
window.seconds.innerHTML = parseInt(window.seconds.innerHTML) + 1;
and moving the script tag at the very bottom, should to the trick
I have been learning Javascript and I'm a little confused as to why this doesn't work. I'd like it so if you click the div, it creates a red border around it:
JSFiddle link
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css">
<title>Generation X</title>
</head>
<body>
<script src="test.js"></script>
<div id="clickHere" onclick="run()">
<p>Hello</p>
</div>
</body>
</html>
Javascript:
function run() {
document.getElementById("clickHere").style.border = thick solid red;
alert("Changed");
}
make it ..updated fiddle (you need to wrap it in the head tag)
function run(thisObj) {
thisObj.style.border = "1px solid red"; //or "1px solid #ff000"
alert("Changed");
}
also, rather than getting the reference to element again, simply pass the reference during the time of invocation.
So, instead of putting an onClick on div, use a addEventListener should be better.
https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Event_attributes
https://jsfiddle.net/5jsbhbhu/5/
var run = function() {
document.getElementById("clickHere").style.borderColor = "red";
document.getElementById("clickHere").style.borderWidth = "1px";
document.getElementById("clickHere").style.borderStyle = "solid";
alert("Changed");
};
var node = document.getElementById('clickHere');
node.addEventListener('click', run);
In the html part I don't want to include the events related code, events related code should be in inside the script tag
<!doctype html>
<head>
<style>
div{
width:200px;
background-color:grey;
}
</style>
<body>
<p>use the below area for events</p>
<div> point here </div>
<a id="event_output"></a>
<script>
var output=document.getElementById("event_output").innerHTML;
var div=document.getElementsByTagName("div");
div[0].onmouseover=function(){output="mouse over"}
div[0].onmouseout=function(){output="mouse out"}
</script>
</body>
You are just updating the output variable which is a string. Instead store the object reference and set its innerHTML property.
<style>
div {
width: 200px;
background-color: grey;
}
</style>
<p>use the below area for events</p>
<div>point here</div>
<a id="event_output"></a>
<script>
var output = document.getElementById("event_output");
var div = document.getElementsByTagName("div");
div[0].onmouseover = function() {
output.innerHTML = "mouse over"
}
div[0].onmouseout = function() {
output.innerHTML = "mouse out"
}
</script>
IE (tested 7-10) is not applying the base (an absolute URL) to background images within a style tag, resulting in 404. This only happens when the code is injected using innerHTML (a requirement of the larger application this belongs to). It applies the base to all other elements as seen in the example.
Any suggestions?
Edit 2014/01/13 This is fixed if I remove the style tags from the HTML string and manually append them to the header. Would like to know if this is the only answer. Based upon this solution: How to create a <style> tag with Javascript
<!DOCTYPE html>
<html>
<head>
<title>base test</title>
<base href="http://absoluteurl.com/">
</head>
<body>
<div id="container"></div>
</body>
<script>
var html = "First Node<br>Second Node.<br><style>#bkgdiv {background-image: url(media/ex_amp.jpg); border: 1px solid #f00; width: 200px; height: 200px;}</style><div id=\"bkgdiv\">DIV w/ Background</div><br><img src=\"media/ex_amp.jpg\">";
document.getElementById('container').innerHTML = html;
</script>
</html>
Have you tried the jQuery appendTo method?
Inline style elements have to be removed from the HTML string, added to a style element object, and then appended to the head.
<!DOCTYPE html>
<html>
<head>
<title>base test</title>
<base href="http://absoluteurl.com/">
</head>
<body>
<div id="container"></div>
</body>
<script>
var html = "First Node<br>Second Node.<br><style>#bkgdiv {background-image: url(media/ex_amp.jpg); border: 1px solid #f00; width: 200px; height: 200px;}</style><div id=\"bkgdiv\">DIV w/ Background</div><br><img src=\"media/ex_amp.jpg\">";
var head = document.getElementsByName('head')[0];
content.html = content.html.replace(/<style(.|\n)*?>(.|\n)*?<\/style>/ig, function(match) {
var css = match.replace(/<\/?style(.|\n)*?>/ig, "");
style = document.createElement('style');
style.type = 'text/css';
if(style.styleSheet){
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
head.appendChild(style);
return "";
});
document.getElementById('container').innerHTML = html;
</script>
</html>
I'd like to display a div on a webpage when a user clicks on a button.
Does someone know how to do this ?
My code, so far, is :
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso 8859-1" />
</head>
<body>
<input id="text" type="text" size="60" value="Type your text here" />
<input type="button" value="When typing whatever text display the div balise on the page" onclick="check();" />
<script type="text/javascript">
function check() {
//Display my div balise named level0;
}
</script>
</body>
</html>
Thanks,
Bruno
EDIT: All my code (I've erased it because it was too long and not very clear)
You can use document.createElement("div") to actually make the div. Then you can populate the div using innerHTML for the text. After that, add it to the body using appendChild. All told, it can look like this:
function check() {
var div = document.createElement("div");
div.innerHTML = document.getElementById("text").value;
document.body.appendChild(div);
}
This will add a div every time the button is pressed. If you want to update the div each time instead, you can declare the div variable outside the function:
var div;
function check() {
if (!div) {
div = document.createElement("div");
document.body.appendChild(div);
}
div.innerHTML = document.getElementById("text").value;
}
If you have the div already in the page with an id of "level0", try:
function check() {
var div = document.getElementById("level0");
div.innerHTML = document.getElementById("text").value;
}
A quick search on google gave me this example:
Demo of hide/show div
The source-code for that example is:
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<html>
<head>
<title>Demo of Show hide div layer onclick of buttons</title>
<META NAME="DESCRIPTION" CONTENT="Displaying and hiding div layers through button clicks">
<META NAME="KEYWORDS" CONTENT="Show layer, hide layer, display div, hide div, button on click, button on click event, div property, div style set">
<style type="text/css">
div {
position: absolute;
left: 250px;
top: 200px;
background-color: #f1f1f1;
width: 280px;
padding: 10px;
color: black;
border: #0000cc 2px dashed;
display: none;
}
</style>
<script language="JavaScript">
function setVisibility(id, visibility) {
document.getElementById(id).style.display = visibility;
}
</script>
</head>
<body>
<input type=button name=type value='Show Layer' onclick="setVisibility('sub3', 'inline');";><input type=button name=type value='Hide Layer' onclick="setVisibility('sub3', 'none');";>
<div id="sub3">Message Box</div>
<br><br>
</body>
</html>
Paste this code somewhere in your body
<div id="myDiv" style="display:none">
Hello, I am a div
</div>
Add this snippet into your check() function to display the otherwise-hidden content.
document.getElementById("myDiv").style.display = "block";
You could also change the div content programmatically thus:
document.getElementById("myDiv").innerHTML = "Breakfast time";
... would change the text to 'Breakfast time'.
You might want to look into jquery, it'll make your life 100 times easier.
Jquery is a javascript library (script) that you include and it allows you to manipulate the DOM very easily.
Start by adding the latest Jquery to your head which will allow you to use something like $(document).ready( )
The function inside .ready( fn ) is a callback function; it get called when the document is ready.
$("#lnkClick") is a selector (http://api.jquery.com/category/selectors/)
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready( function() {
$("#lnkClick").click( function() {
$("#level0").attr("style", "display: block;width: 100px; height: 100px; border: solid 1px blue;");
});
});
</script>
</head>
<body>
<div id="level0" style="display:none;">
</div>
Click me
</body>
</html>
Of course this code can be made cleaner. You want to check: http://api.jquery.com/click/
There are plenty of examples.
Best of luck with Jquery!
you really should be using jquery , there's a little bit of a learning curve but once you get it, developing web apps is much easier.
<html>
<head>
<script src="http://code.jquery.com/jquery-1.5.2.min.js"></script>
<script>
$(document).ready(function() {
$("#show_div_button").click(function() {
$("#div_to_show").show();
return false;
});
});
</script>
</head>
<body>
Click Me to Show the Div
<div style="display:none" id="div_to_show">I will be shown when the link is clicked</div>
</body>
</html>