GET request iframe - javascript

<div id="result"></div>
<button id="send">Request</button>
JavaScript:
var button = document.getElementById("send"),
div = document.getElementById('result');
button.addEventListener('click', function() {
var result = createIframe("f", "/lorem.txt");
console.log(result.contentWindow);
div.innerHTML = result.contentWindow.document.body.innerHTML;
});
function createIframe(name, src, debug) {
var tmpElem = document.createElement('div');
tmpElem.innerHTML = '<iframe name="' + name + '" id="' + name + '" src="' + src + '">';
var iframe = tmpElem.firstChild;
iframe.style.display = 'none';
document.body.appendChild(iframe);
return iframe;
}
I have on the local server is a file lorem.txt. With hidden frame I am trying to query the contents of this file and paste it into <div id="result"></div>. But for some reason it does not is inserted. What could be the problem?

I believe elements with the ids of "send" and "result", respectively do not exist at the moment when your javascript code is running, therefore the click event will not be attached to the button. You need to make sure that these elements exist when you try to get them by their ids or attach events to them.
Solution: Either make sure your code is running after the document has been loaded or put your relevant script tag below the html you have described in your question.

Related

Why is my script pushed in a iframe is executed in the parent?

I try to push a script into a iframe.
At least the script is pushed 'somewhere' because it outputs something in the console.
If I open the iframe in the debugger I see it in the document INSIDE the iframe.
So everything looks fine until now.
But when it runs the message is inconsistent with the place of execution.
Its output look like it is runned inside the parent : it finds a #parent that exists only in the parent and it doesn't find the #child that has been pushed in the child.
Sorry I cannot make a working fiddle because of security concerns (communication between parent and iframe)
<html>
<body>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<div id='parent'>
<iframe id="frame"></iframe>
<script>
var $frm = $("#frame");
var $doc = $frm[0].contentWindow ? $frm[0].contentWindow.document : $frm[0].contentDocument;
var $body = $($doc.body);
$body.html('');
$body.append("<div id='child' >this isthe child</div>");
var $head = $($doc.head);
$head.append($("<script"+">console.log('location = '+window.location + ' ' + 'isParent:' + $('#parent').length + ' ischild:' + $('#child').length); <\/"+"script>"));
</script>
</body>
</html>
This outputs
location = file:///tmp/test.html isParent:1 ischild:0
I expected
location = about:/blank isParent:0 ischild:1
It's because jQuery handles evaluating the script content in append, rather than having the browser do it. It does that because when you insert a script via innerHTML or insertAdjacentHTML, the script isn't executed. jQuery ensures that the script is executed regardless of how it implements append.
If you append the script directly using the DOM, it's executed in the correct document (and fails because $ is undefined).
To do that, replace:
$head.append($("<script"+">console.log('location = '+window.location + ' ' + 'isParent:' + $('#parent').length + ' ischild:' + $('#child').length); <\/"+"script>"));
with
var script = document.createElement("script");
script.textContent = "console.log('location = '+window.location + ' ' + 'isParent:' + $('#parent').length + ' ischild:' + $('#child').length);";
$head[0].appendChild(script);
Of course, you'll probably want to add jQuery to the iframe's document so $ is defined. :-) You can use the load event on script to do that:
var script = document.createElement("script");
script.onload = function() {
script = document.createElement("script");
script.textContent = "console.log('location = '+window.location + ' ' + 'isParent:' + $('#parent').length + ' ischild:' + $('#child').length);";
$head[0].appendChild(script);
};
script.src = "https://code.jquery.com/jquery-1.12.4.min.js";
$head[0].appendChild(script);
With those changes, you get the result you're expecting:
location = about:blank isParent:0 ischild:1

