Append jQuery code into iframe does not work - javascript

I encounter a very strange problem!
I wrote the following code:
<script type="text/javascript" src="jquery-1.8.3.min.js"></script>
<textarea id="code">
<div id="hello">Hello world!</div>
<script type="text/javascript">
$(function(){
$("#hello").css({"border":"solid 3px red"});
alert($("#hello").size());
});
</script>
</textarea>
<iframe src="iframe.html"></iframe>
<script type="text/javascript">
$(function(){
$("iframe").on("load",function(){
$(this).contents().find("body").append($("#code").val());
});
});
</script>
The "iframe.html" file contains only a call to the jQuery library.
The result is that "Hello world!" is displayed in the iframe but without red border! It seems that $("#hello") does not work. In fact, if I do alert($("#hello").size()), I get "0".
Do you have any idea?
Thanks!
Edit: Add "alert".

$(this).contents().find("body").append($("#code").val());
Only gets the current value so probably it wont copy over any css value that is linked to it.
http://api.jquery.com/val/
What I suggest is testing it in 1 file first to see what it does so remove the iframe part for now and check the .size() on 1 file. that way you know how the .val and .size() behave on your #hello.
Try this as the script under the :
<script type="text/javascript">
$(function(){
$("iframe").on("load",function(){
alert($("#code").val());
var scriptx = $("#code").val();
$(this).contents().find("body")[0].innerHTML = scriptx;
});
});
</script>
});
</script>

I think the html format is wrong. You are putting the div inside the text area and inside any text area if you put some html elements then those are simply taken as some text and that html elements are not going to render in browser.
So you can put the the div element out side the text area.
<textarea id="code"></textarea>
<div id="hello">Hello world!</div>
I hope this will work.. :)

Related

JQuery method not giving the expected result

Thiis is my code:
$("p").css("background-color", "yellow");
alert( $("p").css("background-color"));
The alert is returning undefined instead of the color.
I tried on both Google Chrome and Firefox. I have extracted this from the w3c website and in their example, it works (I am even using the same jQuery version).
Either you're calling that code before jQuery loads, or you don't have a <p> tag in your document at the time the code is executed.
To test the first case, move the script to the window's onload event handler. This code will be run only after all scripts have been loaded.
window.onload = function(){
if(window.jQuery){
$("p").css("background-color", "yellow");
alert( $("p").css("background-color"));
}
else{
alert("jQuery is not loaded");
}
}
If the alert jQuery is not loaded opens, you've identified the problem
To test the 2nd case, just be sure to include a <p> tag in your document before you try to change its CSS.
Works perfectly fine in this JSFiddle.
$("p").css("background-color", "yellow");
alert( $("p").css("background-color"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
test
</p>
Verify that you have a <p> tag in your HTML (like in my fiddle), and check if you have JQuery included, like so:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
try this instead of your script.
$(document).ready(function(){
$("button").click(function(){
$("p").css("background-color", "yellow");
alert( $("p").css("background-color"));
});
});
for html try this
<body>
<h2>This is a heading</h2>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button>Click me</button>
</body>
this is basic Javascript. you should need to define which html property you want to change using Javascript.
Make sure you've included JQuery source in the head tag.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
The code's working fine on JSFiddle.
checkout: here
never mind, I found the reason it isn't working. I created the p AFTER this instruction, so it was actually selecting nothing.

JQuery & advanced javascript

i am trying to get a value in input box automatically by clicking button "get name", from database. how can i implement it...?
my so far work is below...
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
var n = $("#div2").load("getTotal.html #p1").val();
$("#div2").val(n);
});
});
</script>
</head>
<body>
<input type="text" id="div2" value=""/>
<button>Get Name</button>
</body>
</html>
and getTotal.html page contents...
<h2>jQuery and AJAX is FUN!!!</h2>
<p id="p1">John D. Feller</p>
in doing so.... i am getting an error "[object, Object]".
Help me out....with this error and advice me how can i take values from database.
Issues in the code:
1) $("#div2").load(...) doesn't make much sense because it's telling jQuery to pull the content of the URL as HTML content of #div2. Here #div2 is an input which is not supposed to have HTML content. http://api.jquery.com/load/
2) You may want to load only the content of #p1 by using getTotal.html #p1, but this syntax won't work as you expected. jQuery can only pull the full content of getTotal.html, then you need to extract content of #p1 from it.
Assuming getTotal.html page is in same directory as your main page, the JS code can be modified to:
$(document).ready(function(){
$("button").click(function(){
$.get("getTotal.html", null, function(text) {
$("#div2").val($(text).filter("#p1").html());
});
});
});

Simple jQuery .load Example Not Working

