jQuery load events - php

I have a page with dynamic content from PHP and I want to use jQuery's load function to periodically refresh the div container which contains the dynamic content so that new content is displayed on top of the old content.
I using a jQuery function as follows:
setInterval(function() {
$("#ContentWrapper").load("Livefeed.php #ContentWrapper");
}, 10000);
to refresh the content container's wrapper every 10 seconds
My problem is that after the load function is executed. Click events and hover events do no properly work on the page. Initially they did not fire at all so I used Jquery live function on all click and hover events within the content wrapper and it solved the problem.
However, when the page reloads the hovers reload as well and all hidden divs with are made visible by jQuery's .show method hide. Is there any way to prevent the hover from reloading and also for the visible hidden divs to remain visible every time the .load function is called.
I'm using click and hover functions like so:
$('selector').live("click",function(){
});
and
$('selector').live("hover",function(){
});
Any help is appreciated.

Using jQuery.live is deprecated now. So don't use it. Use jQuery.on from now on. Also, .hover event is being taken down. You should use separate mouseenter and mouseleave events.
You can fix this issue by replacing .live with:
/*
If click happens inside contentwrapper, check if click target was yourSelector, if true execute this function
*/
$("#ContentWrapper").on("click", "#yourSelector", function(){
//do whatever u wanna do on click
});
To keep track of all divs that were hidden and all those weren't you need to set unique id for each div. And before you reload with .load() you loop through all divs and save their current state (hidden or visible) in an Object Array in [{ id : state },..] format. Once ajax request finishes, loop through Object array via $.map and set states for each div

You can use JQuery delegate,its primary intention is dynamically driven content:
http://api.jquery.com/delegate/
$("#Parent").delegate("selector","click", function() { });

Related

jQuery click functions in included files not firing

