Inject script inside ajax loaded div - javascript

I'm using Jquery in my site and I have a div with content loaded by ajax, like an iFrame. With my code I can access the content and even change the class and values, but I can't insert a script to be executed.
There is the code:
<script>
$("#loginsb").click(function () {
$('#curso')
.contents()
.find('#script').jQuery("<script>").prop("tagName")
.attr('src', load.js);
});
</script>
My ajax loaded div is curso and inside this div I have another div script where I placed the the script line - without the src. Is the only way I knew to use more than one script in my page and find just one of them.
Inside Curso div
<div id="script">
<script></script>
</div>
Any idea to attribute this src inside my div script? Thanks!

You miss some basics in understanding Javascript and jQuery.
First thing: you can only have one element with id="script" and in your example you have one script element inside it.
So you can target that script element inside the script id element using jQuery:
$('#script script')
Then adjust the source of the script:
$('#script script').attr('src', 'load.js');
(Note the quotation marks around load.js. this is a string literal not a variable or constant.)

Related

Can jQuery replace text with JavaScript that is then executed

I have a page with headers, images, etc. I'd like to replace a "page" div with another file of HTML, JavaScript, etc using Ajax and execute JavaScript on that page after it is loaded. How do I do this and also handle < , ", and other tags in the file and pass the page some parameters?
Is the other "page" content owned by you? If so, you can have javascript methods on your main "container" page, then once you fire the method to pull the contents of the new "page" div, fire the corresponding javascript method you need, since any necessary DOM elements will have been added to the page at this time.
To do it the way you mentioned, you can follow the steps seen here to use the dynamic script pattern: Executing <script> inside <div> retrieved by AJAX
Basically, you host your javascript externally, then once the page has loaded, add the "src" tag to a script element and it will execute.
As for handling special characters, you can follow steps with jQuery's ajax call to inject HTML from the other page into your current one, such as here: How to get the html of a div on another page with jQuery ajax?
$.ajax({
url:'http://www.example.com/',
type:'GET',
success: function(data){
$('#ajaxcontent').html($(data).find('body').html());
}
});
(Instead of targeting a specific div on the external page, you would target the body or parent container div)
given an html page
<html>
...
<body>
<div class="page">
some html content...
</div>
</body>
</html>
you can replace the content of the div via the jQuery function load()
$("div.page").load("an-http-resource.html");
Use an AJAX request to get the HTML file as a response.
Replace the "page" div innerHTML with the response.
If the HTML page has a bunch of headers and such and you only want a certain portion of that HTML file, you may want to use getElementById or some other method of selecting the portion of the HTML file.
The HTML entities will appear as they normally would in a browser, if that is what you mean by handling < and " and other tags.
You can send parameters by editing the endpoint:
index.html?date=today&car=yours

getting the contents of a div tag with class

I am trying to read the particular contents of an child IFrame wrapped in a div tag from parent window. I am using
detailsValue = window.frames['myIframe'].document.getElementById('result').innerHTML;
with this I'm able to access the entire content of that frame. But I need to access only a portion of that content. The problem is that the div which wraps the content that I am looking for contains only class and no ID.
<div class="watINeed"> <table class="details"> </table> </div>
I am unable to access the content which is in a form of table (with no id and only class).
Any help.
Edit1: I need to access the content of the table to check for char length and also for some html tags present in that content.
You can do this either using plain Javascript (as mentioned by Notulysses):
window.frames['myIframe'].document.querySelector('.watINeed .details')
or using jQuery (since you aded jquery) by specifying the iframe's document as context to $:
$(".watINeed .details", window.frames['myIframe'].document)
In the latter case you've a fullfeatured jQuery object.
Note that in either case the iframe's document has to be on the same domain otherwise you'd run into cross origin issues.
Tested against jQuery 2.0.x
Update
If you're running the selector during page load of the including page, you'll have to listen to the load event of the iframe before accessing its content:
$(window.frames['myIframe']).on("load", function(){
// above query here
});
If your are looking for a vanilla Javascript, and your target div is a direct children of starting selector, it is a simple task
var detailsValue = window.frames['myIframe'].document.getElementById('result').innerHTML;
var target;
for(var i = 0; i< detailsValue.children.lenght; i ++){
if(detailsValue.children[i].getAttribute('class')== 'watINeed'){
target = detailsValue.children[i] ;
}
}
otherwise, have to write a recursive method to scrap all children of structure
As i wrote above, it can be done using the following:
document.querySelectorAll(".className")[0] or $(".className")[0]
those are basically the same as both return a list of nodes and the [0] simply means taking the first result from the list.
there are 2 things to pay attention to:
the iframe loads the content asynchronously therefore when you execute the query its most likely that the elements you are searching for did not load yet.
executing the code after DOM loads is not enough.
the solution is simply put your code in a block that executes once all the asynchronous content is loaded:
window.onload=function(){
window.frames['myIframe'].document.querySelectorAll(".watINeed")[0];
}
or the jQuery alternative:
$(window).load(function(){
window.frames['myIframe'].document.querySelectorAll(".watINeed")[0];
});
the second thing is, according to the page Here, you can access the iframe's document using contentWindow.document:
window.onload=function(){
window.frames['myIframe'].contentWindow.document.querySelectorAll(".watINeed")[0];
}
or the jQuery alternative:
$(window).load(function(){
window.frames['myIframe'].contentWindow.document.querySelectorAll(".watINeed")[0];
});
live example: Fiddle

