Dynamic inserting HTML inside DIV and accessing the new elements - javascript

I am loading remote HTML into a DIV using jQuery and need to access all the elements and JS contained therein. Seems as though the inserted HTML is added and renders correctly but the elements are not in the DOM. How can I access these new elements ? Using document.getElementById('myDiv') returns null
var canvas .. in the script below returns null and I don't understand why.
<script>
function draw(){
var canvas=document.getElementById("pdf1");
var pdf=canvas.getContext("2d");
// other code here populates canvas.....
}
</script>
<body>
<div>
<canvas id="pdf1" width="801" height="1041"></canvas>
</div>
</body>
<script type="application/javascript">
$(window).load(draw());
</script>
</html>

$('#new_html_wrapper').load('file.html', function(){
// Access the new DOM elements here inside the load callback.
$(this).on('#myDiv','click',function(){
alert('You clicked on myDiv!');
});
$('#myDiv', this).css('background','red');
});
// Accessing the elements here will fail as they haven't been loaded yet.
Read more: http://api.jquery.com/load/
Also don't use document.getElementById('myDiv').
You already have jQuery loaded so do: $('#myDiv').

If you need to bind events to those new elements use the .on() function

You would have tried to get the content before HTML inserted there.
you should try accessing the element after content inserted. i.e. if you call the same function after content inserted, you can get the content in div.
or if you want to bind some events like click, on the content which comes later(inserted data like in your case) as well, you can live bind the events as below
$("div.className").live("click",function(){ alert('1'); })
or
$("document").on("div.className","click",function(){ alert('1'); })

Related

The buttons not working when I use load() function in jquery

When I use the load() method,the buttons in the file that loaded don't work;
Code in main page;
$("html").load("demo.php")
Code in demo.php;
<button id="btn">Alert</button>
<script>
var btn = document.getElementById("btn");
btn.onclick = function(){
alert("Hello")
}
</script>
The button works fine when i only open the demo.php but doesn't work when i load it into another document.
Any solutions?
When I replaced the html selector with the body selector it worked
$("body").load("demo.php")
I found out something but still doesn't explain the reason.
When I use the Javascript inline then it will work in the main page like this;
<button onclick="alert('hello')" id="btn">Alert</button>
Please try other element insted of html
$("another selector").load("demo.php")
Add another elemnt in to your first page and use that elemt to load demo.php
When you are loading the demo.php you are removing the jquery from your page thats why you are getting nothing
Try to create another elemnt as i mentioned above
$("div").load("demo.php")
When calling .load() using a URL without a suffixed selector expression, the content is passed to .html() prior to scripts being removed. This executes the script blocks before they are discarded. If .load() is called with a selector expression appended to the URL, however, the scripts are stripped out prior to the DOM being updated, and thus are not executed.
So when you call:
$("#buttons").load("demo.php");
This will execute the Script block. You may want to consider adjusting this block to ensure it can work with the DOM better. Consider the following.
<button id="btn">Alert</button>
<script>
$("#buttons").on("click", "#btn", function(e){
alert("Hello")
});
</script>

Confusing jQuery behaviour

I've got a basic HTML page, consisting of just:
<body id="body">
<script src="js/jquery-2.0.3.js" type="text/javascript"></script>
<script src="js/three.min.js" type="text/javascript"></script>
<script src="js/stats.min.js" type="text/javascript"></script>
<script src="js/application.js" type="text/javascript"></script>
</body>
as the main body of a index.html page, and where the content of application.js is:
function init() {
var container = $('div');
container.attr('id', 'container');
$('body').append(container);
alert('Container: ' + $('#container').length);
}
$(function() {
init();
});
So this is clearly some very basic code, I create a div and append it to the body. However, the alert call I make returns 0 and when I inspect the DOM tree via chrome, no div is added.
As I'm adding the script files to the bottom of the <body> tag, and calling init() from a jQuery ready() block, why would this be happening? Seems like such a basic and simple task.
Note: No errors are being thrown in chrome's console
Your line var container = $('div'); isn't creating a DIV, it's selecting one. If you want to create a container then do var container = $('<div></div>');
As a result, your current code returns an empty jQuery object, but you don't notice as jQuery plays nicely with them, and just does nothing.
$('div')
This selects all <div> elements in your page using an element selector.
You don't have any <div> elements, so it returns an empty jQuery object.
The rest of your code therefore has no effect.
It sounds like you actually want to create a new element:
$('<div />')

Dynamically load fancybox and attach it?

