jQuery Live -- fire when item added to page - asp.net-mvc-2

I've got an Ajax update happening to my MVC view. It displays a message telling the user the operation has completed:
<% if (ViewData["colorOptionsMessage"] != null) { %>
<span class="ajaxMessage"><%= ViewData["colorOptionsMessage"] %></span>
<% } %>
I want to atuomatically fade this message out once it appears, and I'd like to do it once, and have it work site-wide. This is what I tried, which doesn't work (the message appears, but the alert does not show):
$(function () {
$(".ajaxMessage").live("load", function () {
alert("once I can get this to show I'll put in a jueryUI fadeOut"); });
});
EDIT
Just to be clear, I don't need help with the fade out code; I just need help getting this call to Live() to wire up properly.

There's no direct way to be informed automatically when new elements are added to the page. $('.ajaxMessage').live('load') would only happen when the load event fires on an image, iframe or object/embed/applet with class="ajaxMessage", a load event is not fired with its own target for every new element that enters the page.
You could only do this by (a) DOM Mutation Events, which generally aren't widely enough supported, or (b) constantly polling to fetch the .ajaxMessage selector and seeing if any new elements appear in the results.
Better to manually $('.ajaxMessage', function() {...}) immediately after (potentially) adding the content to the page, in the ajax() method's success handler.
ETA:
that jQuery handler doesn't seem to execute after an ajaxForm success
If you can't catch success directly you could try registering a global success handler using ajaxSuccess.

The code below expects you made the Ajax call through jQuery. if the ajax call was not through jQuery, then ignore this answer. Could we see the ajax call itself?
<Script type="text/javascript">
$(function () {
// this is a jQuery global ajax event that fires for every ajax, you need to check the URL
$.ajaxSuccess(function(e, xhr, settings){
if (settings.url == 'URI/ for/ajax /message/load.') {
alert("once I can get this to show I'll put in a jueryUI fadeOut");
}
});
);
</script>

When i want to add something, wait a few, and hide it, I use setTimeout function instead of live events. I add the code on the success callback.
This is a 1 second wait:
setTimeout(function(){ $("ajaxMessage").fadeOut(); }, 1000)
Of course, if you dont want to wait, just fadeOut the element in the success callback.
Can this be enough for you?

I dont think you can bind load to span.
only to IMG IFRAME BODY

As I know "ready" and "load" events are not supported by jQuery in "live". So you can use plugins as this one http://startbigthinksmall.wordpress.com/2011/04/20/announcing-jquery-live-ready-1-0-release/
Here is the demo http://cdn.bitbucket.org/larscorneliussen/jquery.liveready/downloads/demo.html

Related

jQuery .live()-functionality for other jQuery methods such as .text()

I have the problem that my jQuery stuff isn't working after a div which includes elements being manipulated by my jQuery code are reloaded by ajax. The jQuery .live function helped me out that at least all my events are triggered. However functions like .text() are still not working. E.g.
$('#idOfElementBeingInDivWhichIsReloadedByAjax').text('New text');
Has anybody suggestions how to cope with this issue?
Edit: The problem is that the web site I'm working on loads its page content with ajax when clicking on a navigation item. All the jQuery functionality works when the sites are visited for the first time. However at the second time the DOM is reloaded and jQuery still uses the original DOM, so methods like .text() don't show changes any more. As mentioned above the .live() method helped me that at least events are still triggered after the second call of a specific page.
The only way to do this, is to make sure that your code is executed after the ajax reload. A common approach is to create a init() function, which are called from the ajax callback function.
$(function(){
$('#myParentAjaxDiv').load('somepage.html', function(){
initStuff();
});
});
function initStuff(){
$('#idOfElementBeingInDivWhichIsReloadedByAjax').text('New text');
}

How do I disable a submit button and show a loading image while an jquery ajax call is running?

The following code is NOT working. The button is not disabled, the loading image does not display, and instead the whole page locks up during the AJAX call.
JavaScript:
$(function() {
$("#submitButton").click(function() {
// Disable the submit button
$(this).attr("disabled", "disabled");
// Show the loading image
$(".loading").show();
// Serialize the form values for AJAX submission
var $formParamsString = $(this).closest("form").serialize();
$.ajax({
type: "POST",
url: "myService.cfm",
dataType: "JSON",
data: $formParamsString,
async: false,
success: function(data) {
alert("Form values saved!")
},
error: function() {
alert("Form values not saved!")
}
});
// Hide the loading image
$(".loading").hide();
// Re-enabled the submit button
$(this).removeAttr("disabled");
// Prevent form post
return false;
});
});
HTML:
<input
id="submitButton"
name="submitButton"
type="submit"
value="Submit"
class="submitButton" />
<span class="loading"></span>
CSS:
.loading {
background: url("/images/loading.gif");
}
Browser is freezing and nothing happens because you're issuing synchronous request (async: false), see docs:
Note that synchronous requests may temporarily lock the browser,
disabling any actions while the request is active
To achieve your goal, you need to:
make you request asynchronous (remove async: false),
move this code:
// Hide the loading image
$(".loading").hide();
// Re-enabled the submit button
$(this).removeAttr("disabled");
to your success and error functions,
sumbit form manually in success function ($('#form').submit()).
So basically what you are doing is
1) disabling your button and showing the image
2) firing off an asynchronous event
3) immediately enabling your button once more and hiding the image
The ajax call that you are making will not hang the function that you are calling it from. The function is called on a separate thread and therefore the image is being disabled/enabled so quickly that you can't even tell. What you need to do is attach functions to the ajax events that jQuery exposes.
You can attach an event to the initial ajax call event that will disable the button and show the loading image, and then attach an event to the call complete part that will re-enable your button and get rid of the image.
The two options that you have to do this are
1) Have the button and image manipulating effects reside in the .success and .fail events that are attached to your single ajax call
2) Attach functions to the .ajaxStart and .ajaxComplete events that are exposed on the page. Doing this will make the same thing happen for all ajax calls on the page however. More info can be found here: http://api.jquery.com/category/ajax/
One problem is the AJAX call isn't finished when you hide the loading image and remove the disabled attribute, because by definition AJAX calls are (A)synchronous. You should do the hide and remove attribute in your callback functions.

