This question already has answers here:
Setting innerHTML: Why won't it update the DOM?
(7 answers)
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 10 years ago.
I was working on a simple javascript code and I don't know what it is not working.
Please tell me if you figure this out.
<!DOCTYPE html>
<html>
<head>
<script>
function displayText(){
var xa = document.getElementById('abcd').innerHTML;
xa+= 'asdf';
}
displayText();
</script>
</head>
<body>
<div id="abcd"></div>
</body>
</html>
innerHTML returns a String of the current contents of the element and not a pointer to it. So use this instead:
function displayText(){
document.getElementById('abcd').innerHTML += 'asdf';
}
or
function displayText(){
var el = document.getElementById('abcd');
var xa = el.innerHTML;
xa += 'asdf';
el.innerHTML = xa;
}
Furthermore you can not call the function, before the element you are referring to is actually created. So move the call at the bottom of the body tag.
<!-- .... -->
<script>
display();
</script>
</body>
At the time the code runs the body (including your div) has not yet been parsed. getElementById('abcd') doesn't find anything at that time.
Either move your script element to the end of the body so that it runs after the body has been parsed, or call your displayText() function from an onload handler.
(And if you intend the new value in xa to be displayed in the same field you'll need to write it back to the element with document.getElementById('abcd').innerHTML = xa.)
Related
This question already has an answer here:
jsFiddle: no connection between html and js? Can't call simple function from button? [duplicate]
(1 answer)
Closed 6 years ago.
I keep getting this error when i inspected the element of my button. The button is suppose to give a print view to page.
HTML Code:
<button class = "hidden-print" onclick = "printProducts()">Print Products</button>
Javascript Code:
function printProducts(){
window.print();
}
Attached here is my code live in jsFiddle:
https://jsfiddle.net/PochMendoza/scj0q0dk/
"In JSFiddle, when you set the wrapping to "onLoad" or "onDomready", the functions you define are only defined inside that block, and cannot be accessed by outside event handlers."
Easiest fix is to change:
function something(...)
To:
window.something = function(...)
---Niet The Dark Absol
For your example, you want to define the onclick method of a button. That's really easy with JavaScript, we just need to give the button an id in the HTML, so that we can find it in our JavaScript code.
Change this:
<button class = "hidden-print" onclick = "printProducts()">Print Products</button>
To this:
<button id="myButton" class="hidden-print">Print Products</button>
Note that we no longer need the onclick="printProducts()" part anymore.
Now we need to set the printProducts function to run when the button is clicked. This can be done like so:
document.getElementById('myButton').onclick = printProducts;
Start edit
This code needs to be placed in the onload function though, to properly run.
Do that like so:
window.onload = function() {
document.getElementById('myButton').onclick = printProducts;
}
End edit
And the printProducts function remains the same.
Working JSFiddle
document.getElementById('myButton').onclick = printProducts;
function printProducts(){
window.print();
}
<button id="myButton" class="hidden-print">Print Products</button>
This question already has answers here:
setTimeout or setInterval?
(20 answers)
'setInterval' vs 'setTimeout' [duplicate]
(5 answers)
Closed 8 years ago.
i am trying to move a small div along a big div in the y-direction according to how much i scrolled down the page.but i've found that using setTimeout() and setInterval() gives two completely different results.actually setInterval() hanged by browser several times .what is the basic difference between the two function??
<!DOCTYPE html>
<head>
<title>creat a dynamic div</title>
<style>
#mydiv{
border:2px solid green;
}
</style>
</head>
<body>
<script>
var i=0;
var elem1=document.createElement("div");
var atts1=document.createAttribute("style");
atts1.value="width:200px;height:3200px;border:1px solid black;background-color:orange;";
elem1.setAttributeNode(atts1);
document.body.appendChild(elem1);
var elem2=document.createElement("div");
var atts2=document.createAttribute("style");
var atts22=document.createAttribute("id");
atts22.value="mydiv";
atts2.value="width:200px;height:300px;background-color:red;position:absolute;top:0px;left:300px;";
elem2.setAttributeNode(atts2);
elem2.setAttributeNode(atts22);
document.body.appendChild(elem2);
function moveIt(){
var a=window.pageYOffset;
if(i > (a+30)){
clearTimeout(p);
}else{
elem2.style.top=i+"px";
i=i+1;
}
var p=setTimeout(moveIt,200);
}
window.onscroll=moveIt;
</script>
</body>
<html>
setTimeout executes the function once on a time out. setInterval executes the function repeatedly on and interval
https://developer.mozilla.org/en-US/docs/Web/API/Window.setTimeout
https://developer.mozilla.org/en-US/docs/Web/API/Window.setInterval
setTimeout will only execute the function once whereas setInterval will execute the function every n seconds (whatever you specify).
Say I have a string named html that has this in it:
<script>
document.write("Some random stuff here");
</script>
<script src="someremotejsfile"></script>
I want to display this within an iframe window dynamically.
My original solution was to do:
document.open();
document.write(html);
document.close();
But this causes problems in firefox where the spinner keeps spinning as if its loading forever even though the content has already loaded. My next attempt was to:
document.body.innerHTML = html;
This adds the scripts to the body, but that doesn't actually execute them. So lastly I tried:
div = document.createElement("div");
div.innerHTML = html;
document.body.appendChild(div);
But this also doesn't seem to execute the scripts inside the html string.
So my question is, given a string of html, how do I dynamically add it to the page? For instance, it can be an ad tag that has any number of scripts and other html elements in it. I have no control over what that html string has in it. It's a black box to me. I just have to be able to take that long string of html and load it into the window (an iframe in this case).
document.write works:
<iframe id="ifr"></iframe>
<script type="text/javascript">
var scr = decodeURIComponent("%3Ch1%3EHello%20World%3C%2Fh1%3E%3Cscript%3Ealert(%27Some%20random%20stuff%20here%27)%3B%3C%2Fscript%3E");
document.getElementById("ifr").contentWindow.document.write(scr);
document.getElementById("ifr").contentWindow.document.close();
</script>
(Never mind encoded URI string, just needed it to be able to assign code <h1>Hello World</h1><script>alert('Some random stuff here');</script> to a string variable inside of script tags
If you're using jQuery you can use .html to load, and it will fire your script
$(document.body).html( $(document.body).html() + htmlToAdd );
If you're not using jQuery, you can eval manually your script..
function appendHTMLtoBody(html){
var body = document.body;
var scriptsLoaded = [].slice.apply(body.getElementsByTagName("script"),[0]);
for(var i = 0; i < scriptsLoaded.length; i++){
scriptsLoaded[i].setAttribute("data-loaded","true");
}
body.innerHTML += html;
var allScripts = body.getElementsByTagName("script");
for(var i = 0; i < allScripts.length; i++){
if( allScripts[i].getAttribute("data-loaded") !== "true" ){
var script = allScripts[i].innerHTML;
eval(script);
}
}
}
i think will solve your problem.
I currently have a JavaScript file that will change the testimonial shown every five seconds. Everything works perfectly, except for the first five seconds, nothing appears. If I put a value where the JavaScript function is being called, it does show up initially, then is replaced by whatever the first testimonial is.
Here is the HTML code where the JavaScript is being called.
<html>
<head>
<SCRIPT language="JavaScript" SRC="textCycle.js"></SCRIPT>
</head>
<body>
<table border = 0><tr><td style="width:300px;"> <!-- Change the height in order to determine width of quotes -->
<div id="change"></div></td></tr></table>
</body>
</html>
Here is the Javascript:
var quotes=new Array(5);
var i = 0;
var authors=new Array(5);
//Load Quotes into array
quotes[0]="\"Website is awesome!\"";
quotes[1]="\"Love it!\"";
quotes[2]="\"Awesome site!\"";
quotes[3]="\"This site was very informative and helped with my problem.\"";
quotes[4]="\"Best site for helping with this issue.\"";
//Load authors that correspond with the quote array
authors[0]="Anonymous";
authors[1]="Anonymous";
authors[2]="Anonymous";
authors[3]="Anonymous";
authors[4]="Anonymous";
//Call the changeText() function every 5000 miliseconds
setInterval(changeText, 5000);
//Function that determine what quote and author to put in html.
function changeText(){
document.getElementById("change").innerHTML=(quotes[i] + '<p style="text-align: right"><i>' + authors[i] + '</i></p>');
if(i == 4)
i = 0;
else
i++;
}
Is this just a matter of changing the javascript file so that quotes[0] is outside of the loop?
Note: The values in the arrays were changed to keep it anonymous. These aren't real testimonials.
Just add changeText() (call your function) anywhere in your code before setInterval(). Well, it is not mandatory.
Fiddle
If you add the call to changeText() as mentioned, it likely still will not work. This is because the DOM has not been parsed yet. You should call it after the DOM is ready. One way to do this would be to put it in the onload event. This is the easiest way without a third-party library, but also waits until all images have been loaded. Here is an example:
<body onload="changeText()">
setInterval waits the interval duration (5 seconds) before executing the first time.
You could just call it once before setting the interval, and you'll be good to go. Eg:
//Call the changeText() function every 5000 miliseconds
changeText();
setInterval(changeText, 5000);
for example ,I have the following html
<HTML>
<HEAD>
<script type="text/javascript">
function trackElement(event){
event=event||window.event;
var target = event.explicitOriginalTarget||event.srcElement||document.activeElement;
var targetText = target.nodeValue||target.innerHTML;
alert(targetText);
}
</script>
</HEAD>
<BODY onclick="trackElement(event)">
<div>bbbbbb<div>cccccc</div>dddddddddd<div>eeeeeeeee</div></div>
</BODY>
</HTML>
When I clicked "bbbbbb",
On firefox ,I got "bbbbbb" alerted
which is exactly what I expected.
But on IE, I got
"bbbbbb<div>cccccc</div>dddddddddd<div>eeeeeeeee</div>"
When I clicked "dddddddddd",
On firefox ,I got "dddddddddd"
alerted which is exactly what I
expected.
But on IE, I got
"bbbbbb<div>cccccc</div>dddddddddd<div>eeeeeeeee</div>"
How can I get the same result with firefox on IE?
That's because the property "nodeValue" returns null for element nodes so you return innerHtml instead, which is gonna contain the whole html code inside an element. In Internet Explorer, your target is assigned by event.srcElement and hence is an element node, while it's a text node in FF. One way to solve the problem would be the following code :
function trackElement(event){
event=event||window.event;
var targetText;
var target = event.explicitOriginalTarget||event.srcElement||document.activeElement;
if(target.nodeType==3){
targetText = target.nodeValue
}else{
targetText = target.firstChild.nodeValue;
}
alert(targetText);
}
This way, you'd return the value if your assignment assigned a text node, and the text of the first child (which is what you're after) for an element node.
EDIT: Turns out I'm wrong. The problem is that event.srcElement returns the whole Element that's being clicked (event.explicitOriginalTarget being mozilla specific). From there, you need to retrieve the text. I see no easy way to do that if there are several texts in the element. If there is only one, it's a matter of iterating over the child nodes and displaying the text ones.
Please see comment about explicitoriginaltarget in crossbrowser-equivalent-of-explicitoriginaltarget-event-parameter.
In IE you get the Div element and the second one is in it, does this solution of separating the divs work for you? - the script is the same...
(This works both in IE and in FF)
<BODY onclick="trackElement(event)">
<div>bbbbbb</div>
<div>cccccc</div>
</BODY>
What about just substringing it?
<script type="text/javascript">
function trackElement(event){
event=event||window.event;
var target = event.explicitOriginalTarget||event.srcElement||document.activeElement;
var targetText = target.nodeValue||target.innerHTML.substr(0, target.innerHTML.indexOf("<"));
alert(targetText);
}
</script>
</HEAD>
<BODY onclick="trackElement(event)">
<div>bbbbbb<div>cccccc<p>Hellooo</p></div></div>
This seems to work, clicking ccccc returns "cccccc", and so on. Or did I completely miss the point?
EDIT: You also need to check if the element has any child elements before substringing it...
finally,I use offset to check which text node is clicked as below:
if ($.browser.mozilla) {
el = event.originalEvent.explicitOriginalTarget;
}else{
var parent =event.srcElement;
var left = event.pageX;
var top = event.pageY;
var offset=$(parent).offset();
for(var i=0;i<parent.childNodes.length;i++){
var n = parent.childNodes[i];
if ( n.nodeType == 1 ){
if($(n).offset().top>offset.top){
if($(n).offset().top>top){
el=parent.childNodes[i-1];
break;
}
}else if($(n).offset().top+$(n).height()>offset.top){
if($(n).offset().left>left){
el=parent.childNodes[i-1];
break;
}
}
}
el=n;
}
}