I am trying to dynamically load fancybox via getScript and then attach it to a element. I have the fancybox dynamically load inside of a document ready...
So it goes.
documents ready -> getScript
But it doesn't seem to want to attach to my a tag (.fancybox) if I do a console.log jQuery('.fancybox') I get a [] but the element is already loaded? And if I type in jQuery('.fancybox').fancybox(); in the console in Google Chrome it still doesn't work?
Any idea what I am doing wrong?
jQuery.getScript("/fancybox/jquery.fancybox.pack.js", function() {
console.log(jQuery(".fancybox"),jQuery("a"));
return jQuery(".fancybox").fancybox();
});
The element is a simple a tag wrapping an image, and it is NOT dynamically loaded.
<div class="youtube"><img height="181" src="images/youtube-video.png" width="326"></div>
document ready is too early try wrapping it in $(window).load(function(){//CODE HERE}); instead because it needs to run only after DOM has loaded so it can apply your fancybox to your DOM element.
Try this:
jQuery.getScript("/fancybox/jquery.fancybox.pack.js", function() {
jQuery(document).ready(function() {
jQuery(".fancybox").fancybox();
});
});
EDIT: function call fixed

How to make a div onload function?

I want to load an HTML page as a div inside my webpage by removing its HTML and body tags. But the HTML page has a <body onload=" ... " > , I need this function to continue working. Seems <div onload=" ... " > is not working. How can I insert this onload function into my website's body (on this page only) without directly editing my original website code (php)?
Have you used jQuery before? If so, just get the id of your div (let's say "SomeDiv") and then use the "ready" method like this:
$("#SomeDiv").ready(
function(){
//do stuff
});
you can use jQuery.load to load the contents of the page into your div
$(document).ready(function() {
$("#containing-div").load("[url of page with onload function]");
});
the code above goes in the page that contains the div. the page with the onload function doesn't get changed.
You can add an additional Javascript tag at the end of the loaded page (once inserted inside the div) which will executing as soon as it's loaded. Like this:
<div>
Insert the inner html content of that pages here and add this script at the bottom and add the onload function of the original html to this script.
<script type="javascript">
alert("hello world");
</script>
</div>
Just remember to have the javascript available to your page. What I mean is that if the javascript function called which is called inside onload="..." is defined in the <head> of the loading html document and you're throwing the <head> out then this won't work.
Not the best but one way is to check the div periodically if it's loaded:
var myInterval = setInterval(function () {
if ($('.mydiv') && $('.mydiv').width() > 0) {
// write your logic here
clearInterval(myInterval);
}
}, 3000);
If you want to add the onload event on a div, you cannot, but you can add onkeydown and trigger the onkeydown event on document load.
<div onkeydown="setCss();"></div>
$(function () {
$(".ccsdvCotentPS").trigger("onkeydown");
});

jQuery fn() isn't loading / working?

There is one div which changes frequently it's innerHTML by ajax. Once the page loads, jQuery function() works but when innerHTML changes by ajax then some functionality doesn't work. I checked the code using firebug and try to explain it in short.**
I think DOM loads the js file only when the page loaded first time and if ajax modifies innerHTML then function is not invoked somehow.What you say? what could be solution according to you?
HTML page
<body>
<div class="_div_change"> dynamically class add by jQuery function()
here contenet is added by ajax functionality
</div>
<script type="text/javascript">
$(function(){
$('._div_change').addClass('.div_class');
});
</script>
</body>
Loading first time & class is added by fn() |only div innerHTML modified by ajax ***
|
<div class="_div_change div_class"> | <div class="_div_change">
innerHTML elements added successfully| innerHTML elements altered successfully
</div> | </div>
Your script is incomplete, but assuming that it looks like this:
$(function(){
$('._div_change').addClass('.div_class');
});
...then what you're doing there is telling jQuery to run that function once when the DOM is initially loaded (calling $() with a function is a shortcut to jQuery.ready). If you want to re-run that function when you update the div's contents via ajax, you'll have to do that in your success handler on the ajax call.
You can give jQuery a function that it will call whenever any ajax call is complete, via jQuery.ajaxSuccess, which may be useful.
Yes, the code only runs once when the page loads.
The $(function(){...}); is the short form of hooking up the ready event for the document: $(document).ready(function(){...});.
If you change the DOM and want to apply the jQuery code to the new elements, you should rerun the code with the parent element as scope. Create a function with the code and a scope parameter:
function updateElements(scope) {
$('._div_change', scope).addClass('.div_class');
}
Now you can run the function from the ready event with the document as scope:
$(function(){
updateElements(document);
});
When you have loaded new content into an elements, lets say one with id="asdf", you can rerun the function with that element as scope, and it will apply the changes only to the newly added content:
updateElements($('#asdf'));

Categories

Resources