JQuery: How to refactor JQuery interaction with interface? - javascript

The question is very simple but also a bit theoretical.
Let's imagine you have a long JQuery script which modifies and animate the graphics of the web site. It's objective is to handle the UI. The UI has to be responsive so the real need for this JQuery is to mix some state of visualization (sportlist visible / not visible) with some need due to Responsive UI.
Thinking from an MVC / AngularJS point of view. How should a programmer handle that?
How to refactor JS / JQuery code to implement separation of concerns described by MVC / AngularJS?
I provide an example of JQuery code to speak over something concrete.
$.noConflict();
jQuery(document).ready(function ($) {
/*variables*/
var sliderMenuVisible = false;
/*dom object variables*/
var $document = $(document);
var $window = $(window);
var $pageHost = $(".page-host");
var $sportsList = $("#sports-list");
var $mainBody = $("#mainBody");
var $toTopButtonContainer = $('#to-top-button-container');
/*eventHandlers*/
var displayError = function (form, error) {
$("#error").html(error).removeClass("hidden");
};
var calculatePageLayout = function () {
$pageHost.height($(window).height());
if ($window.width() > 697) {
$sportsList.removeAttr("style");
$mainBody
.removeAttr("style")
.unbind('touchmove')
.removeClass('stop-scroll');
if ($(".betslip-access-button")[0]) {
$(".betslip-access-button").fadeIn(500);
}
sliderMenuVisible = false;
} else {
$(".betslip-access-button").fadeOut(500);
}
};
var formSubmitHandler = function (e) {
var $form = $(this);
// We check if jQuery.validator exists on the form
if (!$form.valid || $form.valid()) {
$.post($form.attr("action"), $form.serializeArray())
.done(function (json) {
json = json || {};
// In case of success, we redirect to the provided URL or the same page.
if (json.success) {
window.location = json.redirect || location.href;
} else if (json.error) {
displayError($form, json.error);
}
})
.error(function () {
displayError($form, "Login service not available, please try again later.");
});
}
// Prevent the normal behavior since we opened the dialog
e.preventDefault();
};
//preliminary functions//
$window.on("load", calculatePageLayout);
$window.on("resize", calculatePageLayout);
//$(document).on("click","a",function (event) {
// event.preventDefault();
// window.location = $(this).attr("href");
//});
/*evet listeners*/
$("#login-form").submit(formSubmitHandler);
$("section.navigation").on("shown hidden", ".collapse", function (e) {
var $icon = $(this).parent().children("button").children("i").first();
if (!$icon.hasClass("icon-spin")) {
if (e.type === "shown") {
$icon.removeClass("icon-caret-right").addClass("icon-caret-down");
} else {
$icon.removeClass("icon-caret-down").addClass("icon-caret-right");
}
}
toggleBackToTopButton();
e.stopPropagation();
});
$(".collapse[data-src]").on("show", function () {
var $this = $(this);
if (!$this.data("loaded")) {
var $icon = $this.parent().children("button").children("i").first();
$icon.removeClass("icon-caret-right icon-caret-down").addClass("icon-refresh icon-spin");
console.log("added class - " + $icon.parent().html());
$this.load($this.data("src"), function () {
$this.data("loaded", true);
$icon.removeClass("icon-refresh icon-spin icon-caret-right").addClass("icon-caret-down");
console.log("removed class - " + $icon.parent().html());
});
}
toggleBackToTopButton();
});
$("#sports-list-button").on("click", function (e)
{
if (!sliderMenuVisible)
{
$sportsList.animate({ left: "0" }, 500);
$mainBody.animate({ left: "85%" }, 500)
.bind('touchmove', function (e2) { e2.preventDefault(); })
.addClass('stop-scroll');
$(".betslip-access-button").fadeOut(500);
sliderMenuVisible = true;
}
else
{
$sportsList.animate({ left: "-85%" }, 500).removeAttr("style");
$mainBody.animate({ left: "0" }, 500).removeAttr("style")
.unbind('touchmove').removeClass('stop-scroll');
$(".betslip-access-button").fadeIn(500);
sliderMenuVisible = false;
}
e.preventDefault();
});
$mainBody.on("click", function (e) {
if (sliderMenuVisible) {
$sportsList.animate({ left: "-85%" }, 500).removeAttr("style");
$mainBody.animate({ left: "0" }, 500)
.removeAttr("style")
.unbind('touchmove')
.removeClass('stop-scroll');
$(".betslip-access-button").fadeIn(500);
sliderMenuVisible = false;
e.stopPropagation();
e.preventDefault();
}
});
$document.on("click", "div.event-info", function () {
if (!sliderMenuVisible) {
var url = $(this).data("url");
if (url) {
window.location = url;
}
}
});
function whatDecimalSeparator() {
var n = 1.1;
n = n.toLocaleString().substring(1, 2);
return n;
}
function getValue(textBox) {
var value = textBox.val();
var separator = whatDecimalSeparator();
var old = separator == "," ? "." : ",";
var converted = parseFloat(value.replace(old, separator));
return converted;
}
$(document).on("click", "a.selection", function (e) {
if (sliderMenuVisible) {
return;
}
var $this = $(this);
var isLive = $this.data("live");
var url = "/" + _language + "/BetSlip/Add/" + $this.data("selection") + "?odds=" + $this.data("odds") + "&live=" + isLive;
var urlHoveringBtn = "/" + _language + '/BetSlip/AddHoveringButton/' + $this.data("selection") + "?odds=" + $this.data("odds") + "&live=" + isLive;
$.ajax(urlHoveringBtn).done(function (dataBtn) {
if ($(".betslip-access-button").length == 0 && dataBtn.length > 0) {
$("body").append(dataBtn);
}
});
$.ajax(url).done(function (data) {
if ($(".betslip-access").length == 0 && data.length > 0) {
$(".navbar").append(data);
$pageHost.addClass("betslipLinkInHeader");
var placeBetText = $("#live-betslip-popup").data("placebettext");
var continueText = $("#live-betslip-popup").data("continuetext");
var useQuickBetLive = $("#live-betslip-popup").data("usequickbetlive").toLowerCase() == "true";
var useQuickBetPrematch = $("#live-betslip-popup").data("usequickbetprematch").toLowerCase() == "true";
if ((isLive && useQuickBetLive) || (!isLive && useQuickBetPrematch)) {
var dialog = $("#live-betslip-popup").dialog({
modal: true,
dialogClass: "fixed-dialog"
});
dialog.dialog("option", "buttons", [
{
text: placeBetText,
click: function () {
var placeBetUrl = "/" + _language + "/BetSlip/QuickBet?amount=" + getValue($("#live-betslip-popup-amount")) + "&live=" + $this.data("live");
window.location = placeBetUrl;
}
},
{
text: continueText,
click: function () {
dialog.dialog("close");
}
}
]);
}
}
if (data.length > 0) {
$this.addClass("in-betslip");
}
});
e.preventDefault();
});
$(document).on("click", "a.selection.in-betslip", function (e) {
if (sliderMenuVisible) {
return;
}
var $this = $(this);
var isLive = $this.data("live");
var url = "/" + _language + "/BetSlip/RemoveAjax/" + $this.data("selection") + "?odds=" + $this.data("odds") + "&live=" + isLive;
$.ajax(url).done(function (data) {
if (data.success) {
$this.removeClass("in-betslip");
if (data.selections == 0) {
$(".betslip-access").remove();
$(".betslip-access-button").remove();
$(".page-host").removeClass("betslipLinkInHeader");
}
}
});
e.preventDefault();
});
$("section.betslip .total-stake button.live-betslip-popup-plusminus").click(function (e) {
if (sliderMenuVisible) {
return;
}
e.preventDefault();
var action = $(this).data("action");
var amount = parseFloat($(this).data("amount"));
if (!isNumeric(amount)) amount = 1;
var totalStake = $("#live-betslip-popup-amount").val();
if (isNumeric(totalStake)) {
totalStake = parseFloat(totalStake);
} else {
totalStake = 0;
}
if (action == "decrease") {
if (totalStake < 1.21) {
totalStake = 1.21;
}
totalStake -= amount;
} else if (action == "increase") {
totalStake += amount;
}
$("#live-betslip-popup-amount").val(totalStake);
});
toggleBackToTopButton();
function toggleBackToTopButton() {
isScrollable() ? $toTopButtonContainer.show() : $toTopButtonContainer.hide();
}
$("#to-top-button").on("click", function () { $("#mainBody").animate({ scrollTop: 0 }); });
function isScrollable() {
return $("section.navigation").height() > $(window).height() + 93;
}
var isNumeric = function (string) {
return !isNaN(string) && isFinite(string) && string != "";
};
function enableQuickBet() {
}
});