google wave: how did they make divs clickable

As we are facing GWT performance issues in a mobile app I peeked into Google Wave code since it is developed with GWT.
I thought that all the buttons there are widgets but if you look into generated HTML with firebug you see no onclick attribute set on clickable divs. I wonder how they achieve it having an element that issues click or mousedown events and seemingly neither being a widget nor injected with onclick attribute.
Being able to create such components would surely take me one step further to optimizing performance.
Thanks.
ps: wasnt google going to open source client code too. Have not been able to find it.
You don't have to put an onclick attribute on the HTML to make it have an onclick handler. This is a very simple example:
<div id="mydiv">Regular old div</div>
Then in script:
document.getElementById('mydiv').onclick = function() {
alert('hello!');
}
They wouldn't set the onclick property directly, it would have been set in the GWT code or via another Javascript library.
The GWT documentation shows how to create handlers within a GWT Java app:
public void anonClickHandlerExample() {
Button b = new Button("Click Me");
b.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
// handle the click event
}
});
}
This will generate an HTML element and bind a click handler to it. However, in practice this has the same result as using document.getElementById('element').onclick() on an existing element in your page.
You can hook functions to the onclick event using JavaScript. Here's an example using jQuery:
$(document).ready(function(){
$("#div-id").click(function(){
/* Do something */
});
});
If you're interested in optimizing performance around this, you may need to investigate event delegation, depending on your situation.
A click event is generated for every DOM element within the Body. The event travels from the Body down to the element clicked (unless you are using Internet Explorer), hits the element clicked, and then bubbles back up. The event can be captured either through DOM element attributes, event handlers in the javascript, or attributes at any of the parent levels (the bubbling or capturing event triggers this).
I'd imagine they've just set it in a .js file.
Easily done with say jQuery with $(document).ready() for example.

tiny question about jquery's live()

How would I change the html of a tag like so:
$('#someId').html('<p>foo bar</p>');
while using the live() or delegate() function? Just for clarification I don't want this to happen on hover or focus or click... I just want jquery to immediately change the html inside of a certain tag.
Basically, I'm trying to change the logo in the Mojomotor's little dropdown panel and I don't want to change the logo every time I upgrade to a new version.
Any suggestions?
.live() and .delegate() don't work like this, what you're after is still done through the .livequery() plugin or simply in the document.ready if it's present on page load, like this:
$(function() {
$('#someId').html('<p>foo bar</p>');
});
Or with .livequery() if it's replaced dynamically in the page:
$('#someId').livequery(function() {
$(this).html('<p>foo bar</p>');
});
.live() and .delegate() work off of event bubbling...an element just appearing doesn't do this whereas a click or change, etc would.
Just do it when the DOM loads.
<script type="text/javascript">
$(document).ready(function() {
$('#someId').html('<p>foo bar</p>');
});
</script>

FBML elements rendering delay

I am using FBML for rendering certain elements on the page such as the name of the user, profil pic, etc. However when there are many FBML elements on page, there is a slight delay which occurs before they are rendered - that's fine since AJAX calls are made to the server to fetch the data by the JS FB library. However, I want to hide the container DIV holding these element till the elements have finished loading, so is there any way to specify a JS callback function which gets fired when the FBML data has finished loading?
Try FB.Event.subscribe
FB.Event.subscribe('xfbml.render', function(response) {
//xfbml.render is fired when a call to FB.XFBML.parse() completes
});
There is another option for this. First, make sure you have the xfbml=0 parameter set on all embeds. Next, you can use this small bit of jQuery:
window.fbAsyncInit = function(){
FB.XFBML.parse(null,function(){
// all FB embeds are rendered as of this point
});
};