I'm sure this is a fairly basic question, but I'm relatively new to jQuery so was hoping someone might be able to help.
Basically, I need to load an HTML snippet into a page. This works fine when the snippet contains just HTML, but not when it contains a script.
I've stripped down my code to the bare minimum for clarity. This is index.html:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
</head>
<body>
<h1>Heading</h1>
<div id="banner"></div>
<script>
$(document).ready(function(){
$('#banner').load('banner.html');
});
</script>
</body>
</html>
And banner.html contains just the following (as an example):
<h2>Subheading</h2>
<script>
document.write('Hello');
</script>
The script is executed, but for some reason it strips out the rest of the HTML in both index.html and banner.html (i.e. it just displays "Hello" and nothing else).
Any help greatly appreciated!
document.write after the page has load writes to the document, and at the same overwrites everything else currently in the document, that's why you end up with only the string "hello".
Just remove the document write :
<h2>Subheading</h2>
<p id="test"></p>
<script>
document.getElementById('test').innerHTML = 'hello';
</script>
that is becuase when banner.html is loaded .. the script inside banner.html get executed, which writes "hello" in your document(the document here is your entire index.html)
one way to understand this is by replacing certain content of banner.html rather than the whole document.
banner.html
<h2>Subheading</h2>
<div id="divID"></div>
<script>
$('#divID').html('hello'); //using jquery .. gets the element with id as divID and replace the HTML
</script>
here i am replacing just the div whose id is "divID" rather than replacing the enrite document

jQuery next() - selector

I have a few sets of javascript codes and divs just below them:
<script type='text/javascript'>
jQuery(document).ready(function(){
jQuery(".display").something({
/*myfunction*/
});
});
</script>
<div class="display"></div>
<script type='text/javascript'>
jQuery(document).ready(function(){
jQuery(".display").something({
/*myfunction*/
});
});
</script>
<div class="display"></div>
(...)
Is there a way of selecting only the .display div after exact JS? I've been thinking about next() but it's hard to attach to document.ready ;)
You should give each <div> an id and attach handlers that way.
Javascript doesn't really care where within HTML you write it. Put all your Javascript in a script file and refer to DOM elements by className/id.
Just give each DIV a unique id, and use that id in your selector.
You could give the script tag a unique id and call next():
<script id="script-tag-1">
jQuery(function() {
var node = $('#script-tag-1').next('.display');
});
</script>
<div><!-- content --></div>
jsFiddle: http://jsfiddle.net/SYgEX/
Everything was generated dynamically (that's why I asked how to change my JS code, WITHOUT touching DOM!).
Anyways I've found the best way.
<?php $id = rand(); ?>
<script type='text/javascript'>
jQuery(document).ready(function(){
jQuery(".display-"<?php echo $id;?>").something({
/*myfunction*/
});
});
</script>
<div class="display-<?php echo $id;?>"></div>
Not perfect, but it works at least (and could possibly break, but chances are really low).

add javascript into a html page with jquery

I want to add a javascript google ad but I can't insert the javascript into the div using jquery. I try to simulate my problem with this test, which is using some advice I found on stackoverflow , but it does not work.
I want <script type='text/javascript'>document.write('hello world');</script> to be inserted in the div, and "hello world" be displayed between the tag_1 and tag_2.
Here is the code :
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var str="<script type='text/javascript'>document.write('hello world');";
str+="<";
str+="/script>";
$('#insert_here').append(str);
});
</script>
</head>
<body>
tag_1<br/>
<div id="insert_here">
</div>
tag_2<br/>
</body>
</html>
Tanks for your answers,
Lucas
See my answer to Are dynamically inserted <script> tags meant to work? for why you can't use innerHTML, which jQuery's functions map to when passed a HTML string, to insert a script element. document.write will also fail when used after the document has been fully parsed.
To work around this, you will have to use DOM functions to insert an element into the div. Google ads are iframes, so it's usually a case of finding the iframe code and appending that instead.
To correctly insert a script element, you need to use DOM functions, for instance:
var txt = 'alert("Hello");';
var scr = document.createElement("script");
scr.type= "text/javascript";
// We have to use .text for IE, .textContent for standards compliance.
if ("textContent" in scr)
scr.textContent = txt;
else
scr.text = txt;
// Finally, insert the script element into the div
document.getElementById("insert_here").appendChild(scr);
I figured out a great solution:
Insert your Google Adsense code anywhere on your page - e.g. if your CMS only allows you to put this on the right hand side then stick it there.
Wrap a div around it with display:none style
Add some jquery code to move the div to the location you desire.
Since the javascript has already run there is no problem then with moving the block of script to wherever you'd like it to be.
e.g. if you wish to put 2 blocks of google adverts interspersed throughout your blog (say after paragraph 1 and after paragraph 4) then this is perfect.
Here's some example code:
<div id="advert1" style="display:none">
<div class="advertbox advertfont">
<div style="float:right;">
<script type="text/javascript"><!--
google_ad_client = "pub-xxxxxxxxxxxxxxxxx";
/* Video box */
google_ad_slot = "xxxxxxxxxxxxxxxxx"
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>
</div>
</div>
<script>
$(document).ready(function() {
$('#advert1').appendTo("#content p:eq(1)");
$('#advert1').css("display", "block");
});
</script>
p.s. #content happens to be where the content starts on my CMS (Squarespace) so you can replace that with whatever you have in your CMS. This works a treat and doesn't break Google ToS.
You cannot use document.write after the page has finished loading. Instead, simply insert the contents that you want to be written in.
<script type="text/javascript">
$(function() { // This is equivalent to document.ready
var str="hello world";
$('#insert_here').append(str);
});
</script>

Categories

Resources