jquery .attr() class switch not working - javascript

I'm working on a web service,
when the user requests more data through ajax, I want the div that will contain the data to show a loading circle. I wrote a css class in the style file for when I want the circle:
.ajax_getTeams_loading{
background: url('ajax-loader.gif') no-repeat center center;
}
So my ajax function is like this:
function(profile, divId){
$('#' + divId).attr('class', 'goose');
/*$.get('testGetTeams.php', {username: profile}, function(data) {
$('#' + divId).html(data);
});*/
}
The problem is that the circle never shows up. I tried simplifying the css class to just background-color:blue, but that didn't even work. I also removed the ajax part entirely, and it still doesn't work at all. What am I doing wrong?

At this point I don't see you adding the "ajax_getTeams_loading" class to the div. However, because it's a background you might not see it if there is data in the div. Then it will just be beneath the text or whatever is in the div.
It might be better to replace whatever is in the div with the loading icon, and then replace the loading icon with the newly requested data. Example:
// store your div object in a variable,
// this is faster since you'll be using it multiple times
var div = $('#' + divId);
// replace the div's content with the loader
// you might want to add a width and height to the css
// to make sure the div is large enough to show the entire loading icon
var loader = '<div class="ajax_getTeams_loading"></div>';
div.html(loader);
$.get('testGetTeams.php', {username: profile}, function(data) {
// replace the loader icon with the requested data
div.html(data);
});

Try using
$('#'+divId).removeClass('old_class');
$('#'+divId).addClass('new_class');

It seems you are just setting the wrong class
Your class is ajax_getTeams_loading but you are adding goose. Put the same name and it should be fine.
Also, you might want to look in some jQuery functions:
addClass
removeClass
toggleClass

jQuery has start and stop indicators for AJAX. Since you're using ajax calls, you could try it.
function(profile, divId){
$.ajaxStart(function() {
// add the loading class while ajax is working
$('#loading').addClass("ajax_getTeams_loading");
});
$.ajaxComplete(function() {
// hide the loading div when we're done
$('#loading').hide();
});
// initiate the object sent to the server as a post
var data = {};
data.username = profile;
$.ajax({
url: "testGetTeams.php",
data: data,
type: "POST",
success: function(data){
$('#' + divId).html(data);
}
});
}

Take a note that attr will empty the attribute and replace it with what you pass, so in classes as we can have several of them, if you have, for example:
<div id="ajax_getTeams_loading"
class="classA classB classC">text</div>
and you use
$("#ajax_getTeams_loading").attr("class", "classD");
this will end up having:
text
Which could not be what you want. For this addCLass and removeClass result in a better way to add and remove css classes to the DOM elements in your particular case, you could easily change the way you do thing (not that if does not work, but this is what you find out there the most)
<html>
<head>..</head>
<body>
<div id="ajax-response-wrapper">
<div id="ajax-loading" style="display:none;">
<img src="loading.gif" alt="" /></div>
<ul id="myAjaxPopulatedList"></ul>
</div>
<a id="load" href="javascript:void(0);">Load list from ajax</a>
<script>
$(document).ready( function() {
$("#load").click( function() {
// let's show the loading while we are fetching data
$("#ajax-loading").show();
// get our stuff
$.get('testGetTeams.php', {username: profile}, function(data) {
// we got it, let's hide the loading now
$("#ajax-loading").hide();
// and append the data
$('#myAjaxPopulatedList').append(data);
});
});
});
</script>
</body>
</html>
I hope this helps you get what you want and see how stuff work.

Related

Group of script calls for buttons in a .js using wheelzoom

