I have a function to grab a video title from a YouTube json callback, which works - however I'm having issues inserting the variable into an element.
Here is the feed I'm grabbing:
<script type="text/javascript" src="http://gdata.youtube.com/feeds/api/videos/2WNrx2jq184?v=2&alt=json-in-script&callback=youtubeFeedCallback"></script>
The javascript function I'm using:
function youtubeFeedCallback(data) {
var info = data.entry.title.$t;
document.write(info);
}
This works fine, but I'd like to insert it into a div with the ID "box".
Usually I would use the following (and add it to the function - and remove the document.write):
var box = document.getElementById('box');
box.innerHTML = info;
I just cannot get this to work though. What would be the correct way to achieve what I'm trying to do? Thanks
http://jsfiddle.net/b3VYT/
Either make sure that the script is below the element or wrap your code in a document.ready callback so that it is not run until after the DOM is loaded.
http://jsfiddle.net/b3VYT/1
You need to make sure that the element that you are using is declared prior to your script executing:
<div id='test'></div>
<script>
function youtubeFeedCallback(data) {
document.getElementById('test').innerHTML = data.entry.title.$t;
}
</script>
Example
Related
I'll start by apologising as this may seem like or actually be a duplicate, but I've tried every solution I've encountered and none seem to be working for me.
In my HTML I have an iframe referencing another HTML document. With JavaScript, at the press of a list of buttons I insert text into the body of that iframe. I also use JavaScript to maintain focus on the iframe body. The problem is that nothing appears to work for me to get the cursor to move to the end of the text each time I press those buttons, it always moves to the beginning.
One of the solutions I've tried was to add this code to the function that handles my button presses:
iFrameBody.focus();
var content = iFrameBody.innerHTML;
iFrameBody.innerHTML = content;
so the function looks like this:
function typeIn(buttonId) {
var iFrameBody = document.getElementById("iFrame").contentWindow.document.body;
iFrameBody.innerHTML += buttonId;
iFrameBody.focus();
var content = iFrameBody.innerHTML;
iFrameBody.innerHTML = content;
}
Something else I tried was, in the HTML file referenced by my iframe I did:
<body onfocus="this.innerHTML = this.innerHTML;"></body>
I tried several other more complicated solutions that frankly I didn't even quite understand to be honest, all to no avail. Any help would be much appreciated.
I figured it out. The issue was that I was using a body element, writing to it's innerHTML and trying to set focus on the body. By simply using a textarea inside my iFrame instead it became very simple and it only required the simplest code.
This to set focus when the page loads:
window.onload = function () {
var iFrameTextArea = document.getElementById("iFrame").contentWindow.document.getElementById("iFrameTextArea");
iFrameTextArea.focus();
}
And then this to set the button to write to the textarea while maintaining focus:
function typeIn(buttonId) {
var iFrameTextArea = document.getElementById("iFrame").contentWindow.document.getElementById("iFrameInput");
iFrameTextArea.focus();
iFrameTextArea.value += buttonId;
}
Super easy!!
Instead of again using textarea in iframe, u can also solve this by using the following code.
var iframeElement = document.getElementById("iFrame").contentWindow.document.body;
iframeElement.focus();
var len = iframeElement.length ;
iframeElement.setSelectionRange(len, len);
I was trying to check some of javascript code and I found one thing which I am not able to understand the exact reason. In my html file, I have a div with id called test which dont have any value. Now, I want to update the a text/ sentence inside this div through innerHTML. as it is just for testing purpose I am not using any function/ event. Just adding a to update the value.
<body>
<script type="text/javascript">
var test_content = "This is new text in my test div";
document.getElementById("test").innerHTML = test_content;
</script>
<div id="test"></div>
</body>
Now, when I load the page, it showing empty nothing inside the test div but if put the javascript code below the div as in below, then it is showing the value in the variable. (note: I am not using any function nor event, just want to update on page load).
<body>
<div id="test"></div>
<script type="text/javascript">
var test_content = "This is new text in my test div";
document.getElementById("test").innerHTML = test_content;
</script>
</body>
can any one explain me the reason for this? Thanks in advance.
Thanks!
Robin
That's because the first is executed before the div#test is created, so it currently doesn't exist. That's why is a good practice to either put your script tags at the bottom of the page or wrap them with an window.onload event listener.
<body>
<script type="text/javascript">
window.onload = function () {
var test_content = "This is new text in my test div";
document.getElementById("test").innerHTML = test_content;
}
</script>
<div id="test"></div>
</body>
If you are using jQuery, you can also do this:
$(function () {
var test_content = "This is new text in my test div";
document.getElementById("test").innerHTML = test_content;
});
And since you seem to be a beginner in JavaScript coding, I recommend you read some articles on MDN, like this one and this one.
Pretty standard issue. Needs an 'onload' of some sort!
<body>
<div id="test"></div>
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function() {
var test_content = "This is new text in my test div";
document.getElementById("test").innerHTML = test_content;
});
</script>
</body>
The reason this is not happening in the the first instance, is because the DOM element, 'test' has not been created yet.
When you place the script after the div, the element has already been created and hence, the script can execute.
You will need to execute your code once the DOM is ready, by listening for load event dispatched from the body tag. This can be done quite simply using an in-line listener such as <body onload='myFunction'> or by an onload handler in javascript:
body.onload = function() {...}
Javascript is executed at runtime, as soon at it is being called. In your first example, the parser reads the script tag, executes it and then loads the rest of the page (top-to-bottom). As the script is executed before the div is laoded and created, the div will stay empty. That's the reason the onload event was introduced. http://www.w3schools.com/jsref/event_onload.asp
take one example of jquery you either have to write $(document).ready() or you have to write your jquery code at the last of html code and, both have same meaning i.e when all the html is loaded then do some function. this is same in this case, do some function after all the document content is loaded. take two cases:
case #1:
in this case we have the javascript code written above the html as in your first case which is without any event handler, the html engine will start reading the html code from top to bottom and at the moment it will hit to script tag it will call javascript engine. so according to this javascript code will be executed first.
if you write this line document.getElementById("test").innerHTML = test_content;
as :
var x = document.getElementById("test");
x.innerHTML = test_content;
then the console will return null i.e the value of x would benull.because div is still not loaded, therefore the value of div will not change
case #2:
script tag is placed at the last. so now, all the html is loaded by html engines, so now the value of x will be <div id="test"></div> and now all the javascript code will be executed without any error.
as i mentioned earlier about jquery $(document).ready()... well this is a jquery method but this can be written as in javascript as:
<script type="text/javascrip">
var start_script = function(){
// function to be performend
}
</script>
<body onload="start_script();">
......
</body>
because all the event are triggered when all the html is loaded and compiled.
i am working on a mobile website with html,js and css.i have created tag through HTML5 DOM & assigned functions to it. It's not working.
My html code(which i have tried thro' DOM method);
<script>
var addExhibits = document.getElementById('mycontent');
function mytest()
{
var div = document.createElement('div');
div.id = 'rateMe';
var anchor = document.createElement('a');
anchor.id="_1";
anchor.onclick = rateIt(this);
anchor.onmouseover=rating(this);
anchor.onmouseout=off(this);
div.appendChild(anchor);
addExhibits.appendChild(div);
}
</script>
<body><div id='mycontent' title="Rate Me..."></body>
Code(statically created tag - works fine)
<div id="rateMe" title="Rate Me...">
<a onclick="rateIt(this)" id="_1" onmouseover="rating(this)" onmouseout="off(this)"></a>
</div>
rate(this) is a function in external JS(http://reignwaterdesigns.com/ad/tidbits/rateme/)
Your event handler just assign the result of the respective function calls here:
anchor.onclick = rateIt(this);
anchor.onmouseover=rating(this);
anchor.onmouseout=off(this);
I assume you want them to execute in case of the event instead:
var that = this;
anchor.onclick = function(){ rateIt(that); };
anchor.onmouseover = function(){ rating(that); };
anchor.onmouseout= function(){ off(that); };
You don't call your mytest() function anywhere. That's the first thing I see. The other thing is that you are putting your script above your div (mycontent) so the div has not yet been created when your script is read. But I don't completely understand what your aim is here or what exactly your problem is.
You don't need to pass this.
you can access your element inside the function in many ways.
var addExhibits=document.getElementById('mycontent'),
rateIt=function(e){
e=e||window.event;
var target=e.target||e.srcElement;//polyfill for older browser
console.log(this,target);
},
rating=function(e){
console.log(this,e.target);
},
off=function(e){
console.log(this,e.target);
},
mytest=function(){
var div=document.createElement('div'),
a=document.createElement('a');
div.id='rateMe';
a.id="_1"; // id's shouldn't contain _ - & numbers(1st letter) even if it works.
a.onclick=rateIt;
a.onmouseover=rating;
a.onmouseout=off;
div.appendChild(a);
addExhibits.appendChild(div);
};
this way you also don't create memory leaks.
ps.: that external js example you using is written very bad.
to make your example work you need to change the strange me/num/sel variables in the external js with the proper one (this/e.target/e.srcElement).
I'm not sure the title of question is all right, as well as how much my question is valid.
Here is scenario:
// HTML
<script src="/script.js" data-app="app.js" />
// script.js
$(function () {
var script = // ???
});
Inside the js code, I want to get reference to original tag, the one who initialized the loading on "/script.js", so I'm able to check the data-app attribute.
Is that possible?
$('script').last().data('app');
Note that this may not be in a DOM ready block. The only place where you can access the current script tag is when it executes for the first time. An async callback such as the DOM ready event would not qualify for this. You can simply store the value in a variable though and then use it from inside your event:
(function() {
var app = $('script').last().data('app');
$(document).ready(function() {
// do stuff
});
})();
You can enumerate the scripts in document.scripts and recognize yours with its src property.
I don't think that there is a "proper" way to get your tag. However, in theory, when your script runs the corresponding tag should be the last one inserted into the document. So putting code like this into script.js works:
var child = document;
while (child && child.localName != "script")
child = child.lastChild;
if (child)
alert("My script tag: " + child);
You will need to run this code when the script loads and remember the script tag if you need it after the initial load.
document.scripts[document.scripts.length-1].src
i don't know what browser support it (IE and chrome, yes)
First, the background:
I'm working in Tapestry 4, so the HTML for any given page is stitched together from various bits and pieces of HTML scattered throughout the application. For the component I'm working on I don't have the <body> tag so I can't give it an onload attribute.
The component has an input element that needs focus when the page loads. Does anyone know a way to set the focus to a file input (or any other text-type input) on page load without access to the body tag?
I've tried inserting script into the body like
document.body.setAttribute('onload', 'setFocus()')
(where setFocus is a function setting the focus to the file input element), but that didn't work. I can't say I was surprised by that though.
EDIT:
As has been stated, I do indeed need to do this with a page component. I ended up adding file-type inputs to the script we use for giving focus to the first editable and visible input on a page. In researching this problem I haven't found any security issues with doing this.
<script>
window.onload = function() {
document.getElementById('search_query').select();
//document.getElementById('search_query').value = '';
// where 'search_query' will be the id of the input element
};
</script>
must be useful i think !!!
This has worked well for me:
<script>
function getLastFormElem(){
var fID = document.forms.length -1;
var f = document.forms[fID];
var eID = f.elements.length -1;
return f.elements[eID];
}
</script>
<input name="whatever" id="maybesetmaybenot" type="text"/>
<!-- any other code except more form tags -->
<script>getLastFormElem().focus();</script>
you can give the window an onload handler
window.onload = setFocus;
I think you have a fundamental problem with your encapsulation. Although in most cases you could attach an event handler to the onload event - see http://ejohn.org/projects/flexible-javascript-events/ by John Resig for how to do this, setFocus needs to be managed by a page component since you can't have two components on your page requiring that they get the focus when the page loads.
Try play with tabstop attribute
First of all, the input file is no the same as the other inputs, you need to keep this in mind.... thats for security reasons. When the input file get focus it should be read only or the browser should popup a dialog to choose some file.
Now, for the other inputs you could try some onload event on some of your elements...(not only the body have the onload event) or you could use inline javascript in the middle of the html. If you put javascript code without telling that is a function it gets executes while the browser reads it. Something like:
<script type="text/javascript">
function yourFunction()
{
...;
};
alert('hello world!");
yourFunction();
</script>
The function will be executed after the alert just when the browser reads it.
If you can, you should use jQuery to do your javascript. It will make your live soooo much easy.... :)
With jQuery could be done like this:
$(function() {
$("input:file").eq(0).focus()
})
With plain javascript could be done like this:
var oldWindowOnload = window.onload; // be nice with other uses of onload
window.onload = function() {
var form = document.forms[0];
for(i=0; i < form.length; i++) {
if (form[i].type == "file") {
form[i].focus();
}
}
oldWindowOnload();
}
For more elaborate solution with plain javascript see Set Focus to First Input on Web Page on CodeProject.
Scunliffe's solution has a usability advantage.
When page scripts are loading slowly, calling focus() from "onLoad" event makes a very nasty page "jump" if user scrolls away the page. So this is a more user friendly approach:
<input id="..."></input>
... really small piece of HTML ...
<script>getTheDesiredInput().focus();</script>