My steps in such cases are:
First of all write (at least) one controller
Replace all eventhandler with ng-directives (ng-click most of all)
Pull the view state out of the controller with ng-style and ng-class. In most of all cases ng-show and ng-hide will be sufficed
If there is code that will be used more than once, consider writing a directive.
And code that has nothing todo with the view state - put the code in a service
write unit tests (i guess there is no one until now:) )

Related

Commenting out JS gives dev console error?

I'm trying to comment out a block of code in my site's main.js file, since it makes my sticky header jump in a funny way upon scrolling.
When I comment out the sticky header section, it fixes the jumpy header issue.
However, it also throws the following error in Firefox or Chrome developer console:
Uncaught ReferenceError: jQuery is not defined
Here is the original unedited code:
jQuery(function ($) {
// Sticky Header
if ($('body').hasClass('sticky-header')) {
var header = $('#sp-header');
if($('#sp-header').length) {
var headerHeight = header.outerHeight();
var stickyHeaderTop = header.offset().top;
var stickyHeader = function () {
var scrollTop = $(window).scrollTop();
if (scrollTop > stickyHeaderTop) {
header.addClass('header-sticky');
} else {
if (header.hasClass('header-sticky')) {
header.removeClass('header-sticky');
}
}
};
stickyHeader();
$(window).scroll(function () {
stickyHeader();
});
}
if ($('body').hasClass('layout-boxed')) {
var windowWidth = header.parent().outerWidth();
header.css({"max-width": windowWidth, "left": "auto"});
}
}
// go to top
$(window).scroll(function () {
if ($(this).scrollTop() > 100) {
$('.sp-scroll-up').fadeIn();
} else {
$('.sp-scroll-up').fadeOut(400);
}
});
$('.sp-scroll-up').click(function () {
$("html, body").animate({
scrollTop: 0
}, 600);
return false;
});
// Preloader
$(window).on('load', function () {
$('.sp-preloader').fadeOut(500, function() {
$(this).remove();
});
});
//mega menu
$('.sp-megamenu-wrapper').parent().parent().css('position', 'static').parent().css('position', 'relative');
$('.sp-menu-full').each(function () {
$(this).parent().addClass('menu-justify');
});
// Offcanvs
$('#offcanvas-toggler').on('click', function (event) {
event.preventDefault();
$('.offcanvas-init').addClass('offcanvas-active');
});
$('.close-offcanvas, .offcanvas-overlay').on('click', function (event) {
event.preventDefault();
$('.offcanvas-init').removeClass('offcanvas-active');
});
$(document).on('click', '.offcanvas-inner .menu-toggler', function(event){
event.preventDefault();
$(this).closest('.menu-parent').toggleClass('menu-parent-open').find('>.menu-child').slideToggle(400);
});
//Tooltip
$('[data-toggle="tooltip"]').tooltip();
// Article Ajax voting
$('.article-ratings .rating-star').on('click', function (event) {
event.preventDefault();
var $parent = $(this).closest('.article-ratings');
var request = {
'option': 'com_ajax',
'template': template,
'action': 'rating',
'rating': $(this).data('number'),
'article_id': $parent.data('id'),
'format': 'json'
};
$.ajax({
type: 'POST',
data: request,
beforeSend: function () {
$parent.find('.fa-spinner').show();
},
success: function (response) {
var data = $.parseJSON(response);
$parent.find('.ratings-count').text(data.message);
$parent.find('.fa-spinner').hide();
if(data.status)
{
$parent.find('.rating-symbol').html(data.ratings)
}
setTimeout(function(){
$parent.find('.ratings-count').text('(' + data.rating_count + ')')
}, 3000);
}
});
});
// Cookie consent
$('.sp-cookie-allow').on('click', function(event) {
event.preventDefault();
var date = new Date();
date.setTime(date.getTime() + (30 * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
document.cookie = "spcookie_status=ok" + expires + "; path=/";
$(this).closest('.sp-cookie-consent').fadeOut();
});
$(".btn-group label:not(.active)").click(function()
{
var label = $(this);
var input = $('#' + label.attr('for'));
if (!input.prop('checked')) {
label.closest('.btn-group').find("label").removeClass('active btn-success btn-danger btn-primary');
if (input.val() === '') {
label.addClass('active btn-primary');
} else if (input.val() == 0) {
label.addClass('active btn-danger');
} else {
label.addClass('active btn-success');
}
input.prop('checked', true);
input.trigger('change');
}
var parent = $(this).parents('#attrib-helix_ultimate_blog_options');
if( parent ){
showCategoryItems( parent, input.val() )
}
});
$(".btn-group input[checked=checked]").each(function()
{
if ($(this).val() == '') {
$("label[for=" + $(this).attr('id') + "]").addClass('active btn btn-primary');
} else if ($(this).val() == 0) {
$("label[for=" + $(this).attr('id') + "]").addClass('active btn btn-danger');
} else {
$("label[for=" + $(this).attr('id') + "]").addClass('active btn btn-success');
}
var parent = $(this).parents('#attrib-helix_ultimate_blog_options');
if( parent ){
parent.find('*[data-showon]').each( function() {
$(this).hide();
})
}
});
function showCategoryItems(parent, value){
var controlGroup = parent.find('*[data-showon]');
controlGroup.each( function() {
var data = $(this).attr('data-showon')
data = typeof data !== 'undefined' ? JSON.parse( data ) : []
if( data.length > 0 ){
if(typeof data[0].values !== 'undefined' && data[0].values.includes( value )){
$(this).slideDown();
}else{
$(this).hide();
}
}
})
}
$(window).on('scroll', function(){
var scrollBar = $(".sp-reading-progress-bar");
if( scrollBar.length > 0 ){
var s = $(window).scrollTop(),
d = $(document).height(),
c = $(window).height();
var scrollPercent = (s / (d - c)) * 100;
const postition = scrollBar.data('position')
if( postition === 'top' ){
// var sticky = $('.header-sticky');
// if( sticky.length > 0 ){
// sticky.css({ top: scrollBar.height() })
// }else{
// sticky.css({ top: 0 })
// }
}
scrollBar.css({width: `${scrollPercent}%` })
}
})
});
The portion I want to comment out is just the "sticky header" block.
I tried to do so like this:
jQuery(function ($) {
// Sticky Header
/* if ($('body').hasClass('sticky-header')) {
var header = $('#sp-header');
if($('#sp-header').length) {
var headerHeight = header.outerHeight();
var stickyHeaderTop = header.offset().top;
var stickyHeader = function () {
var scrollTop = $(window).scrollTop();
if (scrollTop > stickyHeaderTop) {
header.addClass('header-sticky');
} else {
if (header.hasClass('header-sticky')) {
header.removeClass('header-sticky');
}
}
};
stickyHeader();
$(window).scroll(function () {
stickyHeader();
});
}
if ($('body').hasClass('layout-boxed')) {
var windowWidth = header.parent().outerWidth();
header.css({"max-width": windowWidth, "left": "auto"});
}
}
*/
// go to top
$(window).scroll(function () {
if ($(this).scrollTop() > 100) {
$('.sp-scroll-up').fadeIn();
} else {
$('.sp-scroll-up').fadeOut(400);
}
});
$('.sp-scroll-up').click(function () {
$("html, body").animate({
scrollTop: 0
}, 600);
return false;
});
// Preloader
$(window).on('load', function () {
$('.sp-preloader').fadeOut(500, function() {
$(this).remove();
});
});
//mega menu
$('.sp-megamenu-wrapper').parent().parent().css('position', 'static').parent().css('position', 'relative');
$('.sp-menu-full').each(function () {
$(this).parent().addClass('menu-justify');
});
// Offcanvs
$('#offcanvas-toggler').on('click', function (event) {
event.preventDefault();
$('.offcanvas-init').addClass('offcanvas-active');
});
$('.close-offcanvas, .offcanvas-overlay').on('click', function (event) {
event.preventDefault();
$('.offcanvas-init').removeClass('offcanvas-active');
});
$(document).on('click', '.offcanvas-inner .menu-toggler', function(event){
event.preventDefault();
$(this).closest('.menu-parent').toggleClass('menu-parent-open').find('>.menu-child').slideToggle(400);
});
//Tooltip
$('[data-toggle="tooltip"]').tooltip();
// Article Ajax voting
$('.article-ratings .rating-star').on('click', function (event) {
event.preventDefault();
var $parent = $(this).closest('.article-ratings');
var request = {
'option': 'com_ajax',
'template': template,
'action': 'rating',
'rating': $(this).data('number'),
'article_id': $parent.data('id'),
'format': 'json'
};
$.ajax({
type: 'POST',
data: request,
beforeSend: function () {
$parent.find('.fa-spinner').show();
},
success: function (response) {
var data = $.parseJSON(response);
$parent.find('.ratings-count').text(data.message);
$parent.find('.fa-spinner').hide();
if(data.status)
{
$parent.find('.rating-symbol').html(data.ratings)
}
setTimeout(function(){
$parent.find('.ratings-count').text('(' + data.rating_count + ')')
}, 3000);
}
});
});
// Cookie consent
$('.sp-cookie-allow').on('click', function(event) {
event.preventDefault();
var date = new Date();
date.setTime(date.getTime() + (30 * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
document.cookie = "spcookie_status=ok" + expires + "; path=/";
$(this).closest('.sp-cookie-consent').fadeOut();
});
$(".btn-group label:not(.active)").click(function()
{
var label = $(this);
var input = $('#' + label.attr('for'));
if (!input.prop('checked')) {
label.closest('.btn-group').find("label").removeClass('active btn-success btn-danger btn-primary');
if (input.val() === '') {
label.addClass('active btn-primary');
} else if (input.val() == 0) {
label.addClass('active btn-danger');
} else {
label.addClass('active btn-success');
}
input.prop('checked', true);
input.trigger('change');
}
var parent = $(this).parents('#attrib-helix_ultimate_blog_options');
if( parent ){
showCategoryItems( parent, input.val() )
}
});
$(".btn-group input[checked=checked]").each(function()
{
if ($(this).val() == '') {
$("label[for=" + $(this).attr('id') + "]").addClass('active btn btn-primary');
} else if ($(this).val() == 0) {
$("label[for=" + $(this).attr('id') + "]").addClass('active btn btn-danger');
} else {
$("label[for=" + $(this).attr('id') + "]").addClass('active btn btn-success');
}
var parent = $(this).parents('#attrib-helix_ultimate_blog_options');
if( parent ){
parent.find('*[data-showon]').each( function() {
$(this).hide();
})
}
});
function showCategoryItems(parent, value){
var controlGroup = parent.find('*[data-showon]');
controlGroup.each( function() {
var data = $(this).attr('data-showon')
data = typeof data !== 'undefined' ? JSON.parse( data ) : []
if( data.length > 0 ){
if(typeof data[0].values !== 'undefined' && data[0].values.includes( value )){
$(this).slideDown();
}else{
$(this).hide();
}
}
})
}
$(window).on('scroll', function(){
var scrollBar = $(".sp-reading-progress-bar");
if( scrollBar.length > 0 ){
var s = $(window).scrollTop(),
d = $(document).height(),
c = $(window).height();
var scrollPercent = (s / (d - c)) * 100;
const postition = scrollBar.data('position')
if( postition === 'top' ){
// var sticky = $('.header-sticky');
// if( sticky.length > 0 ){
// sticky.css({ top: scrollBar.height() })
// }else{
// sticky.css({ top: 0 })
// }
}
scrollBar.css({width: `${scrollPercent}%` })
}
})
});
This is effectively commenting out the section and fixing the header bug, but it's also throwing the jQuery not defined error. Is there a more appropriate method for commenting out the section?
Note that the same error occurs if I simply delete the entire sticky header block.
Thank you from a newbie for any help!
Simply try single line comments for each line in the code block. If you have VS Code or similar IDE, then it should do it for you. Select all the lines and press CTRL + / or CMD + / (Mac).
// if ($('body').hasClass('sticky-header')) {
// var header = $('#sp-header');
// if($('#sp-header').length) {
// var headerHeight = header.outerHeight();
// var stickyHeaderTop = header.offset().top;
// var stickyHeader = function () {
// var scrollTop = $(window).scrollTop();
// if (scrollTop > stickyHeaderTop) {
// header.addClass('header-sticky');
// } else {
// if (header.hasClass('header-sticky')) {
// header.removeClass('header-sticky');
// }
// }
// };
// stickyHeader();
// $(window).scroll(function () {
// stickyHeader();
// });
// }
// if ($('body').hasClass('layout-boxed')) {
// var windowWidth = header.parent().outerWidth();
// header.css({"max-width": windowWidth, "left": "auto"});
// }
// }

Modify javascript to open in a new window (window.location.href)

I'm creating a site for a client who needs to use a zip code to search for a provider but the search is on a provider search website that's not within our domain. I need to modify this script to be able to force it to open in a new window.
<script type="text/javascript">
$(document).ready(function () {
var submitVetSearchD = function () {
submitVetSearch($('#zip'));
}
function submitVetSearchM() {
submitVetSearch($('#zipM'));
}
function submitVetSearchF() {
submitVetSearch($('#zipF'));
}
function submitVetSearch(ele) {
var zipval = ele.val();
var url = 'https://www.fakesearchresultswebsite.com/';
if (zipval !== "") {
return window.location.href = url + '?zip=' + zipval;
}
}
$("#zip").keyup(function (event) {
if (event.keyCode == 13) {
submitVetSearchD();
}
});
$('#large-header-vet-search').click(submitVetSearchD);
$("#zipM").keyup(function (event) {
if (event.keyCode == 13) {
submitVetSearchM();
}
});
$('#mob-vet-search').click(submitVetSearchM);
$("#zipF").keyup(function (event) {
if (event.keyCode == 13) {
submitVetSearchF();
}
});
$('#footer-vet-search').click(submitVetSearchF);
$("a[rel^='prettyPhoto']").prettyPhoto();
//top menu size
$(window).resize(function () {
setTopMenuHeight();
});
setTopMenuHeight();
var smallHeader = false;
var menuBig = true;
$(document).scroll(function () {
var ele = $("#top-menu-height");
var menuBigNew = !(ele.is(":visible") && $(window).scrollTop() > 200);
if (menuBig != menuBigNew && smallHeader) {
menuBig = menuBigNew;
$("#navtop").toggleClass("small-page-header");
$(".fixed-top").toggleClass("pos-fix");
$("#page-header").toggleClass("fixed-header");
$("#title-area").toggleClass("title-area-small");
$("#logo1").finish();
$("#logo2").finish();
$("#top-menu").finish();
if (menuBig) {
$("#logo2").toggle();
$("#logo1").toggle(1000);
} else {
$("#logo1").toggle();
$("#logo2").toggle(1000);
}
//$("#top-menu").fadeToggle();
}
});
//$('body').on('open.fndtn.reveal', function(){
// $('body').css('overflow', 'hidden');
//});
//$('body').on('closed.fndtn.reveal', function(){
// $('body').css('overflow', 'visible');
//});
});
function setTopMenuHeight() {
var ele = $("#top-menu-height");
var height = $("#page-header").height();
ele.height(height);
}
</script>
Replace
return window.location.href = url + '?zip=' + zipval;
with
var newWin = window.open(url + '?zip=' + zipval);
return true;
Declare newWin in the global scope, it will reference the new window.
Reference: http://www.w3schools.com/jsref/met_win_open.asp

I want to add a loading png in LiveSearch

I am using a plugin for live search .. everything is working fine .. i just want to add a loading png that appear on start of ajax request and disappear on results ..
please help me to customize the code just to add class where form id="search-kb-form" .. and remove the class when results are completed.
<form id="search-kb-form" class="search-kb-form" method="get" action="<?php echo home_url('/'); ?>" autocomplete="off">
<div class="wrapper-kb-fields">
<input type="text" id="s" name="s" placeholder="Search what you’re looking for" title="* Please enter a search term!">
<input type="submit" class="submit-button-kb" value="">
</div>
<div id="search-error-container"></div>
</form>
This is the plugin code
jQuery.fn.liveSearch = function (conf) {
var config = jQuery.extend({
url: {'jquery-live-search-result': 'search-results.php?q='},
id: 'jquery-live-search',
duration: 400,
typeDelay: 200,
loadingClass: 'loading',
onSlideUp: function () {},
uptadePosition: false,
minLength: 0,
width: null
}, conf);
if (typeof(config.url) == "string") {
config.url = { 'jquery-live-search-result': config.url }
} else if (typeof(config.url) == "object") {
if (typeof(config.url.length) == "number") {
var urls = {}
for (var i = 0; i < config.url.length; i++) {
urls['jquery-live-search-result-' + i] = config.url[i];
}
config.url = urls;
}
}
var searchStatus = {};
var liveSearch = jQuery('#' + config.id);
var loadingRequestCounter = 0;
// Create live-search if it doesn't exist
if (!liveSearch.length) {
liveSearch = jQuery('<div id="' + config.id + '"></div>')
.appendTo(document.body)
.hide()
.slideUp(0);
for (key in config.url) {
liveSearch.append('<div id="' + key + '"></div>');
searchStatus[key] = false;
}
// Close live-search when clicking outside it
jQuery(document.body).click(function(event) {
var clicked = jQuery(event.target);
if (!(clicked.is('#' + config.id) || clicked.parents('#' + config.id).length || clicked.is('input'))) {
liveSearch.slideUp(config.duration, function () {
config.onSlideUp();
});
}
});
}
return this.each(function () {
var input = jQuery(this).attr('autocomplete', 'off');
var liveSearchPaddingBorderHoriz = parseInt(liveSearch.css('paddingLeft'), 10) + parseInt(liveSearch.css('paddingRight'), 10) + parseInt(liveSearch.css('borderLeftWidth'), 10) + parseInt(liveSearch.css('borderRightWidth'), 10);
// Re calculates live search's position
var repositionLiveSearch = function () {
var tmpOffset = input.offset();
var tmpWidth = input.outerWidth();
if (config.width != null) {
tmpWidth = config.width;
}
var inputDim = {
left: tmpOffset.left,
top: tmpOffset.top,
width: tmpWidth,
height: input.outerHeight()
};
inputDim.topPos = inputDim.top + inputDim.height;
inputDim.totalWidth = inputDim.width - liveSearchPaddingBorderHoriz;
liveSearch.css({
position: 'absolute',
left: inputDim.left + 'px',
top: inputDim.topPos + 'px',
width: inputDim.totalWidth + 'px'
});
};
var showOrHideLiveSearch = function () {
if (loadingRequestCounter == 0) {
showStatus = false;
for (key in config.url) {
if( searchStatus[key] == true ) {
showStatus = true;
break;
}
}
if (showStatus == true) {
for (key in config.url) {
if( searchStatus[key] == false ) {
liveSearch.find('#' + key).html('');
}
}
showLiveSearch();
} else {
hideLiveSearch();
}
}
};
// Shows live-search for this input
var showLiveSearch = function () {
// Always reposition the live-search every time it is shown
// in case user has resized browser-window or zoomed in or whatever
repositionLiveSearch();
// We need to bind a resize-event every time live search is shown
// so it resizes based on the correct input element
jQuery(window).unbind('resize', repositionLiveSearch);
jQuery(window).bind('resize', repositionLiveSearch);
liveSearch.slideDown(config.duration)
};
// Hides live-search for this input
var hideLiveSearch = function () {
liveSearch.slideUp(config.duration, function () {
config.onSlideUp();
for (key in config.url) {
liveSearch.find('#' + key).html('');
}
});
};
input
// On focus, if the live-search is empty, perform an new search
// If not, just slide it down. Only do this if there's something in the input
.focus(function () {
if (this.value.length > config.minLength ) {
showOrHideLiveSearch();
}
})
// Auto update live-search onkeyup
.keyup(function () {
// Don't update live-search if it's got the same value as last time
if (this.value != this.lastValue) {
input.addClass(config.loadingClass);
var q = this.value;
// Stop previous ajax-request
if (this.timer) {
clearTimeout(this.timer);
}
if( q.length > config.minLength ) {
// Start a new ajax-request in X ms
this.timer = setTimeout(function () {
for (url_key in config.url) {
loadingRequestCounter += 1;
jQuery.ajax({
key: url_key,
url: config.url[url_key] + q,
success: function(data){
if (data.length) {
searchStatus[this.key] = true;
liveSearch.find("#" + this.key).html(data);
} else {
searchStatus[this.key] = false;
}
loadingRequestCounter -= 1;
showOrHideLiveSearch();
}
});
}
}, config.typeDelay);
}
else {
for (url_key in config.url) {
searchStatus[url_key] = false;
}
hideLiveSearch();
}
this.lastValue = this.value;
}
});
});
};
add a background to the loading class
.loading {
background:url('http://path_to_your_picture');
}

S3Slider jQuery Stop After One Rotation

I'm using an S3Slider on WordPress. I'd like it to stop after one rotation, but can't seem to figure out the setting.
The following code is used in the slider.js file. Right now it's live at http://beaconwc.com on the frontpage, would like it to show the two slides and then stop until the user refreshes the page.
(function($){
$.fn.s3Slider = function(vars) {
var element = this;
var timeOut = (vars.timeOut != undefined) ? vars.timeOut : 4000;
var current = null;
var timeOutFn = null;
var faderStat = true;
var mOver = false;
var capOpacity = vars.captionOpacity || .7;
var items = $("#" + element[0].id + "Content ." + element[0].id + "Image");
var itemsSpan = $("#" + element[0].id + "Content ." + element[0].id + "Image div");
itemsSpan.css({
'opacity': capOpacity,
'display': 'none'
});
items.each(function(i) {
$(items[i]).mouseover(function() {
mOver = true;
});
$(items[i]).mouseout(function() {
mOver = false;
fadeElement(true);
});
});
var fadeElement = function(isMouseOut) {
var thisTimeOut = (isMouseOut) ? (timeOut/2) : timeOut;
thisTimeOut = (faderStat) ? 10 : thisTimeOut;
if(items.length > 0) {
timeOutFn = setTimeout(makeSlider, thisTimeOut);
} else {
console.log("Poof..");
}
}
var makeSlider = function() {
current = (current != null) ? current : items[(items.length-1)];
var currNo = jQuery.inArray(current, items) + 1
currNo = (currNo == items.length) ? 0 : (currNo - 1);
var newMargin = $(element).width() * currNo;
if(faderStat == true) {
if(!mOver) {
$(items[currNo]).fadeIn((timeOut/6), function() {
if($(itemsSpan[currNo]).css('bottom') == 0) {
$(itemsSpan[currNo]).slideUp((timeOut/6), function() {
faderStat = false;
current = items[currNo];
if(!mOver) {
fadeElement(false);
}
});
} else {
$(itemsSpan[currNo]).slideDown((timeOut/6), function() {
faderStat = false;
current = items[currNo];
if(!mOver) {
fadeElement(false);
}
});
}
});
}
} else {
if(!mOver) {
if($(itemsSpan[currNo]).css('bottom') == 0) {
$(itemsSpan[currNo]).slideDown((timeOut/6), function() {
$(items[currNo]).fadeOut((timeOut/6), function() {
faderStat = true;
current = items[(currNo+1)];
if(!mOver) {
fadeElement(false);
}
});
});
} else {
$(itemsSpan[currNo]).slideUp((timeOut/6), function() {
$(items[currNo]).fadeOut((timeOut/6), function() {
faderStat = true;
current = items[(currNo+1)];
if(!mOver) {
fadeElement(false);
}
});
});
}
}
}
}
makeSlider();
};
})(jQuery);
Thanks!
Source
http://www.serie3.info/s3slider/

According to jQuery my custom function in not a function

Error message (Last line):
$("select").selectList is not a
function
Code:
(function( $ ){
$.fn.selectList = function(options) {
var settings = {
'buttonClass' : 'custom-select',
'buttonTextClass' : 'custom-select-status',
'buttonIconClass' : 'custom-select-button-icon',
'menuClass' : 'custom-select-menu',
'menuClassHidden' : 'custom-select-menu-hidden'
}
$('body').click(function() {
$('.' + settings.menuClass).each(function() {
$(this).addClass(settings.menuClassHidden);
})
});
return this.each(function() {
if (options) {
$.extend(settings, options);
}
var $this = $(this).hide(),
$menu = $('<ul></ul>').addClass(settings.menuClass)
.addClass(settings.menuClassHidden),
optionsTexts = new Array(),
currIdx;
$this.find('option').each(function(idx) {
var $opt = $(this);
if ($opt.is(':selected')) {
currIdx = idx;
}
optionsTexts[idx] = $opt.text();
})
for (var i = 0; i < optionsTexts.length; i++) {
var $item = $('<li></li>'),
$link = $('' + optionsTexts[i] + '');
if (i == currIdx) {
$item.addClass('selected');
}
$link.click(function() {
var linkIdx = $link.parent().parent().find('li').index($link.parent());
$this.find('option').eq(linkIdx).attr('selected', 'selected');
$menu.prev().find('.' + settings.buttonTextClass).text($link.text());
if ($menu.hasClass(settings.menuClassHidden)) {
$menu.removeClass(settings.menuClassHidden);
} else {
$menu.addClass(settings.menuClassHidden);
}
});
$item.append($link);
$menu.append($item);
}
$menu.insertBefore($this);
$('')
.html('<span class="'+ settings.buttonTextClass + '">'+ optionsTexts[currIdx] +'</span><span class="' + settings.buttonIconClass + '"></span>')
.addClass(settings.buttonClass)
.insertBefore($menu)
.click(function() {
$('.custom-select-menu').addClass(settings.menuClassHidden);
$menu.hasClass(settings.menuClassHidden)
? $menu.removeClass(settings.menuClassHidden)
: $menu.addClass(settings.menuClassHidden);
return false;
});
});
};
})(jQuery);
$(document).ready(function() {
if (! $('.section-admin').length > 0) {
$('select').selectList();
}
});
Could somebody help?
This works perfect.
See an working example here: Custom jQuery works
Please check if somewhere, somehow you're not initializing jQuery twice. See this answer: https://stackoverflow.com/a/33054683/1712145

Categories

Resources