I have this:
$("#about-us .faq-cta").click(function () {
$('#faq').load('faqs.html #main').delay(100).slideToggle('1000', "easeOutQuad", function () {
$.waypoints('refresh');
$("#siteNav li a").removeClass("siteNavSelected");
}, {
offset: function () {
return $.waypoints('viewportHeight') - $(this).outerHeight();
}
});
});
And this:
if (window.location.hash.toLowerCase() === "#faq") {
$("#about-us .faqCta").click(function () {
$('#faq').load('faqs.html #main').delay(100).slideToggle('1000', "easeOutQuad", function () {
$.waypoints('refresh');
$("#siteNav li a").removeClass("siteNavSelected");
}, {
offset: function () {
return $.waypoints('viewportHeight') - $(this).outerHeight();
}
});
});
}
Each do exactly the same thing.
Is there a way to write a bit of shorthand to combine the two?
Use:
var fcOnClick = function () {
$('#faq').load('faqs.html #main').delay(100).slideToggle('1000', "easeOutQuad", function () {
$.waypoints('refresh');
$("#siteNav li a").removeClass("siteNavSelected");
}, {
offset: function () {
return $.waypoints('viewportHeight') - $(this).outerHeight();
}
});
};
var $cont= $('#about-us');
$('.faq-cta',$cont).click(fcOnClick);
if(window.location.hash.toLowerCase() === "#faq"){
$('.faqCta',$cont).click(fcOnClick);
}
Related
I have written this simple piece of code, and it works!
$(function () {
$('form').each(function () {
var form = $(this);
form.find('[class^="custAction_"]').prop('disabled', true).trigger("chosen:updated");
form.find('[class^="custAction_4b"]').button('disable');
form.find('.custSwitch_1').change(function () {
if (form.find('.custSwitch_1:checked').length) {
form.find('.custAction_1').prop('disabled', false).trigger("chosen:updated").trigger("change");
} else {
form.find('.custAction_1').prop({'disabled': true, 'selectedIndex': 0}).trigger("chosen:updated").trigger("change");
}
});
form.find('.custSwitch_2').change(function () {
if (form.find('.custSwitch_2:checked').length) {
form.find('.custAction_2').prop('disabled', false).trigger("chosen:updated").trigger("change");
} else {
form.find('.custAction_2').prop({'disabled': true, 'selectedIndex': 0}).trigger("chosen:updated").trigger("change");
}
});
form.find('.custSwitch_3').change(function () {
if (form.find('.custSwitch_3:checked').length) {
form.find('.custAction_3').prop('disabled', false).trigger("chosen:updated").trigger("change");
} else {
form.find('.custAction_3').prop({'disabled': true, 'selectedIndex': 0}).trigger("chosen:updated").trigger("change");
}
});
form.find('.custSwitch_4').change(function () {
if (form.find('.custSwitch_4:checked').length) {
form.find('.custAction_4').prop('disabled', false).trigger("chosen:updated").trigger("change");
form.find('.custAction_4b').button("enable");
} else {
form.find('.custAction_4').prop({'disabled': true, 'selectedIndex': 0}).trigger("chosen:updated").trigger("change");
form.find('.custAction_4b').prop("checked", false).button("refresh").button("disable", "disable");
}
});
});
});
Knowing that this was repetitive, I thought a "while" loop would work here, so tried this.....
$(function () {
$('form').each(function () {
var form = $(this);
var switchClass = $('form[class^="custSwitch_"]').length;
form.find('[class^="custAction_"]').prop('disabled', true).trigger("chosen:updated");
form.find('[class^="custAction_4b"]').button('disable');
var countSw = 1;
while (countSw < switchClass) {
form.find('.custSwitch_'+countSw).change(function () {
if (form.find('.custSwitch_' + countSw + ':checked').length) {
form.find('.custAction_' + countSw).prop('disabled', false).trigger("chosen:updated").trigger("change");
} else {
form.find('.custAction_' + countSw).prop({'disabled': true, 'selectedIndex': 0}).trigger("chosen:updated").trigger("change");
}
}); countSw++
}
form.find('.custSwitch_4').change(function () {
if (form.find('.custSwitch_4:checked').length) {
form.find('.custAction_4').prop('disabled', false).trigger("chosen:updated").trigger("change");
form.find('.custAction_4b').button("enable");
} else {
form.find('.custAction_4').prop({'disabled': true, 'selectedIndex': 0}).trigger("chosen:updated").trigger("change");
form.find('.custAction_4b').prop("checked", false).button("refresh").button("disable", "disable");
}
});
});
});
But, alas it didn't! :-) I know I'm missing something, probably something simple.
the .custSwitch_1, 2, and 3 classes no longer enable and disable the custAction_1, 2, and 3 classes!!
Si.
The problem with your code is that the variable countSw is always 3 because when the code inside the change listener is executed, the variable's value is 3.
while (countSw < switchClass) {
form.find('.custSwitch_'+countSw).change(function () {
doSomething(countSw);
}); countSw++
}
function doSomething(countSw) {
if (form.find('.custSwitch_' + countSw + ':checked').length) {
form.find('.custAction_' + countSw).prop('disabled', false).trigger("chosen:updated").trigger("change");
} else {
form.find('.custAction_' + countSw).prop({'disabled': true, 'selectedIndex': 0}).trigger("chosen:updated").trigger("change");
}
}
Note that your countSw is being passed as a parameter now.
I have used Durandal.js for my SPA. I need to have slideshow of Images as background in certain pages, for which I am using jquery-backstretch. I am fetching images from my web back-end. Everything works fine while navigating between pages in normal speed. But, when I navigate from one of the pages which has backstretch to another one with backstretch very rapidly, Images from backstretch in first page also creeps in second page. When I debugged, only the correct Images were being passed to second page. And also the slideshow is not running in a proper interval. So it must be both the backstretches being invoked.
Please tell me how I can stop the previous backstretch from appearing again. Here are the relevant code snippets.
This is my first page's(with backstretch) viewmodel code.
var id = 0;
var backstetcharray;
function loadbackstretchb() {
backstetcharray = new Array();
$.each(that.products, function (i, item)
{
if(item.ProductBackImage != "")
{
backstetcharray.push("xxxxxxxxxx" + item.ProductBackImage);
}
}
);
$.backstretch(backstetcharray, { duration: 5000, fade: 1500 });
}
var that;
define(['plugins/http', 'durandal/app', 'knockout'], function (http, app, ko) {
var location;
function callback() {
window.location.href = "#individual/"+id;
// this.deactivate();
};
return {
products: ko.observableArray([]),
activate: function () {
currentpage = "products";
that = this;
return http.get('yyyyyyyyyyyyyyy').then(function (response) {
that.products = response;
loadbackstretchb();
});
},
attached: function () {
$(document).ready(function () {
$('.contacticon').on({
'mouseenter': function () {
$(this).animate({ right: 0 }, { queue: false, duration: 400 });
},
'mouseleave': function () {
$(this).animate({ right: -156 }, { queue: false, duration: 400 });
}
});
});
$(document).ready(function () {
$(".mainmenucont").effect("slide", null, 1000);
});
//setTimeout($(".mainmenucont").effect("slide", null, 1000), 1000);
$(document).on("click", ".ind1", function (e) {
// alert("ind1");
id = e.target.id;
// $(".mainmenucont").effect("drop", null, 2000, callback(e.target.id));
$('.mainmenucont').hide('slide', { direction: 'left' }, 1000, callback);
});
}
}
});
This is my second page's(with backstretch) viewmodel code.(To where I am navigating)
var recs;
var open;
var i, count;
var backstetcharray;
function loadbackstretchc() {
backstetcharray = new Array();
$.each(recs, function (i, item) {
if (item.BackgroundImage != "") {
backstetcharray.push("xxxxxxxxxx" + item.BackgroundImage);
}
}
);
$.backstretch(backstetcharray, { duration: 5000, fade: 1500 });
}
var that;
define(['plugins/http', 'durandal/app', 'knockout'], function (http, app, ko) {
var system = require('durandal/system');
var location;
function menucallback() {
window.location.href = location;
// this.deactivate();
};
return {
activate: function (val) {
currentpage = "recipes";
open = val;
that = this;
var pdts;
recs;
var recipeJson = [];
http.get('yyyyyyyyyyyyyy').then(function (response) {
pdts = response;
http.get('yyyyyyyyyyyy').then(function (response1) {
recs = response1;
loadbackstretchc();
$.each(pdts, function (i, item) {
var json = [];
$.each(recs, function (j, jtem) {
if (item.DocumentTypeId == jtem.BelongstoProduct) {
json.push(jtem);
}
});
jsonitem = {}
jsonitem["product"] = item.ProductName;
jsonitem["link"] = "#" + item.UmbracoUrl;
jsonitem["target"] = item.UmbracoUrl;
jsonitem["recipes"] = json;
recipeJson.push(jsonitem);
});
// that.products = recipeJson;
count = recipeJson.length;
i = 0;
return that.products(recipeJson);
});
});
},
attached: function(view) {
$(document).ready(function () {
$('.contacticon').on({
'mouseenter': function () {
$(this).animate({ right: 0 }, { queue: false, duration: 400 });
},
'mouseleave': function () {
$(this).animate({ right: -156 }, { queue: false, duration: 400 });
}
});
});
$(document).ready(function () {
$(".mainmenucont").effect("slide", null, 1000);
});
$(document).on("click", ".recipeclick", function (e) {
console.log(e);
location = "#recipe/" + e.target.id;
$('.mainmenucont').hide('slide', { direction: 'left' }, 1000, menucallback);
});
$(document).on("click", ".locclick", function (e) {
if (e.handled != true) {
if (false == $(this).next().is(':visible')) {
$('#accordion ul').slideUp(300);
}
$(this).next().slideToggle(300);
e.handled = true;
}
});
},
products: ko.observableArray([]),
expand: function() {
++i;
if (i == count) {
$("#" + open).addClass("in");
}
}
};
});
I'm trying to animate a view, I'm inserting this code into a js but I have problems on the line 84, in:
function trigger_accordion(item-slide) {
if(!(item-slide.is(':animated'))) {
item-slide.trigger('open');
}
}
The error is printed: Uncaught SyntaxError: Unexpected token function
Attach the full code:
(function ($, Drupal) {
var animation = {
'auto_animate': true,
'auto_animate_delay': 8000,
'auto_animate_id': '',
'caption_speed': 'fast',
//'panel_speed': 'slow',
'panel_speed': 1000,
'panel_easing': 'easeInOutCubic'
}
Drupal.behaviors.pamh_theme = {
attach: function(context, settings) {
$(document).ready(function(){
var i = 1;
$('.item-slide').each(function(key, value) {
$(value).attr('id', 'item-slide-'+i);
i++;
});
$('.slide_caption').hide();
$('#item-slide-1 > .slide_caption').show();
$('#item-slide-1').addClass('active');
$('.item-slide').not('.active').children('.slide_image_slice').show();
});
$('.item-slide')
.bind('open', function(){
if(! $(this).hasClass('open')){
$(this).next().trigger('open');
$(this).addClass('open');
$(this).animate({right: "-=769px"}, animation.panel_speed, animation.panel_easing, function(){display_slices();});
}
else{
$(this).prev().trigger('close');
}
$(this).siblings().removeClass('active');
$(this).addClass('active');
setTimeout(function(){hide_slices()},1);
display_caption();
})
.bind('close', function(){
if($(this).hasClass('open')){
$(this).removeClass('open');
$(this).animate({right: "+=769px"}, animation.panel_speed, animation.panel_easing, function(){display_slices();});
$(this).prev().trigger('close');
}
});
$('.item-slide')
.hoverIntent(
function() {
animation.auto_animate = false;
trigger_accordion($(this));
},
function() {
animation.auto_animate = true;
clearInterval(animation.auto_animate_id);
animation.auto_animate_id = setInterval('slideshow_animate()', animation.auto_animate_delay);
}
)
.click(function() {
trigger_accordion($(this));
});
animation.auto_animate_id = setInterval('slideshow_animate()', animation.auto_animate_delay);
};
function trigger_accordion(item-slide) {
if(!(item-slide.is(':animated'))) {
item-slide.trigger('open');
}
}
function display_caption() {
$('.slide_caption').each(function() {
if(!($(this).parent().hasClass('active'))) {
$(this).fadeOut('fast', function() {
$('.item-slide.active > .slide_caption').fadeIn(animation.caption_speed);
});
}
});
}
function hide_slices() {
$('.slide_image_slice').each(function() {
if($(this).parent().hasClass('active')) {
$(this).fadeOut('fast');
}
});
}
function display_slices() {
$('.slide_image_slice').each(function() {
if(!$(this).parent().hasClass('active') && !$(this).is(":visible")) {
$(this).fadeIn('fast');
}
});
}
function slideshow_animate() {
if(!animation.auto_animate) return;
var next_slide = $('.item-slide.active').next();
if(!next_slide.length) {
next_slide = $('#item-slide-1');
}
next_slide.click();
}
};
})(jQuery, Drupal);
Two things:
You cannot name javascript variables with the - character like you did with item-slide. It is OK with CSS classes, but with javascript you have to find something else.
You had a misplaced closing bracket }. Here is the full code that works for me:
(function ($, Drupal) {
var animation = {
'auto_animate': true,
'auto_animate_delay': 8000,
'auto_animate_id': '',
'caption_speed': 'fast',
//'panel_speed': 'slow',
'panel_speed': 1000,
'panel_easing': 'easeInOutCubic'
}
Drupal.behaviors.pamh_theme = {
attach: function(context, settings) {
$(document).ready(function(){
var i = 1;
$('.item-slide').each(function(key, value) {
$(value).attr('id', 'item-slide-'+i);
i++;
});
$('.slide_caption').hide();
$('#item-slide-1 > .slide_caption').show();
$('#item-slide-1').addClass('active');
$('.item-slide').not('.active').children('.slide_image_slice').show();
});
$('.item-slide')
.bind('open', function(){
if(! $(this).hasClass('open')){
$(this).next().trigger('open');
$(this).addClass('open');
$(this).animate({right: "-=769px"}, animation.panel_speed, animation.panel_easing, function(){display_slices();});
}
else{
$(this).prev().trigger('close');
}
$(this).siblings().removeClass('active');
$(this).addClass('active');
setTimeout(function(){hide_slices()},1);
display_caption();
})
.bind('close', function(){
if($(this).hasClass('open')){
$(this).removeClass('open');
$(this).animate({right: "+=769px"}, animation.panel_speed, animation.panel_easing, function(){display_slices();});
$(this).prev().trigger('close');
}
});
$('.item-slide')
.hoverIntent(
function() {
animation.auto_animate = false;
trigger_accordion($(this));
},
function() {
animation.auto_animate = true;
clearInterval(animation.auto_animate_id);
animation.auto_animate_id = setInterval('slideshow_animate()', animation.auto_animate_delay);
}
)
.click(function() {
trigger_accordion($(this));
});
animation.auto_animate_id = setInterval('slideshow_animate()', animation.auto_animate_delay);
}
};
function trigger_accordion(itemSlide) {
if(!(itemSlide.is(':animated'))) {
itemSlide.trigger('open');
}
}
function display_caption() {
$('.slide_caption').each(function() {
if(!($(this).parent().hasClass('active'))) {
$(this).fadeOut('fast', function() {
$('.item-slide.active > .slide_caption').fadeIn(animation.caption_speed);
});
}
});
}
function hide_slices() {
$('.slide_image_slice').each(function() {
if($(this).parent().hasClass('active')) {
$(this).fadeOut('fast');
}
});
}
function display_slices() {
$('.slide_image_slice').each(function() {
if(!$(this).parent().hasClass('active') && !$(this).is(":visible")) {
$(this).fadeIn('fast');
}
});
}
function slideshow_animate() {
if(!animation.auto_animate) return;
var next_slide = $('.item-slide.active').next();
if(!next_slide.length) {
next_slide = $('#item-slide-1');
}
next_slide.click();
}
})(jQuery, Drupal);
How can I combine these two jQuery functions ? or the .js . Trying to put them together in the same page makes the latter not work at all.
They work just fine for their job if I only use one on the page, but I need them both.
The first one I have is:
(function ($) {
$(document).ready(function () {
// Dropdown Menu
if (!($.browser.msie && ($.browser.version == 6))) {
$("ul#topnav li:has(ul)").addClass("dropdown");
}
$("ul#topnav li.dropdown").hover(function () {
$('ul:first', this).css({
visibility: "visible",
display: "none"
}).slideDown('normal');
}, function () {
$('ul:first', this).css({
visibility: "hidden"
});
});
$("div.prod_hold").hover(function () {
$('.info', this).css({
visibility: "visible",
display: "none"
}).slideDown('normal');
}, function () {
$('.info', this).css({
visibility: "hidden"
});
});
$("li.cat_hold").hover(function () {
$('.info', this).fadeIn(300);
}, function () {
$('.info', this).fadeOut(200);
});
$("li.side_cart").hover(function () {
$('#cart', this).fadeIn(500);
}, function () {
$('#cart', this).fadeOut(200);
});
$("li.side_currency").hover(function () {
$('#currency', this).fadeIn(500);
}, function () {
$('#currency', this).fadeOut(200);
});
$("li.side_lang").hover(function () {
$('#language', this).fadeIn(500);
}, function () {
$('#language', this).fadeOut(200);
});
$("li.side_search").hover(function () {
$('#search', this).fadeIn(500);
}, function () {
$('#search', this).fadeOut(200);
});
$(".main_menu li").hover(function () {
$('.secondary', this).fadeIn(500);
}, function () {
$('.secondary', this).fadeOut(200);
});
$(".cat_right ul li a").hover(function () {
$(this).stop().animate({
paddingLeft: 20,
color: '#ccc'
}, "fast")
}, function () {
$(this).stop().animate({
paddingLeft: 10,
color: '#999'
}, "fast")
});
// Tipsy - tooltips jQuery plugin
$('a.wish_button, a.compare_button, a#button-cart, a.twitter_follow').tipsy({
gravity: 's',
fade: true,
title: function () {
return this.getAttribute('original-title').toUpperCase();
}
});
$('#service_links li a').tipsy({
gravity: 'e',
fade: true,
title: function () {
return this.getAttribute('original-title').toUpperCase();
}
});
// SLIDING ELEMENTS
$("ul.categories li, #sidebar ul.secondary_menu li").hover(function () {
$("a", this).stop().animate({
left: "15px"
}, {
queue: false,
duration: 200
});
}, function () {
$("a", this).stop().animate({
left: "0px"
}, {
queue: false,
duration: 200
});
});
// FADING ELEMENTS
$(".logo img, .oferta_s, .oferta_d").hover(function () {
$(this).stop().animate({
opacity: 0.6
}, "medium")
}, function () {
$(this).stop().animate({
opacity: 1
}, "medium")
});
$(".intro").hover(function () {
$(this).stop().animate({
paddingBottom: 230
}, "medium")
}, function () {
$(this).stop().animate({
paddingBottom: 140
}, "slow")
});
$(".desc_box,.desc_box2").hover(function () {
$(".desc_box,.desc_box2").not(this).stop().animate({
opacity: 0.7
}, "fast")
}, function () {
$(".desc_box,.desc_box2").not(this).stop().animate({
opacity: 1
}, "fast")
});
});
})(window.jQuery);
// non jQuery scripts below
$(document).ready(function () {
var interval;
$('ul#myRoundabout').roundabout({
'btnNext': '.next_round',
'btnPrev': '.previous_round'
}).hover(
function () {
clearInterval(interval);
}, function () {
interval = startAutoPlay();
});
interval = startAutoPlay();
});
function startAutoPlay() {
return setInterval(function () {
$('ul#myRoundabout').roundabout_animateToPreviousChild();
}, 6000);
}
When I add this second code the problems start.. and the code is :
<!-- Validate email using regular expression -->
function validateEmail(emailValue) {
var emailPattern = /^[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]#[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$/;
return emailPattern.test(emailValue);
}
<!-- Validate Form fields -->
function validateForm() {
var send_message = true;
if (jQuery("textarea#message").val().length < 2) {
jQuery("label#message_error").slideDown();
jQuery("textarea#message").focus();
send_message = false;
}
if (!validateEmail(jQuery("input#email").val())) {
jQuery("label#email_error").slideDown();
jQuery("input#email").focus();
send_message = false;
}
if (jQuery("input#name").val().length < 2) {
jQuery("label#name_error").slideDown();
jQuery("input#name").focus();
send_message = false;
}
return send_message;
}
jQuery(function () {
<!-- Contact Form validation -->
jQuery('.error').hide();
jQuery("input#name").bind("keyup focusout", function () {
if (jQuery(this).val().length > 1) {
jQuery("label#name_error").slideUp();
} else {
jQuery("label#name_error").slideDown();
}
});
jQuery("input#email").bind("keyup focusout", function () {
if (validateEmail(jQuery(this).val())) {
jQuery("label#email_error").slideUp();
} else {
jQuery("label#email_error").slideDown();
}
});
jQuery("textarea#message").bind("keyup focusout", function () {
if (jQuery(this).val().length > 1) {
jQuery("label#message_error").slideUp();
} else {
jQuery("label#message_error").slideDown();
}
});
<!-- Submitting Contact Form -->
jQuery("form#contact_form").submit(function () {
var dataString = jQuery(this).serialize();
if (validateForm()) {
jQuery.ajax({
type: "POST",
url: "FormToEmail.php",
data: dataString,
success: function () {
jQuery('#contact_form').slideUp('slow', function () {
jQuery(this).html("<div id='confirmation'></div>");
jQuery('#confirmation').html("<h4>Mesajul a fost trimis cu succes!</h4>").append("<p>Va multumim pentru ca ne-ati contactat. Va vom raspunde la e-mail in cel mai scurt timp posibil!</p>");
Cufon.refresh();
jQuery(this).slideDown('slow');
})
}
});
}
return false;
});
})
* EDIT *
The problem has been fixed, it was the comments. Changed the <!-- comm --> into /* comm */ and it works just fine. Thank you all for your time and help!
Is it possible for me to call selectCompanyJump(this) internally without calling it from App.site.profile?
Instead of doing App.site.profile.selectStateJump(this); can I do like parent.selectStateJump(this); without reassigning this outside of the .change() call?
$(document).ready(function () {
App.site = function () {
return {
init: function () {
this.profile.init();
},
profile: function () {
var profile;
return {
init: function () {
profile = $('div#profile');
$('select[name="company_id"]', profile).change(function () {
App.site.profile.selectCompanyJump(this);
});
$('select[name="state_id"]', profile).change(function () {
App.site.profile.selectStateJump(this);
});
},
selectCompanyJump: function (select) {
$(select.parent()).submit();
},
selectStateJump: function (select) {
$(select.parent()).submit();
}
}
}()
}
}();
App.site.init();
});
You can reference the "this" scope you want as another variable outside change() function definitions:
profile: function () {
var profile;
return {
init: function () {
profile = $('div#profile');
var self = this;
$('select[name="company_id"]', profile).change(function () {
self.selectCompanyJump(this);
});
$('select[name="state_id"]', profile).change(function () {
self.selectStateJump(this);
});
},
selectCompanyJump: function (select) {
$(select.parent()).submit();
},
selectStateJump: function (select) {
$(select.parent()).submit();
}
}
}()
Assuming that you are just using the select argument of your functions to reference the element that triggered the event you could just pass a pointer to the event binder and then use the this keyword.
profile: function () {
var profile;
return {
init: function () {
profile = $('div#profile');
$('name="state_id"', profile).change(this.selectStateJump);
},
selectStateJump: function () {
$(this).parent().submit();
}
}
you can do the following
$(document).ready(function () {
App.site = function () {
var me = this;
me.selectStateJump = function selectStateJump (select) {
$(select.parent()).submit();
}
return {
....
selectStateJump: selectStateJump
}
and you'll be able to call just me.selectStateJump()
EDIT:
actually below would be enough
$(document).ready(function () {
App.site = function () {
function selectStateJump (select) {
$(select.parent()).submit();
}
return {
method : function(select) {
selectStateJump(select);
}
selectStateJump: selectStateJump
}