Fancybox, getting Fancybox to bind using LIVE() to items being loaded onto the page after load - binding

I have a page that loads and after it loads, it pulls in a list of LIs to populate a news feed.
<li>quick view</li>
<li>quick view</li>
<li>quick view</li>
I'm trying to get fancy box to trigger when a user clicks on quick view but haven't had any luck. Any Ideas?
$(document).ready(function() {
$('.quickview').fancybox();
});
also tried:
$(document).ready(function() {
$('a.quickview').live('click', function() {
$(this).fancybox();
});
});
http://fancybox.net/
Thanks for any ideas...

Old question, but might be useful for future searchers.
My preferred solution is to fire fancybox manually from within the live event, eg:
$('.lightbox').live('click', function() {
$this = $(this);
$.fancybox({
height: '100%',
href: $this.attr('href'),
type: 'iframe',
width: '100%'
});
return false;
});
EDIT: From jQuery 1.7 live() is deprecated and on() should be used instead. See http://api.jquery.com/live/ for more info.

this should work after every ajax request
$(document).ajaxStop(function() {
$("#whatever").fancybox();
});

The problems is to attach fancybox into AJAX loaded element, right?
I got same problems and I found this solution.
I copy paste it here, see the original bug report for more info:
$.fn.fancybox = function(options) {
$(this)
.die('click.fb')
.live('click.fb', function(e) {
$(this).data('fancybox', $.extend({}, options, ($.metadata ? $(this).metadata() : {})))
e.preventDefault();
[...]
Credit goes to jeff.gran.

Since .on is now recommended over .live, and after reading over the documentation on delegated events, here's a solution I came up with (assuming your elements have a class of 'trigger-modal'):
$(document).on('click', '.trigger-modal', function() {
// remove the class to ensure this will only run once
$(this).removeClass('trigger-modal');
// now attach fancybox and click to open it
$(this).fancybox().click();
// prevent default action
return false;
});

From my understanding of Fancybox, the call to fancybox() simple attaches the plugin to the selected element. Calling fancybox on a click event won't open anything.
I think you just need to add
$(li_element_that_you_create).fancybox();
to the code that creates the new LI elements in your list
EDIT
If you're using load, then you would do something like:
$('#ul_id_goes_here').load('source/of/news.feed', function() {
$('.quickview').fancybox();
});

Related

Making offline.js work with turbolinks

I am using offline.js with turbolinks and on initial page load it works fine. But if I click another links then this wont work until I refresh the page. I can see the Offline.state is down but still the view is not showing. Is there any way to manually trigger the popup window?
Update
Other than the offline.js file the only js I have is this
var
$online = $('.online'),
$offline = $('.offline');
Offline.on('confirmed-down', function () {
$online.fadeOut(function () {
$offline.fadeIn();
});
});
Offline.on('confirmed-up', function () {
$offline.fadeOut(function () {
$online.fadeIn();
});
});
This is an old question, but I ran into the same problem, maybe it can help someone.
offline.js creating these dom elements on page load inside the body HTML
<div class="offline-ui offline-ui-up">
<div class="offline-ui-content"></div>
</div>
The reason why offline.js not working after page change is that on-page change the body HTML replaced with the new content returned by the server and the code above removed.
This is how Turbolinks works, so page load will be not triggered and the offline.js dom elements will be not created.
One solution will be to warp the offline.js inside a function and call it on every page change, but it will cause eventually memory leak (as "offline" and "online" event listener will be added to 'window' on each change)
Other solution will be to save the 'offline-ui' HTML before the new page loaded and bring it back after load:
# will fire before page change and save offline.js UI
document.addEventListener("turbolinks:before-render", function() {
if (!document.offlineHtml) {
document.offlineHtml = $('.offline-ui');
}
});
# will fire afterload and will check if there is a UI to append to the body
document.addEventListener("turbolinks:load", function() {
if (document.offlineHtml) {
$(document.body).append(document.offlineHtml);
}
});
At the moment this is the best way that I could find to fix that.
This could be a turbolinks issue. In app/assets/javascripts/application.js, wrap your javascript code within:
$(document).on('turbolinks:load', function() {
// your code
});

jQuery mobile listview multiple click event

I fill list dynamically, and after that on click I have multiple calls of event. 1st time it is repeated 1 time, 2nd time 2 times, 3rd time 3 times, etc...
First, more about this problem can be found in my other answer: jQuery Mobile: document ready vs page events
Prevent multiple event binding/triggering
Because of interesting jQM loading architecture, multiple event triggering is a constant problem. For example, take a look at this code snipet:
$(document).on('pagebeforeshow','#index' ,function(e,data){
$(document).on('click', '#test-button',function(e) {
alert('Button click');
});
});
Working jsFiddle example: http://jsfiddle.net/Gajotres/CCfL4/
Each time you visit page #index click event will is going to be bound to button #test-button. There are few ways to prevent this problem:
Solution 1:
Remove event before you bind it:
$('#index').live('pagebeforeshow',function(e,data){
$('#test-button').die().live('click', function(e) {
alert('Button click');
});
});
Working jsFiddle example: http://jsfiddle.net/Gajotres/K8YmG/
In case you have different events bound to an object:
$('#index').live('pagebeforeshow',function(e,data){
$('#test-button').die('click').live('click', function(e) {
alert('Button click');
});
});
Solution 2:
Use a jQuery Filter selector, like this:
$('#carousel div:Event(!click)').each(function(){
//If click is not bind to #carousel div do something
});
Because event filter is not a part of official jQuery framework it can be found here: http://www.codenothing.com/archives/2009/event-filter/
In a nutshell, if speed is your main concern then Solution 2 is much better then Solution 1.
Solution 3:
A new one, probably an easiest of them all.
$(document).on('pagebeforeshow', '#index', function(){
$(document).on('click', '#test-button',function(e) {
if(e.handled !== true) // This will prevent event triggering more then once
{
alert('Clicked');
e.handled = true;
}
});
});
Working jsFiddle example: http://jsfiddle.net/Gajotres/Yerv9/
Tnx to the sholsinger for this solution: http://sholsinger.com/archive/2011/08/prevent-jquery-live-handlers-from-firing-multiple-times/
More info
If you want to find more about this problem take a look at this article, working examples are included.

Jquery mobile How to tap the screen to no avail

I tested on the Apple device, and when I click on the screen when there is no effect. This is my code. Click on the events of this writing there are questions?
<script>
$(function() {
$('#test').tap(function() {
$('#menuNum').text('1');
})
})
</script>
You need to change few things.
Do not use $(function() { or classic document ready to check for a correct state, they can cause problems with jQuery Mobile. Instead use jQuery Mobile alternative called page events.
Then don't bind tap event like that, use proper modern way of doing that. In your case element must be loaded into the DOM for that kind of binding to work. And because of $(function() { sometimes it can happen that element is still loading when binding is executed. So use it like this:
$(document).on('tap','#test',function() {
$('#menuNum').text('1');
});
This method don't care if element exist or not, it will even work if element is loaded into the DOM after binding process.
Working example: http://jsfiddle.net/Gajotres/SQ7DF/
In the end you want something like this:
$(document).on('pagebeforeshow', '#index', function(){
$(document).on('tap','#test',function() {
alert('Tap');
});
});

Bind jQuery UI autocomplete using .live()

I've searched everywhere, but I can't seem to find any help...
I have some textboxes that are created dynamically via JS, so I need to bind all of their classes to an autocomplete. As a result, I need to use the new .live() option.
As an example, to bind all items with a class of .foo now and future created:
$('.foo').live('click', function(){
alert('clicked');
});
It takes (and behaves) the same as .bind(). However, I want to bind an autocomplete...
This doesn't work:
$('.foo').live('autocomplete', function(event, ui){
source: 'url.php' // (surpressed other arguments)
});
How can I use .live() to bind autocomplete?
UPDATE
Figured it out with Framer:
$(function(){
$('.search').live('keyup.autocomplete', function(){
$(this).autocomplete({
source : 'url.php'
});
});
});
jQuery UI autocomplete function automatically adds the class "ui-autocomplete-input" to the element. I'd recommend live binding the element on focus without the "ui-autocomplete-input"
class to prevent re-binding on every keydown event within that element.
$(".foo:not(.ui-autocomplete-input)").live("focus", function (event) {
$(this).autocomplete(options);
});
Edit
My answer is now out of date since jQuery 1.7, see Nathan Strutz's comment for use with the new .on() syntax.
If you are using the jquery.ui.autocomplete.js try this instead
.bind("keydown.autocomplete") or .live("keydown.autocomplete")
if not, use the jquery.ui.autocomplete.js and see if it'll work
If that doesn't apply, I don't know how to help you bro
Just to add, you can use the .livequery plugin for this:
$('.foo').livequery(function() {
// This will fire for each matched element.
// It will also fire for any new elements added to the DOM.
$(this).autocomplete(options);
});
To get autocomplete working when loaded dynamically for the on() event used in jQuery > 1.7, using the syntax Nathan Strutz provides in his comment:
$(document).on('focus', '.my-field:not(.ui-autocomplete-input)', function (e) {
$(this).autocomplete(options)
});
where .my-field is a selector for your autocomplete input element.
.live() does not work with focus.
also keyup.autocmplete does not make any sense.
Instead the thing I have tried and working is this
$(document).ready(function(){
$('.search').live('keyup' , function()
{
$(this).autocomplete({ source : 'url.php' });
});
})
This works perfectly fine.
You can't. .live() only supports actual JavaScript events, not any custom event. This is a fundamental limitation of how .live() works.
You can try using this:
$('.foo').live('focus.autocomplete', function() {
$(this).autocomplete({...});
});
After reading and testing everyone else's answers I have updated it for the current version of JQuery and made a few tweaks.
The problem with using keydown as the event that calls .autocomplete() is that it fails to autocomplete for that first letter typed. Using focus is the better choice.
Another thing I have noticed is that all of the given solutions result in .autocomplete() being called multiple times. If you are adding an element dynamically to the page that will not be removed again, the event should only be fired once. Even if the item is to be removed and added again, the event should be removed and then added back each time the element is removed or added so that focusing on the field again will not unnecessarily call .autocomplete() every time.
My final code is as follows:
$(document).on('focus.autocomplete', '#myAutocomplete', function(e){
$(this).autocomplete(autocompleteOptions);
$(document).off('focus.autocomplete', '#myAutocomplete');
});
autocomplete is not an event rather a function that enables autocomplete functionality for a textbox.
So if you can modify the js that creates the textboxes dynamically to wrap the textbox element in as a jquery object and call autocomplete on that object.
I just noticed you edited your post with this answer. It was obvious to me so I'm posting it below for others. Thank you.
$(function()
{
$('.search').live('keyup.autocomplete', function()
{
$(this).autocomplete({ source : 'url.php' });
});
});
This works for me:
$(function()
{
$('.item_product').live('focus.autocomplete', function()
{
$(this).autocomplete("/source.php/", {
width: 550,
matchContains: true,
mustMatch: false,
selectFirst: false,
});
});
});
You can just put the autocomplete inside input live event, like this:
$('#input-element').live('input', function(){
$("#input-element").autocomplete(options);
});

How to completely remove a dialog on close

When an ajax operation fails, I create a new div with the errors and then show it as a dialog. When the dialog is closed I would like to completely destroy and remove the div again. How can I do this? My code looks something like this at the moment:
$('<div>We failed</div>')
.dialog(
{
title: 'Error',
close: function(event, ui)
{
$(this).destroy().remove();
}
});
When I run this the dialog box shows up correctly, but when I close it the dialog is still visible in the html (using FireBug). What am I missing here? Something I have forgotten?
Update: Just noticed my code gives me an error in the firebug console.
$(this).destroy is not a function
Anyone able to help me out?
Update: If I do just $(this).remove() instead, the item is removed from the html. But is it completely removed from the DOM? Or do I somehow need to call that destroy function first as well?
$(this).dialog('destroy').remove()
This will destroy the dialog and then remove the div that was "hosting" the dialog completely from the DOM
Why do you want to remove it?
If it is to prevent multiple instances being created, then just use the following approach...
$('#myDialog')
.dialog(
{
title: 'Error',
close: function(event, ui)
{
$(this).dialog('close');
}
});
And when the error occurs, you would do...
$('#myDialog').html("Ooops.");
$('#myDialog').dialog('open');
$(dialogElement).empty();
$(dialogElement).remove();
this fixes it for real
This is worked for me
$('<div>We failed</div>')
.dialog(
{
title: 'Error',
close: function(event, ui)
{
$(this).dialog("close");
$(this).remove();
}
});
Cheers!
PS: I had a somewhat similar problem and the above approach solved it.
An ugly solution that works like a charm for me:
$("#mydialog").dialog(
open: function(){
$('div.ui-widget-overlay').hide();
$("div.ui-dialog").not(':first').remove();
}
});
You can do use
$(dialogElement).empty();
$(dialogElement).remove();
I use this function in all my js projects
You call it:
hideAndResetModals("#IdModalDialog")
You define if:
function hideAndResetModals(modalID)
{
$(modalID).modal('hide');
clearValidation(modalID); //You implement it if you need it. If not, you can remote this line
$(modalID).on('hidden.bs.modal', function ()
{
$(modalID).find('form').trigger('reset');
});
}

Resources