I am trying to trigger the ready event after the user clicks on #mail-wrap which loads in another page with AJAX so that sss() can be refired. However, it's not refiring. What am I doing wrong?
jQuery(document).ready(function($) {
function sss() {
$(document).trigger('ready');
$('.slider').sss({
speed: 5000
});
}
// User event
$('#mail-wrap').on('click', function(e) {
e.preventDefault();
sss();
});
$('.slider').sss({
speed: 5000
});
});
Full relevant code (code is surrounded by document ready and the sss() function is outside of it):
(function($) {
var contactButton = $('#contact-button');
// Load the Contact page
function loadContact() {
$('#content').fadeOut(50, function() {
$('<span class="loading-icon page-loading-icon"></span>').insertBefore('#content');
}).load(site.url + '/contact/ #contact-keebs', function() {
$('.page-loading-icon').remove();
$(this).fadeIn(50);
$('body').addClass('contact');
$('#projects-list').removeClass('fadeInUp');
$('#contact-info, #clients').addClass('fadeInUp');
});
// Change the Contact button to 'Projects'
$(contactButton).removeClass('contact-button').addClass('project-button').attr('data-title', 'Projects').css('width', '71px').text('Projects').shuffleLetters();
myIcons.to('work');
// Change the title of the document
$('head').find('title').text('Contact | Keebs');
//Reinitialize SSS
sssInit();
}
// Load the Projects page
function loadProjects() {
$('#content').fadeOut(50, function() {
$('<span class="loading-icon page-loading-icon"></span>').insertBefore('#content');
}).load(site.url + '/ #primary', function() {
$('.page-loading-icon').remove();
$(this).fadeIn(50);
$('body').removeClass('contact');
$('#contact-info, #clients').removeClass('fadeInUp');
$('#projects-list').addClass('fadeInUp');
TweenLite.to("body.single #project-wrapper", 0.3, {height:0, force3D:true, ease:Power4.easeOut});
});
// Change the Projects button to 'Contact'
$(contactButton).removeClass('project-button').addClass('contact-button').attr('data-title', 'Get in touch').css('width', '96px').text('Get in touch').shuffleLetters();
myIcons.to('mail');
// Change the title of the document
$('head').find('title').text(site.title);
}
// User event
$('#mail-wrap').on('click', function(e) {
e.preventDefault();
// Prevent accidental double clicks
if (!$(this).data('isClicked')) {
var link = $(this);
if (!contactButton.hasClass('project-button')) {
var data1 = { contact_page: site.url + '/contact/ #contact-keebs' };
History.pushState(data1, 'Contact | Keebs', site.url + '/contact/');
loadContact();
} else {
var data2 = { home_page_contact: site.url + '/ #primary' };
History.pushState(data2, site.title, site.url + '/');
loadProjects();
}
link.data('isClicked', true);
setTimeout(function() {
link.removeData('isClicked');
}, 500);
}
});
})(jQuery);
It's not clear what your Ajax event does and if you are using sss() bound to the jQuery object defining your own function sss is confusing. Did you really mean to do something like this;
function sssInit() {
jQuery('.slider').sss({
speed: 5000
});
}
jQuery(document).ready(function($) {
sssInit();
// User event
$('#mail-wrap').on('click', function(e) {
e.preventDefault();
sssInit();
});
});
EDIT: You are using .load() so your sssInit call will need to go in the complete function parameter e.g;
$('#content').fadeOut(50, function() {
$('<span class="loading-icon page-loading-icon"> </span>').insertBefore('#content');
}).load(site.url + '/contact/ #contact-keebs', function() {
$('.page-loading-icon').remove();
$(this).fadeIn(50);
$('body').addClass('contact');
$('#projects-list').removeClass('fadeInUp');
$('#contact-info, #clients').addClass('fadeInUp');
sssInit();
});
ISSUE: The Super Simple Slider hooks up it's events using $(window).load(function() { ... }) adding elements to the DOM after load will not get the event handlers and prevents the slider working.
trying to trigger the ready event after the user clicks on #mail-wrap
which loads in another page with AJAX so that sss() can be refired.
However, it's not refiring. What am I doing wrong?
.ready() already called when $(document).trigger('ready'); called ?
Try utilizing $.holdReady()
// do stuff before `.ready()` event called
$.holdReady(true);
// User event
$('#mail-wrap').on('click', function(e) {
e.preventDefault();
sss();
// call `.ready()` event by setting `$.holdReady()` to `false`
$.holdReady(false);
});
function sss() {
jQuery('.slider').sss({
speed: 5000
});
}
jQuery(document).ready(sss);
e.g.,
$.holdReady(true);
// User event
$('#mail-wrap').on('click', function(e) {
e.preventDefault();
sss("$.holdReady(true) within `click` event", this);
$.holdReady(false);
});
function sss() {
console.log(arguments[1]); // `#mail-wrap` , `document`
$("body").append("<br>" + arguments[0] + " " + $.now())
}
jQuery(document).ready(function($) {
sss("$.holdReady(false) within $(document).ready()", this)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div id="mail-wrap">click</div>
Related
So I'm using some parts of gentelella and there is a file custom.js. I have some problems with this file because some parts works and other don't.
The problem is with this method:
$(document).ready(function() {
console.log("custom.js inside document ready");
$('.collapse-link').on('click', function() {
console.log("clicked on a collapse-link");
var $BOX_PANEL = $(this).closest('.x_panel'),
$ICON = $(this).find('i'),
$BOX_CONTENT = $BOX_PANEL.find('.x_content');
// fix for some div with hardcoded fix class
if ($BOX_PANEL.attr('style')) {
$BOX_CONTENT.slideToggle(200, function(){
$BOX_PANEL.removeAttr('style');
});
} else {
$BOX_CONTENT.slideToggle(200);
$BOX_PANEL.css('height', 'auto');
}
$ICON.toggleClass('fa-chevron-up fa-chevron-down');
});
$('.close-link').click(function () {
console.log("close-link clicked")
var $BOX_PANEL = $(this).closest('.x_panel');
$BOX_PANEL.remove();
});
});
It write "custom.js inside document ready" but when I click nothing happened.
And if I look into the HTML I have the same classes as in the JS:
it might be that on document ready these specific elements are not found.
In general a best practice is to delegate the events to the document, like this:
$(document).ready(function() {
console.log("custom.js inside document ready");
$(document).on('click', '.collapse-link' /* <--- notice this */, function() {
console.log("clicked on a collapse-link");
var $BOX_PANEL = $(this).closest('.x_panel'),
$ICON = $(this).find('i'),
$BOX_CONTENT = $BOX_PANEL.find('.x_content');
// fix for some div with hardcoded fix class
if ($BOX_PANEL.attr('style')) {
$BOX_CONTENT.slideToggle(200, function(){
$BOX_PANEL.removeAttr('style');
});
} else {
$BOX_CONTENT.slideToggle(200);
$BOX_PANEL.css('height', 'auto');
}
$ICON.toggleClass('fa-chevron-up fa-chevron-down');
});
$(document).on('click', '.close-link' /* <--- notice this */, function () {
console.log("close-link clicked")
var $BOX_PANEL = $(this).closest('.x_panel');
$BOX_PANEL.remove();
});
});
You have written the click event on the a tag. In general functional specific tags like submit button, a tag will do their default functionality on click. So as it is anchor it will check for href which is not there so the it is not redirecting to anywhere. We can supress the default behaviour of these kinds using e.preventDefault(). Here e is the event. So change your function to
$('.collapse-link').on('click', function(e) {
e.preventDefault();
console.log("clicked on a collapse-link");
var $BOX_PANEL = $(this).closest('.x_panel'),
$ICON = $(this).find('i'),
$BOX_CONTENT = $BOX_PANEL.find('.x_content');
// fix for some div with hardcoded fix class
if ($BOX_PANEL.attr('style')) {
$BOX_CONTENT.slideToggle(200, function(){
$BOX_PANEL.removeAttr('style');
});
} else {
$BOX_CONTENT.slideToggle(200);
$BOX_PANEL.css('height', 'auto');
}
$ICON.toggleClass('fa-chevron-up fa-chevron-down');
});
And
$('.close-link').on('click', function(e) {
e.preventDefault();
console.log("close-link clicked")
var $BOX_PANEL = $(this).closest('.x_panel');
$BOX_PANEL.remove();
});
Edit: I guess part of this is an issue of me being inexperienced with Drupal. I added a javascript file to site.info, so that it will be added to every page. This is all the file contains:
(function ($){
$("#ctl00_btnSearch001").on("click", function(){
var searchVal = $("#ctl00_txtSearch").val();
window.location.href = "http://www.mywebsite.org/search/?sa=Search&q=" + searchVal;
});
})(jQuery);
When the site loads, it gets compiled into this larger script, which looks like this in the debugger:
(function ($) {
Drupal.behaviors.titlebar = {
init: function(context, settings) {
// Using percentage font size to easily increase/decrease page font size
var baseFontSize = 100;
$('.pgc-font-size a').click(function() {
if($(this).hasClass('increase')) {
if(baseFontSize < 150)
baseFontSize += 20;
$('.pg-content-body p').css('font-size', baseFontSize+'%');
} else {
if(baseFontSize > 70)
baseFontSize -= 10;
$('.pg-content-body p').css('font-size', baseFontSize+'%');
}
});
// Print button
$('.pgc-print a').click(function() {
window.print();
})
}
};
}(jQuery));
// There's a problem with our jQuery loading before the ingested site's
// jQuery which is causing jQuery plugins to break (the "once" plugin in this case).
// I'm using this workaround for now
jQuery(function() {
Drupal.behaviors.titlebar.init();
});;
(function ($) {
Drupal.behaviors.giftTypes = {
init: function() {
// Gift details accordion
$('.pg-gift-details .accordion-items').css('display', 'none');
$('.pg-gift-details .accordion-switch').click(function(){
if($(this).hasClass('open')) {
$(this).find('span').removeClass('icon-arrow-up').addClass('icon-arrow-down');
$('.pg-gift-details .accordion-items').slideUp('slow');
$(this).html($(this).html().replace('Hide', 'Show More'));
$(this).removeClass('open');
} else {
$(this).find('span').removeClass('icon-arrow-down').addClass('icon-arrow-up');
$('.pg-gift-details .accordion-items').slideDown('slow');
$(this).html($(this).html().replace('Show More', 'Hide'));
$(this).addClass('open');
}
})
}
}
}(jQuery));
// There's a problem with our jQuery loading before the ingested site's
// jQuery which is causing jQuery plugins to break (the "once" plugin in this case).
// I'm using this workaround for now
jQuery(function() {
Drupal.behaviors.giftTypes.init();
});;
(function ($){
$("#ctl00_btnSearch001").on("click", function(){
var searchVal = $("#ctl00_txtSearch").val();
alert(searchVal);
window.location.href = "http://www.mywebsite.org/search/?sa=Search&q=" + searchVal;
});
})(jQuery);
;
You can see my little script at the bottom there. It says there's something wrong with the first line, but I'm not sure what the problem is. What change would I need to make to my javascript file to make sure it compiles right?
I'm probably overlooking a really simple type, but I can't see what's wrong with my jQuery.
This is the part that's not working:
(function ($){
$("#ctl00_btnSearch001").on("click", function(){
var searchVal = $("#ctl00_txtSearch").val();
window.location.href = "http://www.website.org/search/?sa=Search&q=" + searchVal;
});
})(jQuery);
I have jQuery on my site, I know I do because this it's used earlier in the code with no problem. The error is showing in the debugger on the first line, '$("#ct100_btnSearch001").on("click", function(){ '. Here is a larger section of the script page:
(function($) {
Drupal.behaviors.giftTypes = {
init: function() {
// Gift details accordion
$('.pg-gift-details .accordion-items').css('display', 'none');
$('.pg-gift-details .accordion-switch').click(function() {
if ($(this).hasClass('open')) {
$(this).find('span').removeClass('icon-arrow-up').addClass('icon-arrow-down');
$('.pg-gift-details .accordion-items').slideUp('slow');
$(this).html($(this).html().replace('Hide', 'Show More'));
$(this).removeClass('open');
} else {
$(this).find('span').removeClass('icon-arrow-down').addClass('icon-arrow-up');
$('.pg-gift-details .accordion-items').slideDown('slow');
$(this).html($(this).html().replace('Show More', 'Hide'));
$(this).addClass('open');
}
})
}
}
}(jQuery));
jQuery(function() {
Drupal.behaviors.giftTypes.init();
});;
(function($) {
$("#ctl00_btnSearch001").on("click", function() {
var searchVal = $("#ctl00_txtSearch").val();
alert(searchVal);
window.location.href = "http://www.mywebsite.org/search/?sa=Search&q=" + searchVal;
});
})(jQuery);;
Try to install jQuery update Module.
If you are using Drupal 6, you are not be able to use on function.
One option is to include your custom version of jQuery in your page.tpl.php, another option (not recommended) is to use live, but now is deprecated.
You can bind a function to an event use two way:
1.use bind() method and the event name as the first argument
$( "#foo" ).bind( "click", function() {
alert( "User clicked on 'foo.'" );
});
or
2.just use the event method
$( "#foo" ).click( function() {
alert( "User clicked on 'foo.'" );
});
The problem of your code is that there isn't a on event.
ref http://api.jquery.com/category/events/mouse-events/
If ctl00_btnSearch001 is a correct id for what ever you are trying to click. Try changing it to this:
(function ($){
$(document).on("click", "#ctl00_btnSearch001", function(){
var searchVal = $("#ctl00_txtSearch").val();
window.location.href = "http://www.mywebsite.org/search/?sa=Search&q=" + searchVal;
});
})(jQuery);
I call a loading function for loading content into my #content div.
All work but my problem is this div contains sometimes content that needs a script to run.
(here MIXITUP)
For now, I call ( callback function ) the function who runs mixitup after loading (ajax) but when I load content more than one time, mixitup seems to be a little lost, the filters btn lost active class.
Here's my code for my file AJAX.php:
$(function() {
// historique
$(window).bind('popstate', function() {
console.log( "popstate event" );
var url = window.location;
var hash = url.href.substring(url.href.lastIndexOf('/') + 1);
$('#content').load( url + ' #content');
});
// hide loading
$('#loading').hide();
// menu action link click
$('.menu a').click(function(e) {
e.preventDefault();
$('#loading').slideDown(500);
$("html, body").animate({ scrollTop: $('#loading').offset().top }, 20);
$('.menu li').removeClass('active');
$(this).parent().addClass('active');
var lien = $(this).attr('href');
$('#content').fadeOut(500, function() {
$('#content').load( lien + ' #content> *', function () {
$('#content').fadeIn(500, function() {
$('#loading').slideUp();
history.pushState(null, null, lien);
});
});
});
});
});
And here is my.js
function mixitNow() {
$('.mixit').mixItUp({
load: {
filter: 'all'
},
controls: {
toggleFilterButtons: false,
toggleLogic: 'or',
live: true,
},
callbacks: {
onMixEnd: function(state) {
$("body").getNiceScroll().resize();
}
}
});
$( "a.toggle" ).click(function() {
$(".linkto a.toggle[data-target="+$(this).attr('data-target')+"]").toggleClass( "active" );
// Trigger the NiceScroll to resize
$("body").getNiceScroll().resize();
});
$('.navmenu').niceScroll({cursorcolor: "#84dbff", cursorborder: "none", cursorwidth: "4px", cursorborderradius: "0", scrollspeed: "100"});
$("body").niceScroll({cursorcolor: "#22ABDE", cursorborder: "1px solid #fff", cursorborderradius: "0", scrollspeed: "100"});
};
$(document).ready(function() {
mixitNow(); //works
console.log( "doc ready call 2 mixit" );
});
$(document).ajaxSuccess(function() {
console.log( "ajaxSuccess" );
mixitNow(); //works
});
instead of .load() you could use $.ajax and make use of the success handler
$.ajax({
url: url,
type: 'GET',
success:function(response){
// check response and
if(xyz){
mixItUp()
}else {
// else no mixin
}
}
})
You must delete the instance of MixItUp from the memory before your new ajax call, otherwise further instantiations on the same element will be blocked. Call this before making the ajax call.
try {
$('.mixit').mixItUp('destroy');
}catch(x) {}
I am developing a jquery module for add delete edit view etc.
My problem is when page load complete, a list of items populate. After selecting an item this item's subitems loaded via jquery and html built, appended. But on this table event not fired up. Jquery Live is no longer available. Instead "On" is not working.
I tried :
$(document).on('click', selector , function () { foo(); });
But when a button is clicked it triggers other buttons as well.
My code is below.
I have a working code except links on table which loaded by jquery.
var myModule = {
el: {
listbutton: $('#list-button'),
listcontainer: $('#list'),
detailbutton: $(".item-detail"),
deletebutton: $(".item-delete"),
editbutton: $(".item-edit")
},
init: function() {
...
myModule.el.listbutton.on("click",myModule.getMainData);
},
getMainData: function() {
...
success: function(data) {
myModule.BuildTable(data.Value.DataList);
}
...
},
BuildTable: function (hws) {
var c = "";
c += "<table>";
$.each(hws, function() {
c +=
'<tr>' +
'<td>' + this.Title + '</td>' +
'<td></td>' +
'<td></td>' +
'<td></td>' +
'<tr>';
});
c += "</table>";
myModule.el.listcontainer.empty().append(c);
myModule.TableLinks();
},
itemDetails: function () {
alert("Detail clicked");
},
itemDelete: function () {
alert("Delete clicked");
},
itemEdit: function () {
alert("Edit clicked");
},
TableLinks: function () {
$(document).on('click', myModule.el.detailbutton, function () { myModule.itemDetails(); });
$(document).on('click', myModule.el.deletebutton, function () { myModule.itemDelete(); });
$(document).on('click', myModule.el.editbutton, function () { myModule.itemEdit(); });
},
};
myModule.init();
Can you try following:
TableLinks: function () {
$(document).on('click',
".item-detail",
function (ev) {
myModule.itemDetails();
ev.stopPropagation();
}
);
$(document).on('click',
".item-delete",
function (ev) {
myModule.itemDelete();
ev.stopPropagation();
});
$(document).on('click',
".item-edit",
function (ev) {
myModule.itemEdit();
ev.stopPropagation();
});
},
you need the delegation
$("selector on which item is added").on("click", "new item selector", function(){
});
ON and Delegate
You have to do something like this to use the "on" method.
$("table").on("click", myModule.el.detailbutton, myModule.itemDetails());
UPDATE: Just noticed, you have to used a selector not a jQuery object in the second parameter.
So $("table").on("click", ".item-detail", myModule.itemDetails());
your approach using on is exactly what you need, but should have been bit more careful on constructing the element object
el: {
listbutton: '#list-button',
listcontainer: '#list',
detailbutton: ".item-detail",
deletebutton: ".item-delete",
editbutton: ".item-edit"
},
and use it like this
init: function () {
$(myModule.el.listbutton).on("click", myModule.getMainData);
},
what you did is
TableLinks: function () {
$(document).on('click', myModule.el.detailbutton, function () { myModule.itemDetails(); });
...
},
which is similar to and which is wrong
TableLinks: function () {
$(document).on('click', $(".item-detail"), function () { myModule.itemDetails(); });
....
},
working fiddle
As it is possible to define multiple event handlers in one single function in jQuery like this:
$(document).on({
'event1': function() {
//do stuff on event1
},
'event2': function() {
//do stuff on event2
},
'event3': function() {
//do stuff on event3
},
//...
});
Then again we can do this:
$(document).on('click', '.clickedElement', function() {
//do stuff when $('.clickedElement') is clicked
});
I was wondering if it is also possible to do something like this (the following code does not work, it's just for illustration):
$(document).on('click', {
'.clickedElement1', function() {
//do stuff when $('.clickedElement1') is clicked
},
'.clickedElement2', function() {
//do stuff when $('.clickedElement2') is clicked
},
//... and so on
});
This code gives me an error complaining about the "," after '.clickedElementX'. I also tried it like this:
$(document).on('click', {
'.clickedElement1': function() {
//do stuff when $('.clickedElement1') is clicked
},
//... and so on
});
Then I don't have the error but also the function is not executed. Is there a way to collect all the click handlers in one place like this or would I have to always do it like this:
$(document).on('click', '.clickedElement1', function() {
//do stuff when $('.clickedElement1') is clicked
});
$(document).on('click', '.clickedElement2', function() {
//do stuff when $('.clickedElement2') is clicked
});
//... and so on
You can chain :
$(document).on({
click: function() {
//click on #test1
},
blur: function() {
//blur for #test1
}
}, '#test1').on({
click: function() {
//click for #test2
}
}, '#test2');
FIDDLE
Short answer: no, you have to bind them all separately.
Long answer: You can create an "infrastructure" for your site and have all events in one place. e.g.
var App = function(){
// business logic
return {
Settings: { ... },
Events: {
'event1': function(){
},
'event2': function(){
},
'event3': function(){
}
}
}
}();
Then wiring it up involves:
$(document).on(App.Events);
Then internally you can add then new bindings to your App object but still remains wired up in only one place (as far as jQuery is concerned). You could then make some kind of subscriber model within App (e.g. App.Subscribe('click', function(){ ... })) and each new subscription still is only wired through the single .on() binding.
but, IMHO, this is a lot of overhead with very little pay-off.
$(document).on('click' , function(e){
if($(e.target).hasClass("some-class")){
//do stuff when .some-class is clicked
}
if($(e.target).hasClass("some-other-class")){
//do stuff when .some-other-class is clicked
}
});
you can choose any some-class you want
It can be easily done, really:
$(document).ready(function()
{
$(this).on('click', '.one, .two',function()
{
if ($(this).hasClass('one'))
{//code for handler on .one selector
console.log('one');
}
else
{//code for handler on .two selector
console.log('two');
}
console.log(this);//code for both
});
});
If multiple events is what you're after:
$(document).ready(function()
{
$(this).on('click focus', '.one, .two',function()
{
if (event.which === 'click')
{
if ($(this).hasClass('one'))
{
console.log('one');
}
else
{
console.log('two');
}
}
else
{
console.log('focus event fired');
}
console.log(this);
});
});
Play around with this: here's a fiddle
documentation on event
jQuery's on, which is used here as though it were delegate
you can use a helper function:
function oneplace(all){
for (var query in all){
$(query).on('click', all[query]);
}
}
and then call:
oneplace(
{'#ele1':function(){
alert('first function');
},
'#ele2':function(){
alert('second function');
}});
jsfiddle here: http://jsfiddle.net/5zwkf/