I'm trying to understand the behavior of innerHTML in the code below. I want to permanently add a new div block every time I hit the button, but it seems that the new block only pops up for a split second then disappears.
Does anyone know why this is the case, and how to fix it?
Also, when I change the code to use appendChild instead of innerHTML, I get an error saying Argument 1 of Node.appendChild is not an object.. I'm not sure what this means.
Any help is much appreciated!
Below is the code:
<DOCTYPE html>
<html>
<body>
<form onSubmit="loadData()">
<input type="submit" id="button">
</form>
<div id="block">List of items:</div>
<script>
function loadData(){
document.getElementById("block").innerHTML += "<div>item</div>";
// document.getElementById("block").appendChild("<div>item</div>");
};
</script>
</body>
</html>
Because you are submitting then the page reloads and your HTML is obliterated.
If you need items to persist then you will need to use cookies, localStorage or a server-side solution.
function addItem()
{
document.getElementById("block").innerHTML += "<div>item</div>";
}
<DOCTYPE html>
<html>
<body>
<form>
<input type="button" id="button" onclick="addItem()" />
</form>
<div id="block">List of items:</div>
</body>
</html>
you are submitting the page. appendChild or innerHtml happen directly after submit, before the new page is loaded. once the new page is loaded, the current page (with the applied modifications) is dismissed and replaced with the new page.
if you wanted something to happen on the new page, you would need to execute the code on that page. (or don't use a form submit, but rather some ajax for sending the form).
The reason why appendChild is not working for you, is that appendChild expects a dom node as parameter, not a string. it would be like document.getElementById("foo).appendChild(document.createElement("div")). (the tricky part is that with createElement you get an empty element, you would also need to put the content you want into it.
Your first question is already answered by #lee.
Your problem with your second answer is, that you can not use appendChild like you did. If u want to use append child, according to the mozilla developer docs you will have to to something like this:
var mydiv = document.createElement("div");
mydiv.appendChild(document.createTextNode("item"));
document.getElementById("block").appendChild(mydiv);
to get the result you asked for.
Related
I am really new to HTML and am stuck conceptualising some code as follows.
My question is - which part of the code is actually doing the displaying of 'showHello'.
<html>
<head>
<script>
function displayCD()
{
document.getElementById("showHello").innerHTML="hello";
}
</script>
</head>
<body onload="displayCD()">
<div id='showHello'></div>
</body>
</html>
Doesn't document.getElementById("showHello").innerHTML="hello";
just set id showHello to the value hello and
<div id='showHello'></div> just create the id showHello?
If <div id...> actually displays the value of showHello, how does it, if displayCD() is called before it or is the whole document deciphered before anything is actually displayed ?
Does that make sense as a question?!!!!
Doesn't document.getElementById("showHello").innerHTML="hello"; just set id showHello to the value hello
It searches the DOM for the element with that id, and changes the HTML inside it to hello.
and just create the id showHello?
It creates an element with that id
how does it, if displayCD() is called before it or is the whole document deciphered before anything is actually displayed ?
See this:
<body onload="displayCD()">
The function is called in response to the load event firing. That won't happen until the entire document, including any dependent resources (such as images) has loaded.
The line who is in charge for displaying the "hello" is this one
function displayCD()
{
document.getElementById("showHello").innerHTML="hello"; // THIS one
}
And the displayCD() function is loaded with HTML here
<body onload="displayCD()">
PS : If you're new with HTML, you probably new with Javascript. Maybe you should look after jQuery. Here is how we doing the same thing with jQuery.
$(document).ready(function() {
$("#showHello").html("hello");
});
Preview : http://codepen.io/anon/pen/ypBvf
A simplified version of what a browser would do is like this:
create the document object
add the head element and interpret the script. This will make him remember that there exists a function called displayCD.
add the body element.
add the div HTMLElement to it and set the id property to showHello
Note: the div is declared here in Hypertext markup language <div id='showHello'></div>
when the document has done loading all the elements into it, the function you set on onLoad is called. In your case, onload="displayCD()" is the part that does that and the function called is displayCD.
displayCD will get the HTMLElement that has the id == showHello and set its innerHTML property to the hello string. Since this is called when the document has fully loaded, it means that the div with id == showHello already exists, so it will add the text hello into it.
Please provide an example of how to use the object tag in an HTML form.
I was reading the HTML5 spec today to learn what kind of form elements exist nowadays, and noticed the following:
Submittable elements
Denotes elements that can be used for constructing the form data set when a form element is submitted: button, input, keygen, object,
select, textarea
http://www.w3.org/html/wg/drafts/html/master/forms.html#category-submit
So apparently a form can have an object tag in it, affecting the data that is sent on form submission. The only context in which I was familiar with the object tag is to embed Flash movies onto a page. What would be an example situation where you could use the object tag in a form and have it affect the form submission data?
Update:
In the spec on how form payload is constructed on submit, found this interesting snippet in http://www.w3.org/html/wg/drafts/html/master/forms.html#constructing-form-data-set
If the field element is an object element: try to obtain a form
submission value from the plugin, and if that is successful, append an
entry to the form data set with name as the name, the returned form
submission value as the value, and the string "object" as the type.
But I wonder what kind of plugins hand out such submission values.
Update:
QtBrowserPlugin seems to support using them in forms. Now all I need for an example is a minimalistic such plugin.
http://doc.qt.digia.com/solutions/4/qtbrowserplugin/developingplugins.html#using-plugins-in-forms
At first I suggest to use the latest HTML5 documentation at http://www.w3.org/html/wg/drafts/html/CR/forms.html#constructing-form-data-set and not the HTML5.1 one.
I fear there's no browser that currently implement this behavior. In any case, if you want to mimic what the specification says to do, you can use a script like this:
<!DOCTYPE html>
<html>
<body>
<form method="post" action="index.html" id="myForm">
<input type="text" id="myFieldID" name="myFieldName" value="Hello World!" />
<object type="myPluginMIMETYPE" id="myPluginID" name="myPluginName" ></object>
<button type="submit">Submit</button>
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script>
$( document ).ready(function() {
$( myForm ).on( "submit", function( event ) {
//Ask the plugin for some data, i.e. a flash object
var pluginData = "pluginImportantData"; // ideally something like $(myPluginID).giveMeSomeDataBecauseUserWantsToSubmit();
//Append the data before submission, giving to the input tag the right attributes
$(this).append('<input type="object" name="myPluginName" value="'+ pluginData +'" style="visibility:hidden"/>');
return true;
});
});
</script>
</body>
</html>
On a second thought after trying it out it appears that putting a object tag inside of a form will not work, unless I may have missed a cretin tag that allows the object to be visible However you can use the div tag to separate objects. I have tried the following, the first section works fine, the section starting with "Form" does not show up in fire fox so it is possible that I missed something when writing it. EDIT= removed link (not helpful)
<!DOCTYPE html>
<html>
<body>
<object width="400" height="400" data="file name.***"></object>
<div>
<object width="500" height="500" data="file name.***"></object>
<form>
<object width="500" height="500" data="1r.txt">
<object width="500" height="500" data="2r.txt">
</object>
</object>
</form>
</body>
</html>
Is is possible to both define an anchor to scroll to a URL and set a variable in the frament? I tried with code the below, but this does not work in Chrome. Can I make it work using another delimiter than the ampersand?
<!doctype html>
<html>
<head>
<title>Scroll to anchor test</title>
</head>
<body>
<p>Scroll to bottom (works)</p>
<p><a href="#bottom&test=testing">Scroll to bottom and include
variable in the frament</a> (doesn't work)</p>
<p style="margin-top: 2000px">Bottom of page</p>
<p><a name="bottom">#bottom</a></p>
</body>
</html>
JSFiddle with the code above: http://jsfiddle.net/janaagaard/FHdQr/
As pointed out before #bottom&var=value will not work. The page will scroll to the element with id="bottom&var=value". The page scrolls down without reloading.
?var=value#bottom would reload the page with that variable and scroll to the element with id="bottom" on that new page. This is useful if you need to know the value of the 'var' variable on the server to perform some server-side action. E.g. In PHP you would see the value value in $_GET['var'].
If you need to change something with javascript and want to alter a variable because of that reason, you should use the onclick event (either by using it in-line or binding it to the element in an other way). Usually you wouldn't want to change a variable, but do whatever you need to do in a (nameless) function instead. This is useful if you want to do a client-side action.
Edit: I quickly want to add. To do a server-sided action, you don't necessarely need to reload the page. Lookup ajax-requests if you need to do that. This is done with javascript.
No, it's not possible to both link to an anchor and use the fragment for storing variables.
I ended up scrolling the page using JavaScript, using this answer as a template: https://stackoverflow.com/a/4801719/37147.
I would preffer this if I were you:
javascript
function GetTop(ele){
if (ele.offsetParent)
return (ele.offsetTop + GetTop(ele.offsetParent));
else
return (ele.offsetTop);
}
function scrollToAnchor(id,offset){
var aTop;
if(id=='0')
aTop=0;
else
aTop = GetTop(document.getElementById(id));
//40px to leave room for #title
$('body, html').animate({scrollTop:aTop+offset},900);
//body for chrome/safari and html for ie/firefox/opera
}
Put this in your HTML next to an ID orso:
onclick="scrollToAnchor('div name to scroll to', -10)"
the -10 stands for the pixels he will be above or beneath the place you want to scroll to.
In my page I have a hidden <div>, such as the following:
<div id="myid" style="display:none;">
...
</div>
When the user clicks a button, I have a javascript code that calls $('#myid').show("slow");, thus displaying this <div>.
My question is when does the code inside the <div> gets called: when the page first loads or only when it's shown?
My concern is that inside this <div> I'd like to place a page counter (with an <iframe>), which should only be called when the <div> is shown. The alternative would be to put the code inside the javascript, but I'd rather keep it in the page.
The code inside the div get called as you load the page.
So the counter will get called everytime the page is loaded even if the div stays hidden.
So you have to use javascript somehow like this:
<div id="myid" style="display:none;">
...
</div>
<script>
function showCounter() {
document.getElementById("myid").innerHTML = '<script>counter-code</script>';
document.getElementById("myid").show('slow');
}
</script>
and add the function showCounter to your button.
It will be run when the page loads, display:none only affects visibility and has nothing to do with code operation layer (in fact, some browsers ignore CSS entirely and may show it anyway).
If you want a piece of code to only run when clicking a JavaScript button, you should attach that code to the Javascript function. Make an empty div on your page and then use the function to put code inside it:
<div id="jsDiv"></div>
<script>
function jsCode() {
document.getElementById('jsDiv').innerHTML = 'Whatever you want';
}
</script>
Then attach the jsCode() function to your button, and the HTML will only be rendered when the function is called. If you're using server-side scripting (PHP, Rails etc.) or something more complex, look into jQuery and AJAX functions.
Try like this:
$(document).ready( function() {
$('#myid').show("slow")
}
I am new to perl/html. This is from a perl file. This button is in there right now:
<button id = "button1" name = "submitButton" type="submit">
<span class="right">Submit</span>
</button>
I don't see any piece of code where submitButton or button1 is given any logic so I don't understand why this jumps to the next page. Can someone explain?
EDIT: This seems to be the only javascript in the whole file...
<script type="text/javascript">
% $m->comp('../js/share.js');
</script>
I looked at the file, and it doesn't seem to do any redirecting or anything.
Often event handlers are hooked up at run-time using JavaScript. If there is an included script, look in the code for "button1" and see which function is hooking it up.
Also since this is a SUBMIT button, if it is wrapped in a form, no code needs to hook this up. It will post to whatever is defined in the form's ACTION property.
Maybe there is some JS/Jquery or another js-framework included to the page?
Since this is a submit button, it does the logic defined by the Form that surrounds it.