This question is kind of a duplicate, but the answer provided doesn't actually solve the issue. Here's the related question:
Why jQuery click doesn't work when included in a separate file
I've got a php template that has an overlay div I am dynamically populating with different content, depending upon which link is clicked. So for example, I have this in my template:
<a class="icon-search" href="#"></a>
<div id="overlay" class="hidden"></div>
In my global.js file, I have these functions:
$(document).ready(function(){
$("a.icon-search").click(function () {
$("#overlay").load("inc/search.php");
$("#overlay").toggleClass('show hidden');
});
$("#cancel").click(function() {
$("#overlay").toggleClass('show hidden');
});
});
The cancel button is in "inc/search.php"
When you click "icon-search", the overlay toggles properly, and the content of search.php gets loaded, but pressing the cancel button doesn't work, unless I move that function into the search.php file. I really hate doing this, because it makes the html really messy, and it makes reusing things difficult. Is there any way to overcome this issue, so that functions will work on elements that are included?
You need to use event delegation in order to have generated content fire events.
Lookup the .on() method in the jQuery documentation (http://api.jquery.com/on/)
Try this instead:
$(document).ready(function(){
$("a.icon-search").click(function () {
$("#overlay").load("inc/search.php");
$("#overlay").toggleClass('show hidden');
});
$(document).on('click','#cancel',function() {
$("#overlay").toggleClass('show hidden');
});
});
Using .on() will delegate click events on the document to the elements with the specified selector and this will work for all current elements (which are in the DOM when this code runs) and future elements (like those which are appended using AJAX, like when you use the .load() method).
The event handlers like you are using (which I call static event handlers), must be attached directly to the DOM object they are handling events for. That means that when you run the code to attach the event handler, the DOM object you want to attach to must already exist.
If you are running this code on .ready(), but your dynamically loaded content has not yet been loaded, then no event handler will be attached because there's no DOM object yet to attach it to.
There are two general approaches to solving this type of issue:
Run the code AFTER you've loaded the dynamic content (this is what putting the script into your dynamically loaded PHP content does).
Switch to using delegated event handling. In delegated event handling, you attach an event handler to a parent of the dynamic content that is itself not dynamically loaded and thus it already exists. Then, when a click happens on the dynamic content, that click will "bubble" up through it's parents and encounter the click handler you have. jQuery automates a lot of this for you when using the delegated form of .on() which is of this form $("#staticParent").on("click", "#dynamicChild", fn). You can read the details about using the delegated for of .on() in these references:
Does jQuery.on() work for elements that are added after the event handler is created?
jQuery .live() vs .on() method for adding a click event after loading dynamic html
jQuery .on does not work but .live does

Loading pages into a div with JQuery, existing Javascript not working

I have a page I'm working on where a user clicks a link and it loads a new php file into an existing div. It works but the page that loads into the div will not function with existing Javascript stuff in the page.
I can include the
<script type="text/javascript" src="js/admin.js"></script>
into the loaded pages but when you flick back and forth between the pages I notice that RAM usage starts to go up and up, so I don't think this is the best way of doing it.
Any ideas how the loaded page can function with the already-loaded javascript from the index page?
Thanks!
bind your events like this :
$(document).on({
"event" : function(e) {},
...
}, "selector");
If you are using bind or click type events change to using something like on (or live or delegate if you are required to use jquery version less than 1.9)
OR/AND
In your function that loads in the page via ajax provide a call back that initiates only what is needed. Example:
$('#myDiv').load('ajax/page.php', function(){
$('#myDiv a').customPlugin('whatever');
$('#myDiv button').bind('click', function(){
window.open('http://www.google.com/', 'some-window');
});
});

Load html with ajax, but hide content until loaded

I'm using jQuery to load content dynamically when the user clicks a link. The content is just a bunch of images that are then set to display in a slideshow of sorts. My problem is, I can't seem to figure out a way to show the loaded content only AFTER the images have fully loaded. I've tried several different solutions and all of them seem to either break the script or just not work the way I want. Here's the code I'm using now:
$(document).ready(function() {
$("a#item").click( function() {
var projectName = $(this).attr('class');
$("div.slideshow").css("display", "block");
$("div.slideshow").load(projectName+".php", function() {
var slideshow = new Array();
$("div.slideshow img").each(function() {
slideshow.push($(this));
});
startSlideshow(slideshow.shift());
function startSlideshow(image) {
image.delay(400).fadeIn(150, function() {
if(slideshow.length > 0) {startSlideshow(slideshow.shift());}
else { $("div.slideshow").delay(400).fadeOut(200, function() {$("div.slideshow img").css("display", "none")}); }
});
}
});
return false;
});
});
You can also see the full demo site here: http://publicprofileproject.com/
Any input would be greatly appreciated!
You could create an array of image objects in your JavaScript, loading each image into an element of the array. Attach an event handler to the onLoad event of the images.
In the event handler, increment a count of loaded images. When your counter reaches the length of your array, the browser will have all of the images. This is the point at which you can show your slideshow.
If you do this in your page load, it will have the added advantage of pre-loading the images ready for when the user clicks your link.
I believe this question has already been answered here.
The general idea is that you specify a load event handler to display it prior to specifying the source attribute.
Alternatively, if your projects+".php" file is specifying the images in ready-made, html mark-up, then you should be able to capture the load event of the images in the file you are loading. Add the following pseudocode into your file that is being loaded.
$("img").load(function() {
// show the div on the page it is getting loaded into
alert("images should be loaded now");
});
You might be able to place it in your original code segment and potentially bind it using the live / on binding events. ex: $("img").on("load", function() {...
From the load documentation:
The load event is sent to an element when it and all sub-elements have been completely loaded. This event can be sent to any element associated with a URL: images, scripts, frames, iframes, and the window object.
Edit: Interesting discouragement for doing what it looks like you're doing:
Caveats of the load event when used with images
A common challenge developers attempt to solve using the .load() shortcut is to execute a function when an image (or collection of images) have completely loaded. There are several known caveats with this that should be noted. These are:
It doesn't work consistently nor reliably cross-browser
It doesn't fire correctly in WebKit if the image src is set to the same src as before
It doesn't correctly bubble up the DOM tree
Can cease to fire for images that already live in the browser's cache

jquery ui lost after jQuery load

I have a problem with jQuery being lost after .load() function.
I have a element built up with jQuery UI. The problem is that when I load it from separate page like this:
$("#mydiv").load("getgroup.php?group=" + selectedGroup).html();
The getgroup.php generates something like this, depending on the GET parameter:
<select>
<option>something</option>
<option>something</option>
</select>
When loading it with load() (or post, ajax, get) the element returns unformatted... I have tried including jquery and jquery-ui plugin also in the getgroup.php file but with no luck...
Thank you
The problem is, your jquery code isn't executed automatically on dynamically loaded elements.
What you should do is, put all your jquery ui code in a function. For instance, let's say you want to call the button() jQuery UI function on the newly loaded submit elements:
function launchUiWidgets(target) {
$(target).find('input:submit').button();
}
Then, you use this function as a success callback when you load new elements - giving it target as an argument to avoid rerunning the code on all of your DOM. Let's suppose you're loading the data in a div of id "container":
$.get(
"whatever.html?name=val",
function(data){
$('#container').html(data);
launchUiWidgets('#container');
},
"html");
If my understanding is correct and the element is being inserted, but with no CSS, you may need to run .addClass after the element is loaded to apply your chosen CSS class once the element is present. However, if in your CSS you have default values for the element type predefined, e.g. select{color:#000000;width:... these should also be loaded automatically.
Per the comment below- if you are looking at your predefined handlers still being relevant for content injected by AJAX/load() calls, you can use the .live() method:
http://api.jquery.com/live/

How to initiate javascript in jQuery ajax-loaded content in IE8

I'm facing a trouble with jquery ajax under IE8. I have a form which at the base level displays a list of few items, each with buttons to edit and remove. The list, along with those two buttons, is loaded via jquery ajax call. Although it works fine on Firefox and Chrome, on IE8 it won't trigger functions behind edit or remove buttons.
So basically, on a base page, jquery works and loads the list. Within that list tho, jQuery doesn't work as it won't trigger edit or remove functions
I have a similar problem with the modal window call. IE8 is able to open the modal window (content is loaded with jquery ajax) but won't trigger any function within the content of the modal
Example of a simple call
$('#form-modal').load('/form/' + path + '?id=' + id).modal();
This works on IE8 from the base page, but doesn't when triggered within ajax-loaded content
All js scripts definitions are being loaded in the <head> of the main base page. I tried adding definition to the ajax-loaded file header, but didn't help so it must be something else
Any ideas? If you need more details, will gladly provide
Let me show you the easiest example. Each item on the list loaded with ajax has a 'remove' button.
Remove
DeleteItem definition is in external lib.js file
function deleteItem(id){
$.ajax({
type: "POST",
url: "/ajax/deleteitem.php",
data: "id=" + id,
success: function(msg){
loadItemsList();
}
});
}
This is it... That simply doesn't work on IE8... Nothing happens, not even javascript error. Same thing works no problem on Firefox and Chrome
It would be nice if you show the event handlers for those buttons, since if you're using bind(); for example, it loads when the dom is ready, and your ajax call is made. That means that the dom elements loaded through the ajax call wasn't there when bind was called to bind the buttons.
The solution to this is to use live();
$(".button").live("click", function () {
// do stuff
});
I don't know what event binder you're using, but if you're using anything other than live, you could try live and it should work.
EDIT
Read my comment first on the alert(id), if your function doesn't run at all in IE8, try doing this instead. Give the link element the id instead like this
<a id="item_10" href="#">Remove</a>
Then somewhere in your javascript
$("document").ready( function () {
$("a").live("click", deleteItem);
});
function deleteItem (event) {
event.preventDefault();
var id;
id = $(this).attr("id").replace("item_", "");
//this will now provide you with the current id
console.log(id);
your ajax-stuff here..
}
This should work in IE8, no problem. You might wanna specify the selector though for the click event by giving all the delete links some class or something.

Categories