Am I safe executing this outside "document.ready()" block?

Would I be safe moving this piece of code out from inside the document.ready() block.
var $userInfoNode = $('#userOptions');
CURR_USER_ID = $userInfoNode.attr('data-userId');
CURR_USER_NAME = $userInfoNode.text();
This code is placed in an external js file that is loaded from the head section of html page & selects an html element placed within html body, to extract data from there.
Short answer: No, since the JavaScript file is placed in the header.
The DOM (Document Object Model) needs to contain the <div id="userOptions"> when the code is executed.
Either you place the code after the div, for example right before the closing </body>.
Or you place the code within the $(document).ready() function, which is triggered as soon as the DOM is fully loaded.
out of the document.ready() block.
external js file that is loaded from the head section
selects an html element placed within html body
=> No. You can try it and will find $userInfoNode empty.
Yes.
You also need to ensure that the html elements you are going to refer to appear before your javascript.
in short put this
var $userInfoNode = $('#userOptions');
CURR_USER_ID = $userInfoNode.attr('data-userId');
CURR_USER_NAME = $userInfoNode.text();
at the end of your html page...
If you have to/want to keep it in an external file you can place the script element that references it at the bottom before your closing body tag. It looks a little weird at first but it is valid.

Syntax Highlighter Around A Div Element

I am using the syntax highlighter plugin and I want to always have it applied to a specific div area. The div's content will change based on a on-click hyperlink. How can I enclose the syntax highlighter script tag around the "mydiv" element at all times?
<script>
function viewCode() {
$('#mydiv').load('euler/_48.py');
}
</script>
View Code
<div id="mydiv">
my div's initial content
</div>
<script type="syntaxhighlighter" class="brush: js"><![CDATA[
//always apply this script to mydiv
]]></script>
With syntaxHighlighter, you cannot highlight arbitrary elements on the page, so we will stick to the script method instead.
First, give the script and anchor tag an id, like
Show Code
<script type="syntaxhighlighter" class="brush: js" id="highlighted"></script>
Then, use this to load the contents when the user clicks on the link
$('#show_code').click(function(){
$.get('euler/_48.py', function(data){
$('#highlighted').html('<![CDATA[' + data + ']]>');
SyntaxHighligher.highlight();
});
});
Remember that the usual method to use syntexhighlighter.js would not work here because the SyntaxHighlighter.all() function only binds the highlight() function to the onload event, so you will have to call that function yourself every time the page updates, by adding a call to the SyntaxHighligher.highlight() function everytime you update the page.
Alternatively, I'd usually recommend the pre method. Its almost the same as above, but we use the pre element instead and use the text() jQuery function to get the escaping done correctly. Using the pre element:
<pre class="brush: js" id="highlighted"></pre>
With this piece of Javascript
$.get('euler/_48.py', function(data){
$('#highlighted').text(data);
SyntaxHighligher.highlight();
});
I think you can call HighlightAll method
Example:
dp.SyntaxHighlighter.HighlightAll('code');
Sultan

Removing a word from a class using jquery

I have the following html on a page:
<h1 class="theme-color-3">Knowledge Portal Site</h1>
This is rendered dynamically.I dont want the word Site after 'Knowledge Portal'.I dont know where the word Site is hardcoded,so i wrote the following jquery code to remove that word.
$(document).ready(function() {
$('h1.theme-color-3').html($('h1.theme-color-3').html().replace('Site',''));
});
But the problem is that because this code executes only after the whole page has finished loading,the word Site shows for some time and then disappears.
Is there a way to prevent that ?
Thank You
Place a <script> element right after the <h1> element, like so:
<h1 class="theme-color-3">Knowledge Portal Site</h1>
<script type="text/javascript">
$('h1.theme-color-3').text($('h1.theme-color-3').text().replace('Site',''));
</script>
This will ensure the script is processed immediately after the element is parsed, so make sure the jQuery script is in the <head> or at least further up the document. Also, use text() instead of html() if you're not applying HTML. It's more efficient.
You can use CSS to set the element to display:none, but that would leave those with javascript turned off without the element at all.
Basically there is no good solution.

Categories