I have 12 buttons each with an ID, i'm using this script for the action.
$(document).ready(function() {
$("#WEyear18000").click(function() {
$("#WEtextarea").load("Files/Docs/y18000.txt");
$('#WEimage_view').html('<img src="Files/Image/treesimages/PalaeoGlaciolMaps.jpg" >');
$('#WEee244f5837 .PullZone').click();
wheelzoom(document.querySelectorAll('img'));
});
});
WEyear18000, is the id of button, WEtextarea, is the id of the div where txt is displayed on button click, WEimage_view, is the id of the div where new image displayed on same button click, WEee24f5837, is the id to close a collapsible panel where buttons are located.
There are 12 of these script statements in a .js file.
It all works but it causes some strange effects after the 2nd or another button is clicked, all the images on the page disappear but the one on the button click. Page is here, page with issue
Any suggestion on how to stream line script wanted. I a newbe to scripting but managed to hodgepodge this to work but has and adverse affect on the rest of the pages images. Suggestion and samples to jsfiddle. Thanks in advance.
<div id="wrapper">
<div id="WEtextarea"> </div>
<div id="WEimage_view"></div>
</div>
CSS controls size and all aspects of div.
I tried all your menu items... And did not notice such a bug.
So, while your're here... I have a suggestion to reduce your long script made of a small chunk repeated 12 times.
I would define the maps as objects, like this:
var maps = [
{
buttonId: "WEyear18000",
text: "Files/Docs/y18000.txt",
image: "Files/Image/treesimages/PalaeoGlaciolMaps.jpg"
},
{
// other 11 objects using the same structure...
}
];
And I would just add a class to each items, in the HTML, like this:
<div id="WEyear18000" class="BaseDiv RBoth OEWELinkButton OESK_WELinkButton_Default OECenterAH clickHandlerClass" style="z-index:1">
Then, I would use a shorter function like this one:
$(document).ready(function() {
$(".clickHandlerClass").click(function(){
// Get the id of the clicked menu item
var thisId = $(this).attr("id");
// Find its related object
var mapIndex = -1;
for(i=0;i<maps.length;i++){
if( maps[i].buttonId == thisId ){
mapIndex = i;
}
}
if(mapIndex != -1){
// Use the object infos in the page elements.
$("#WEtextarea").load(maps[mapIndex].text);
$('#WEimage_view').html('<img src="'+maps[mapIndex].image+'" >');
$('#WEee244f5837 .PullZone').click();
wheelzoom(document.querySelectorAll('img'));
}else{
console.log("Undefined map or id error...");
}
});
});
The array of objects is way easier to maintain... And an additional button easier to add.
You can use another class name than "clickHandlerClass".
;)
The wheelzoom looked like the only possible source of error to me. So I looked for its source, and found:
Wheelzoom replaces an img's background-image with its src. Then the src is set to a transparent image.
So, on the first wheelzoom, you get src transeparent, and on the second, you get a transparent background-image as well.
You can fix this by calling wheelzoom only on your new image:
$(document).ready(function() {
$("#WEyear18000").click(function() {
$("#WEtextarea").load("Files/Docs/y18000.txt");
$('#WEimage_view').html('<img src="Files/Image/treesimages/PalaeoGlaciolMaps.jpg" >');
$('#WEee244f5837 .PullZone').click();
//wheelzoom(document.querySelectorAll('img'));
wheelzoom(document.querySelectorAll('#WEimage_view img'));
});
to fix your bug you need to replace:
wheelzoom(document.querySelectorAll('img'));
with:
wheelzoom(document.querySelectorAll('#WEimage_view img'))
So only the images in the #WEimage_view will be affected by wheelzoom

How to display returned html page in a div using javascript and/or html

I want to build a url, send the url and display the returned html page in a div or any block element on the same page.
Ultimately, what I want to do is send a request as soon as the user enters a name, create a div to display the response,
fill the div with the response, hide the div then display a button or tab for the user to click to see the returned document.
But for now I'm just trying to figure out how to get the response into a div on the same page.
This seems like a fundamental HTML activity but I can't figure out how to direct the returned page to a div instead of having it replace the original page.
I would prefer to do this with plain HTML5 and javascript, not JQuery, but if JQuery is the only way I'll tackle that learning curve.
<html>
<body onload="buildPage()">
<div id="documents"></div>
</body>
<script>
function buildPage() {
var name="somename" ; // this will eventually come from user input and be passed in
var documentName = name + ".html";
var url ="http://localhost:8080/docserver/getpage?name=" + documentName;
// create a div to display the requested document
var newDiv = document.createElement("div");
newDiv.id = documentName;
newDiv.style.visibility = "hidden";
// ... probably need to do something here to direct the url response into the new div
// nest the newDiv in the existing div
document.getElementById("documents").appendChild(newDiv) ;
//TBD create a button to display the returned document
}
</script>
</html>
It sounds like you want to make an ajax request, which returns html, then render that html in a div?
I would also recommend using jQuery if you are not. It will make your life a lot easier.
Your file(s) will need to look something like this:
HTML
....
<div id="mydiv"></div>
....
JQUERY
$( document ).ready(function() {
$.ajax({
'type': 'get',
'contentType': 'text/plain',
'url': 'path/to/your/script/',
'dataType': 'html',
'timeout': 50000
}).done(function (data) {
// success
$('#mydiv').html(data);
}).fail(function (error) {
// something went wrong
console.log(error);
});
});
For the sake of simplicity, Let's say your html that is returned is:
HTML
<p>Hello World!</p>
Your page (after the ajax request runs) will look like this:
HTML
....
<div id="mydiv"><p>Hello World!</p></div>
....
This should get you rolling.
To expand on my comment, this code will pretty much do it for you
$.ajax({
url: "mypage.html",
cache: false
})
.done(function( html ) {
$( "#results" ).append( html );
});
With really good supporting documentation found here http://api.jquery.com/jquery.ajax/
Thanks to all that answered my query. Especially jonny who did some impressive hand holding. I really don't understand JQuery so I wanted a pure html/js solution. Here is what I ended up doing.
function buildPage() {
var name="somename" ; // this will eventually come from user input and be passed in
var documentName = name + ".html";
var url="http://localhost:8080/FDS/documents?filename=" + documentName ;
// create a div to display the requested document
var newDiv = document.createElement("div");
newDiv.id = documentName;
//newDiv.style.visibility = "hidden";
// create an iframe to place in the div
var newIframe = document.createElement("iframe") ;
newIframe.src = url ;
// nest the iframe in the div just created
newDiv.appendChild(newIframe) ;
// nest the newDiv in the existing div
document.getElementById("documents").appendChild(newDiv) ;
The missing component was an iframe. I thought I saw JQuery using iframes in the tabs widget but I did not pursue that avenue until it looked like I was going to get only JQuery based replies.

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 can i access a css attribute from a .load()'ed page?

I want to load an entire website in to my website. I have been able to do this with $(#preview).load("index.php") into my <div id="preview"></div>. What i have troubles accessing here is the background image which is a property of body. I tried making a div tag with a background-image attribute but when i removed the image from my body tag it didnt behave like i wanted to (was not filling the entire space).
My question is this. How can i access something from index.php that can let me either preview the site correctly or copy the attribute from somewhere into the preview background-image attribute?
my code now looks like this, after some extensive try-and-error (more like error-and-error and its getting more and more messy)
$(document).ready(
function() {
$("#check").click(
function() {
var bgd;
$("#preview").load("index.php",
function () {
bgd = $("#bg").css("background-image");
}
);
$("#preview").style.backgroundImage(bgd);
}
);
}
);
Where bg is the id of the div which works as a "substitute" body tag in index.php (aka with the same attributes as body)
Im either far from it, or ridiculously close. Thanks for every piece of advice i can get.
$(document).ready(
function() {
$("#check").click(
function() {
$.ajax({
url: 'index.php',
success: function(data){
data = $('data').html();
$('#preview').html(data);
bg = $('data').find('#bg').css('background-image');
$('#preview').css('background-image',bg);
}
});
}
);
}
);
Two problems here. One with how you're accessing style properties and the other has to do with the asynchronous behavior of load().
Style problem
You'll need to use $("#preview").css('background-image',bgd). The first method you were using could still be kept around by accessing the non-jQuery wrapped element, like so:
$("#preview")[0].style.backgroundImage(bgd);
Async problem
The second issue is that .load() is an asynchronous call that returns immediately. The next line of code gets executed and bdg is (most likely) still undefined. Then when load() completes, the success handler gets executed and bdg gets set to the background of the loaded page, but it's too late!
Moving the $("#preview").css('background-image',bgd) into the success handler will rectify that problem:
$(document).ready(
function() {
$("#check").click(
function() {
var bgd;
$("#preview").load("index.php",
function () {
bgd = $("#bg").css("background-image");
$("#preview").css('background-image',bgd);
}
);
}
);
}
);

AJAX - load all div elements

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);
});
});
});

Categories

Resources