AJAX - load all div elements - javascript

I have a webpage with a number of div elements such as this one:
<div id='ahFyb2JpdGFpbGxlc2FuZGJveHIKCxIA'>
</div>
I would like each div element to call a javascript function when it has loaded, to fill in the div. Ideally I would have liked to do
<div id='ahFyb2JpdGFpbGxlc2FuZGJveHIKCxIA'
onload=getcontent('ahFyb2JpdGFpbGxlc2FuZGJveHIKCxIA');>
</div>
but of course, onloads are not allowed for div elements. Is there a way to do this? I have read in a number of places that jQuery can help for this, but I can't figure out how to code it up. Any help would be very much appreciated!

To do it without jquery, you just need to set the onload for the window, and tell it what to do with each div. But jquery makes this much simpler.
So without:
window.document.onload = function() {
var divs = document.getElementsByTagName("div");
for(var i = 0; i < divs.length; i++)
divs[i].text("blah blah blah");
}
};
It might be innerHTML. I'd have to double check. But that's the gist. With jquery:
$(function(){
$("div").text("blah blah blah");
};
This of course assumes each div gets the same text. If you want it to be based on ID or class, you most certainly want jquery.
PS - Most web pages try to avoid placing javascript event handlers in the actual HTML. If yous set up the event handlers on load, there's no need and the code is cleaner. Jquery definitely helps on this.

If you're basing the content on the ID of the div, a slight modification to Anthony's code should work
document.onload = function() {
var divs = document.getElementsByTagName("div");
for(var i = 0; i<divs.length;i++){
divs[i].innerHTML = getContent(divs[i].id);
}

I would assign a class to the div's that you want to 'autoload' their own content. This makes the markup clearer and the JavaScript more concise.
$(function() {
$('.autoload').each(function() {
// Use AJAX
$.get("service.php", {id: this.id} function(response) {
// Handle server response here
});
// Or a local data island
this.innerHTML = getDataById(this.id);
});
});

With jQuery:
You should consider using $.load() to retrieve html content. It's slightly easier to use than $.get(). Altho it'll use POST semantics if you supply paramters...
In any event, do you really want to make separate calls back to server for each div? .. Perhaps you should consider a single call that sends the accumulated set of div id's awaiting content to a your web-service function, that then subsequently returns a json structure that you can walk thru at success filling divs all in one shot ..
Something like (not-tested!):
$(function() {
var ids = [];
$('div.autoload').each() { function() { ids.push($(this).attr('id')); });
$.get('service.php', {ids: ids}, function (response) {
$.each(response.perdiv, function (i, c) {
$('div#' + c.id).html(c.html);
});
});
});

Related

Trying To Add Onclick To Links, But Can't With .onclick

So I'm trying to use ajax to put content into a div, and trying to have it change all internal links before it adds the content so that they will use the funciton and load with ajax instead of navigating to another page. My function is supposed to get the data with ajax, change the href and onclick attributes of the link, then put it into the div... However, all it's doing is changing the href and not adding an onclick attribute at all. Here's what I was using so far:
function loadHTML(url, destination) {
$.get(url, function(data){
html = $(data);
$('a', html).each(function(){
if ( $.isUrlInternal( this.href )){
this.onclick = loadHTML(this.href,"forum_frame"); // I've tried using both a string and just putting the function here, neither seem to work.
this.href = "javascript:void(0)";
}
});
$(destination).html(html);
});
};
Also, I'm using jquery-urlinternal. Just thought that was relevant.
You can get the effect you want with less effort by doing this on your destination element ahead of time:
$(destination).on("click", "A", function(e) {
if ($.isUrlInternal(this.href)) {
e.preventDefault();
loadHTML(this.href, "forum_frame");
}
});
Now any <a> that ends up inside the destination container will be handled automatically, even content added in the future by DOM manipulations.
When setting a function to onclick through js it will not show on the markup as an attribute. However in this case it is not working because the function is not being set correctly. Easy approach to make it work,
....
var theHref=this.href;
this.onclick = function(){loadHTML(theHref,"forum_frame");}
....
simple demo http://jsbin.com/culoviro/1/edit

how to create onclick for a link

i have a div for which i set value dynamically during run time, if there is value than i have enable or create a link which will have onclick method where i will call a javascript method.
how to do this in jquery or javascript?
I set value to a div like the following,
document.getElementById('attachmentName').innerHTML=projectInforamtionMap.Cim_AttachmentNames;
this the div :
<tr>
<td align="left"><div id="attachmentName"> </div></td>
</tr>
Kindly help me to find and fix.
Best Regards
You can set a onclick function:
document.getElementById('attachmentName').onclick = function() {};
Assume that your function are previously define like this
function foo(){alert('function call');}
After adding innerHTML
In Javascript
document.getElementById('attachmentName').setAttribute('onclick','foo()');
In Jquery
$("#attachmentName").attr('onclick','foo()');
You have several alternatives
JavaScript:
// var elem = document.getElementById('attachmentName');
elem.onclick = function() {};
elem.setAttribute('onclick','foo()');
elem.addEventListener('onclick', foo, false); // The most appropiate way
jQuery:
// var elem = $('#attachmentName');
elem.click(foo);
elem.on('click', foo);
$('body').on('click', elem, foo);
Between the 3 jQuery alternatives, the last is the best one. The reason is due to the fact that you are attaching an event just the body element. In this case, it does not matter but in other cases, you are probably willing to attach the same event to a collection of elements, not just one.
Therefore, using this approach, the event is attached to the body but works for the elements clicked, instead of attaching the same event to every element, so it's more efficient :)
$('#attachmentName').click(function(){
//do your stuff
})
jquery way:
$("#attachmentName").click(function() {
some_js_method();
});
You can do this without inserting link in the div in following way
document.getElementById("attachmentName").onClick = function () {
alert(1); // To test the click
};
You can achieve it with the help of jQuery as well in the following way.
$("#attachmentName").click(function ()
{
alert(1);
});
for this you have to include jQuery liabray on the page. refer jQuery.com
Still if you forecefully want to include the link in Div then following is the code for it
var link = $("<a>"+ $("#attachmentName").text() +"</a>");
$("#attachmentName").html($(link);
link.click(function () {
alert(1);
});
Hope this would help.
as i was converting a classical asp details page to a one-page ajaxified page, i converted the existing links in the page to get the details loaded in the DIV in the same page. i renamed the href tag to dtlLink and got that data in the jquery load() function.
detail.asp (server.urlencode is added and required here )
<a href=""#"" onclick=""javascript:LoadDetails(this)"" dtllink="detail.asp?x=" & Server.URLEncode(Request("x"))&y=" & Server.URLEncode(Request("y")) > link text </a>
parent.asp (it has some extra code for holdon.js spinner image, button enable/disable, results div show/hide)
Jquery
function LoadDetails(href) {
//get the hyperlink element's attribute and load it to the results div.
var a_href = $(href).attr('dtllink');
console.log(a_href);
$('#divResults').html('');
DisplayHoldOn();
$('#divResults').load(a_href, function (response, status, xhr) {
$('#divCriteria').hide();
HoldOn.close();
if (status == "error") {
var msg = "There was an error: ";
$("#divResults").html(msg + xhr.status + " " + xhr.statusText);
$('#divCriteria').show();
$("#cmdSubmit").removeAttr('disabled');
}
});
}

is this an acceptable use of jquery data()?

I'm using jquery data() to attach the name of a div I'd like to show when another div (.panel_button) is clicked. I'm doing the attaching of this div's id to the button when the document is ready. Is this an okay way to do this? Or is it too resource intensive and unprofessional-looking?
$(document).ready(function(){
$('#sample_button').data('panel', 'sample_kit_container');
$('#mail_button').data('panel', 'mail_container');
$('#mbillboard_button').data('panel', 'mbillboard_container');
$('.panel_button').on('click', function(){
$('.secondary_panel').hide();
var panel = $(this).data('panel');
$('#' + panel).show();
});
});
Yeah, that should work just fine. As an alternate, you could store the actual element itself (assuming it already exists) rather than finding it each time:
$('#sample_button').data('panel', $('#sample_kit_container'));
$('#mail_button').data('panel', $('#mail_container'));
$('#mbillboard_button').data('panel', $('#mbillboard_container'));
$('.panel_button').on('click', function(){
$('.secondary_panel').hide();
var panel = $(this).data('panel');
panel.show();
});
Another option would be to store the actual jQuery element in the data property, so no need to do a second selection:
$(function(){
$('#sample_button').data('panel', $('#sample_kit_container'));
$('#mail_button').data('panel', $('#mail_container'));
$('#mbillboard_button').data('panel', $('#mbillboard_container'));
$('.panel_button').on('click', function(){
$('.secondary_panel').hide();
var panel = $(this).data('panel');
panel.show();
});
});
#thomas, in my opnion, your solution is actually better than those in the other answers.
Including the whole object inside the data attribute may not always work. For example, what if the $('#sample_kit_container') object doesn't exist on load, but rather ofter an ajax load.
...
Only one tiny comment! why don't you call the data object: panelId. It would be more a bit intuitive.

How to get Information about an element without a callback

I have different container that get reloaded on different events. I have plenty of them, so I gave each container the class load.
This is how all of them look like:
<div class="load" data-href="facebook">
</div>
I also have a function, that is triggered by various actions:
function get_timing(time)
{
$(".load").load("myfolder/mod_"+$(this).attr("data-href")+".php?action="+time, function() {
alert('Here I could use this:' + $(this).attr("data-href"));
}
}
I know that I cannot use this in the example above, I could only use it in the callback. My question is: How can I use attributes of the object to define the path of the load function.
This is how it could work:
function get_timing(time)
{
$(".load").fadeIn(10, function()
{
$(this).load("myfolder/mod_"+$(this).attr("data-href")+".php?action="+time, function() {
alert('loaded');
}
}
}
Is there a way to do this without the asynchronus function (in this case .fadIn) around)
Hope I could explain my problem - thank you in advance!
If you want to go along with classes you can reference them via an index:
var element = $(".load").get(0);
console.log($(element).attr("data-href"));
Note that you have to re-jQueryfy element via $(element) in order to access attr()
If you want to read out all elements with a given class I recommend $.each()
//$.each($(".load"), function(index, value){
$(".load").each(function(index, value){
console.log( $(value).attr("data-href"));
});
Try to give your container an id:
<div class="load" data-href="facebook" id="facebookcontainer">
</div>
Then instead of using this, you can use $("#facebookcontainer") in your javascript.

Calling Javascript in a page after it's been loaded by jQuery GET

Imagine a normal page calling javscript in head. The trouble is some of the content isnt loaded untill i click on a link. Subsequently when this link loads the content it wont work. This is because i guess the javascript has already been run and therefor doesnt attach itself to those elements called later on. There is only standard html being called.
So for example this is the code which calls my external html.
$.get('content.inc.php', {id:id}, function(data){
$('#feature').children().fadeTo('fast', 0).parent().slideUp('slow', function(){
$(this).html(data).slideDown('slow');
});
});
If the html i was calling for example and H1 tag was already in the page the cufon would work. However because i am loading the content via the above method H1 tags will not be changed with my chosen font.This is only an example. The same will apply for any javascript.
I was wonering whether there is a way around this without calling the the javascript as well the html when its received from the above function
If you want to attach events to elements on the page that are dynamically created take a look at the "live" keyword.
$('H1').live("click", function() { alert('it works!'); });
Hope this is what you were looking for.
Does Cufon.refresh() do what you want?
As you said Cufon was just an example, I'd also suggest a more general:
$.get(url, options, function(html, status) {
var dom = $(html);
// call your function to manipulate the new elements and attach
// event handlers etc:
enhance(dom);
// insert DOM into page and animate:
dom.hide();
$target_element.append(dom); // <-- append/prepend/replace whatever.
dom.show(); // <-- replace with custom animation
});
You can attach event handlers to the data that you get via the get() inside of the callback function. For example
$.get('content.inc.php', {id:id}, function(data){
$('#feature').children().fadeTo('fast', 0).parent().slideUp('slow', function(){
$(this).html(data).find('a').click(function(e) {
// specify an event handler for <a> elements in returned data
}).end().slideDown('slow');
});
});
live() may also be an option for you, depending on what events you want to bind to (since live() uses event delegation, not all events are supported).
Andy try this. It will call the Cufon code after each AJAX request is complete and before the html is actually added to the page.
$.get('content.inc.php', {id:id}, function(data){
$('#feature').children().fadeTo('fast', 0).parent().slideUp('slow', function(){
$(this).html(data);
Cufon.replace('h1');
$(this).slideDown('slow');
});
});
JavaScript is not executed because of a security reason OR beccause jQuery is just setting this element's innerHTML to some text (which is not interpreted as a JavScript) if it's contained. So the security is the beside effect.
How to solve it?
try to find all SCRIPT tags in Your response and execute them as fallows:
var scripts = myelement.getElementsByTagName("SCRIPT");
var i = 0;
for (i = 0; i < scripts.length; i++)
eval(scripts[i].innerHTML);

Categories

Resources