onerror Event didn`t work

I try create code which replace src image on another. I want to use function invalidUrl():
function invalidUrl() {
paint.src = randomvariable;
}
but this function isn`t running :<
var paint = '<img src="' + url + '"class="heightImg" onerror="invalidUrl()"/>' + '</br></br>' + description;
How to change src images if current picture doesn`t exist?
paint.src // undefined
this is because paint is of "string" type and strings have no "src" property.
You can use vanilla JavaScript to build your img element:
var paintedElement = document.createElement("img");
paintedElement.src = url;
paintedElement.class = "heightImg";
paintedElement.onerror = function invalidUrl() {
paint.src = randomvariable;
};
paintedElement.innerHTML = "</br></br>" + description;
// append where you need to append paintedElement
If you're willing to use jQuery, you can create an element:
var paintelement=$('<img src="' + url + '"class="heightImg"/>' + '</br></br>' + description);
paintelement.attr('src','wherever');
paintelement.appendTo('#somewhere');
paintelement.on('error',function(){paint.src = randomvariable;});

document.getelementById doesn't work on dynamically generated divs

I am trying to update the content of a dynamically generated div with .innerHTML and getElementById, but when I test it, I get an error: "Uncaught TypeError: Cannot set property 'innerHTML' of null" I also tried using alert() and checking the value of quizDiv at breakpoints. Well, here's my JS file called main.js:
function makeDiv() {
document.body.innerHTML = "<div id='quizDiv'></div>"
}
function createInputBox(boxId) {
var quizDiv = document.getElementById("quizDiv");
quizDiv.innerHTML = "<input type='text' id='" + boxId + "'>";
}
makeDiv();
createInputBox(1);
Here's my html:
<!-- doctype, head, etc -->
<body>
<!-- content -->
<script src="/main.js"></script>
</body>
Any help is appreciated. Thanks!
Since you already creating the div in js, why not hold the reference then?
function makeDiv() {
var quizDiv=document.createElement("div");
document.body.appendChild(quizDiv);
return quizDiv;
}
function createInputBox(quizDiv,boxId) {
// var quizDiv = document.getElementById("quizDiv");
quizDiv.innerHTML = "<input type='text' id='" + boxId + "'>";
}
var quizDiv=makeDiv();
createInputBox(quizDiv,1);
There are a few problems with you code.
Firstly the HTML is not valid, meaning ID's can't start with numbers. Read more about how to overcome this issue here: CSS-Tricks
Secondly, you code 'works' could you provide an image of your directory structure and the full markup? Here is a jsfiddle with your code and it displays the input: jsFiddle Maybe there is a problem with the file path or your calling the js file before the document is ready.
I cleaned your code up a bit so maybe try this instead:
window.onload = function () {
var body = document.body;
function createDiv (identifier) {
var el = document.createElement('div');
el.id = identifier;
body.appendChild(el);
}
function createInput(identifier) {
var div = document.getElementById('quizDiv');
div.innerHTML = "<input type='text' id='" + identifier + "'>";
}
createDiv('quizDiv');
createInput('bar');
};

Nesting in javascript

I don't know if that title even describes what I want to do, but here goes.
I have some JavaScript, which changes the href of a link, depending on what item is selected in a select box. Here's the code:
function setText(text) {
var selectVal = text;
var url = $('twitter2').attr("href");
url = 'https://twitter.com/intent/tweet?button_hashtag=stream&text=Just enjoying ' + selectVal + ' on';
$('a').attr("href", url);
}
The problem is there are multiple links on the page. Would there be a way to specify which link to change the URL of? Sorry for the woeful explanation, here's the accompanying html.
<twitter2><a><img src="http://stream.cz.cc/images/twitter.png" onmouseover="this.src='http://stream.cz.cc/images/twitterover.png'" onmouseout="this.src='http://stream.cz.cc/images/twitter.png'" /></a></twitter2>
Any advice?
Add an id to your image tag and JQuery select it by the ID.
<img id="THISONE" src="http://stream.cz.cc/images/twitter.png" onmouseover="this.src='http://stream.cz.cc/images/twitterover.png'" onmouseout="this.src='http://stream.cz.cc/images/twitter.png'" /></a>
Javascript:
function setText(text) {
var selectVal = text;
var url = $('twitter2').attr("href");
url = 'https://twitter.com/intent/tweet?button_hashtag=stream&text=Just enjoying ' + selectVal + ' on';
$('#THISONE').attr("href", url);
}
first of all
var url = $('twitter2').attr("href") would give you nothing, as twitter2 does not have any href attribute.
second, you can access your a as:
url = 'https://twitter.com/intent/tweet?button_hashtag=stream&text=Just enjoying ' + selectVal + ' on';
$('twitter2 a').first().attr("href", url).
This will change the href of the first a inside the <twitter2> tag

applying image using innerHtml Method but its not working

Hello friends here's my code
function dropItems(idOfDraggedItem,targetId,x,y)
{
var html = document.getElementById('dropContent').innerHTML;
if(html.length<=0){
html.innerHTML='<img src="images/drag.jpg" alt=" " />'
}
if(html.length>0)html = html + '<br>';
html = html + document.getElementById(idOfDraggedItem).innerHTML;
document.getElementById('dropContent').innerHTML = html;
}
I want to to show a image in div when its empty.. but when it receive any data i want to remove that image by using this script .but its not working plz help me
function dropItems(idOfDraggedItem,targetId,x,y)
{
html = document.getElementById('dropContent');
if(html.innerHTML.length<=0){
html.innerHTML='<img src="images/drag.jpg" alt=" " />'
}
if(html.innerHTML.length>0)html = html + '<br>';
html = html + document.getElementById(idOfDraggedItem).innerHTML;
document.getElementById('dropContent').innerHTML = html;
}
function dropItems(idOfDraggedItem,targetId,x,y)
{
var html = document.getElementById('dropContent');
if(html.innerHTML.length<=0){
html.innerHTML='<img src="images/drag.jpg" alt=" " />'
}
if(html.innerHTML.length>0)html+='<br>';
html += document.getElementById(idOfDraggedItem).innerHTML;
document.getElementById('dropContent').innerHTML = html;
}
var html = document.getElementById('dropContent').innerHTML;
Here your passing the value to 'html'. not the reference of 'dropContent'. So you can't call 'innerHTML' on variables.
//Modified code
function dropItems(idOfDraggedItem,targetId,x,y)
{
var html = document.getElementById('dropContent').innerHTML;
if(html.length<=0){
html = '<img src="images/drag.jpg" alt=" " />'
}
if(html.length>0)html = html + '<br>';
html = html + document.getElementById(idOfDraggedItem).innerHTML;
document.getElementById('dropContent').innerHTML = html;
}
The problem is that the dropContent may not be empty even if it shows nothing; because, Javascript does not ignore the White-Spacing so there may be a white-space that keep the length bigger than zero.
Here is the solution, using the jQuery library as it has the needed methods to Trim the contents and other things:
function dropItems(idOfDraggedItem, targetId, x, y) {
var html = $("#dropContent").html();
html = $.trim(html);
if (html.length <= 0) {
var imageContent = $('<img src="images/drag.jpg" alt="" /><br />' + $("#" + idOfDraggedItem).html());
$("#dropContent").html(imageContent);
}
}
It worked for me in a test page I created.
The first line gets the html out of the element, second line trims it and thirth line checks if it is empty.
Forth line creates an element with the html string and the html content of the idOfDraggedItem element.
Fifth line sets the html content of the dropContent to the html content of the recently created element.
That's it.
Hope this works for you too.
PS the .html() method of jQuery extracts the innerHtml of the element, if you want the outerHtml, wrap the element in a div and get the .html() from div to get the outHtml of the wrapped element.

Categories

Resources