Some conflicts in JS file - javascript

I got finished JS file that I need to integrate to Drupal theme, but there is some conflicts or something so it looks like that some parts of the script doesn't work at all. Script works without problems on HTML theme.
There is the whole script:
jQuery.noConflict();
(function( $ ) {
$(function() {
/*********************************************************************************************************/
/* -------------------------------------- Navigation ------------------------------------------ */
/*********************************************************************************************************/
//Add class to inernal and external links
$('.navbar-nav a').each(function(index, element) {
if($(element).attr("href").match("^#"))
{
//Add class to inernal links
$(element).addClass("internal");
}
else
{
//Add class to external links
$(element).addClass("external");
}
});
var lastId,
topMenu = $(".navbar-nav"),
topMenuHeight = topMenu.outerHeight(),
// All list items without external links
menuItems = topMenu.find("a").not(".external"),
// Anchors corresponding to menu items
scrollItems = menuItems.map(function() {
var item = $($(this).attr("href"));
if (item.length) {
return item;
}
});
// Bind click handler to menu items
// so we can get a fancy scroll animation
menuItems.click(function(e) {
if (!$(this).hasClass("dropdown-toggle")) {
var href = $(this).attr("href"),
offsetTop = href === "#" ? 0 : $(href).offset().top - topMenuHeight + 1;
$('html, body').stop().animate({
scrollTop: offsetTop
}, 1450, 'easeInOutQuart');
e.preventDefault();
}
});
// Bind to scroll
$(window).scroll(function() {
// Get container scroll position
var fromTop = $(this).scrollTop() + topMenuHeight;
// Get id of current scroll item
var cur = scrollItems.map(function() {
if ($(this).offset().top < fromTop)
return this;
});
// Get the id of the current element
cur = cur[cur.length - 1];
var id = cur && cur.length ? cur[0].id : "";
if (lastId !== id) {
lastId = id;
// Set/remove active class
menuItems
.parent().removeClass("active")
.end().filter("[href=#" + id + "]").parent().addClass("active");
}
});
/*********************************************************************************************************/
/* -------------------------------------- Home part - 100% hight ------------------------------------------ */
/*********************************************************************************************************/
jQuery.fn.refresh = function() {
var s = skrollr.get();
if (s) {
s.refresh(this);
}
return this;
};
function fullHeight() {
windowHeight = $(window).height();
$('#home, .tp-banner-container').css('height', windowHeight).refresh();
};
fullHeight();
$(window).resize(function() {
fullHeight();
});
/*********************************************************************************************************/
/* -------------------------------------- H2 big shadow ------------------------------------------ */
/*********************************************************************************************************/
$("h2").each(function () {
var h2 = $(this);
var span = h2.parent().find("span.title-shadow");
span.append(h2.html());
});
/*********************************************************************************************************/
/* -------------------------------------- Back to top ------------------------------------------ */
/*********************************************************************************************************/
$(".logo").click(function() {
$("html, body").animate({ scrollTop: 0 }, "easeInOutQuart");
return false;
});
/*********************************************************************************************************/
/* -------------------------------------- Contact form ------------------------------------------ */
/*********************************************************************************************************/
(function(e) {
function n(e, n) {
this.$form = e;
this.indexes = {};
this.options = t;
for (var r in n) {
if (this.$form.find("#" + r).length && typeof n[r] == "function") {
this.indexes[r] = n[r]
} else {
this.options[r] = n[r]
}
}
this.init()
}
var t = {
_error_class: "error",
_onValidateFail: function() {}
};
n.prototype = {
init: function() {
var e = this;
e.$form.on("submit", function(t) {
e.process();
if (e.hasErrors()) {
e.options._onValidateFail();
t.stopImmediatePropagation();
return false
}
return true
})
},
notEmpty: function(e) {
return e != "" ? true : false
},
isEmail: function(e) {
return /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(e)
},
isUrl: function(e) {
var t = new RegExp("(^(http[s]?:\\/\\/(www\\.)?|ftp:\\/\\/(www\\.)?|(www\\.)?))[\\w-]+(\\.[\\w-]+)+([\\w-.,#?^=%&:/~+#-]*[\\w#?^=%&;/~+#-])?", "gim");
return t.test(e)
},
elClass: "",
setClass: function(e) {
this.elClass = e
},
process: function() {
this._errors = {};
for (var t in this.indexes) {
this.$el = this.$form.find("#" + t);
if (this.$el.length) {
var n = e.proxy(this.indexes[t], this, e.trim(this.$el.val()))();
if (this.elClass) {
this.elClass.toggleClass(this.options._error_class, !n);
this.elClass = ""
} else {
this.$el.toggleClass(this.options._error_class, !n)
}
if (!n) {
this._errors[t] = n
}
}
this.$el = null
}
},
_errors: {},
hasErrors: function() {
return !e.isEmptyObject(this._errors)
}
};
e.fn.isValid = function(t) {
return this.each(function() {
var r = e(this);
if (!e.data(r, "is_valid")) {
e.data(r, "is_valid", new n(r, t))
}
})
}
})(jQuery)
/*********************************************************************************************************/
/* -------------------------------------- Ajax contact form ------------------------------------------ */
/*********************************************************************************************************/
$('#forms').isValid({
'name': function(data) {
this.setClass(this.$el.parent());
return this.notEmpty(data);
},
'email': function(data) {
this.setClass(this.$el.parent());
return this.isEmail(data);
},
'subject': function(data) {
this.setClass(this.$el.parent());
return this.notEmpty(data);
},
'message': function(data) {
this.setClass(this.$el.parent());
return this.notEmpty(data);
}
}).submit(function(e) {
e.preventDefault();
var $this = $(this);
$.ajax({
'url': $(this).attr('action'),
'type': 'POST',
'dataType': 'html',
'data': $(this).serialize()
}).done(function(response) {
$this.find('.notification').show();
$this.find('input[type="text"], input[type="email"], textarea').val('');
});
return false;
});
$('.notification').on('click', function() {
var $this = $(this);
$this.hide();
});
/*********************************************************************************************************/
/* -------------------------------------- Sticky navigation ------------------------------------------ */
/*********************************************************************************************************/
$("#navigation").sticky({
topSpacing: 0,
className: 'sticky',
wrapperClassName: 'main-menu-wrapper'
});
/*********************************************************************************************************/
/* -------------------------------------- Wow Scroll Animate ------------------------------------------ */
/*********************************************************************************************************/
wow = new WOW({
boxClass: 'wow',
animateClass: 'animated',
offset: 100,
movile: true
});
/*********************************************************************************************************/
/* -------------------------------------- Skrollr and Wow init ------------------------------------------ */
/*********************************************************************************************************/
if (!/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
//Skrollr
var s = skrollr.init({
edgeStrategy: 'set',
forceHeight: true,
smoothScrolling: true,
easing: {
wtf: Math.random,
inverted: function(p) {
return 1 - p;
}
}
});
//Wow init
wow.init();
}
/*********************************************************************************************************/
/* -------------------------------------- Charts, Skils ------------------------------------------ */
/*********************************************************************************************************/
$('.chart').waypoint(function() {
$(this).easyPieChart({
animate: 1000,
size: 200,
lineWidth: 5,
trackColor: "#fff",
barColor:"#de3926",
scaleColor: false,
size: 200,
onStep: function(from, to, percent) {
jQuery(this.el).find('.percent').text(Math.round(percent));
}
});
}, {
triggerOnce: true,
offset: 'bottom-in-view'
});
$(document).ready(function() {
/*********************************************************************************************************/
/* -------------------------------------- Our work ------------------------------------------ */
/*********************************************************************************************************/
App.gridOption1();
/*********************************************************************************************************/
/* -------------------------------------- Ajax our team ------------------------------------------ */
/*********************************************************************************************************/
$('.ajax-popup-team').magnificPopup({
type: 'ajax',
showCloseBtn: true,
modal: true,
closeOnContentClick: false,
overflowY: 'scroll'
});
/*********************************************************************************************************/
/* -------------------------------------- Ajax portfolio page ------------------------------------------ */
/*********************************************************************************************************/
$('.ajax-popup-portfolio').magnificPopup({
type: 'ajax',
showCloseBtn: true,
modal: true,
closeOnContentClick: false,
overflowY: 'scroll',
gallery: {
enabled: true,
arrowMarkup: '<button title="%title%" type="button" class="portfolio mfp-arrow mfp-arrow-%dir%"></button>'
}
});
/*********************************************************************************************************/
/* -------------------------------------- Portfolio gallery ------------------------------------------ */
/*********************************************************************************************************/
$('.gallery-item-content').each(function() { // the containers for all your galleries
$(this).magnificPopup({
delegate: '.gallery-item', // the selector for gallery item
type: 'image',
gallery: {
enabled: true
}
});
});
/*********************************************************************************************************/
/* -------------------------------------- Video ------------------------------------------ */
/*********************************************************************************************************/
$('.popup-youtube, .popup-vimeo, .popup-gmaps').magnificPopup({
disableOn: 700,
type: 'iframe',
mainClass: 'mfp-fade',
removalDelay: 160,
preloader: true,
fixedContentPos: true
});
/*********************************************************************************************************/
/* -------------------------------------- Owl carousel ------------------------------------------ */
/*********************************************************************************************************/
$("#carousel-our-testimonials").owlCarousel({
autoPlay: 3000,
stopOnHover: true,
navigation: false,
paginationSpeed: 1000,
goToFirstSpeed: 2000,
singleItem: true,
autoHeight: true,
transitionStyle: "fade"
});
$("#carousel-our-clients").owlCarousel({
autoPlay: 10000,
stopOnHover: true,
navigation: true,
paginationSpeed: 1000,
goToFirstSpeed: 3500,
singleItem: false,
autoHeight: true,
transitionStyle: "fade",
navigationText: [
"<i class='fa fa-angle-left'></i>",
"<i class='fa fa-angle-right'></i>"
]
});
$("#blog-single").owlCarousel({
navigation: true, // Show next and prev buttons
pagination: false,
slideSpeed: 300,
paginationSpeed: 400,
navigationText: [
"<i class='fa fa-chevron-left'></i>",
"<i class='fa fa-chevron-right'></i>"
],
singleItem: true
});
/*********************************************************************************************************/
/* -------------------------------------- Dropdown Menu Fade ------------------------------------------ */
/*********************************************************************************************************/
$(".dropdown").hover(
function() {
$('.dropdown-menu', this).fadeIn(275);
$(this).addClass("open");
},
function() {
$('.dropdown-menu', this).fadeOut(275);
$(this).removeClass("open");
});
/*********************************************************************************************************/
/* -------------------------------------- Placeholder fix for IE ------------------------------------------ */
/*********************************************************************************************************/
(function($) {
if (!Modernizr.csstransforms3d) {
$('[placeholder]').focus(function() {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
input.removeClass('placeholder');
}
}).blur(function() {
var input = $(this);
if (input.val() == '' || input.val() == input.attr('placeholder')) {
input.addClass('placeholder');
input.val(input.attr('placeholder'));
}
}).blur().parents('form').submit(function() {
$(this).find('[placeholder]').each(function() {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
}
})
});
}
})
});
/*********************************************************************************************************/
/* -------------------------------------- Count ------------------------------------------ */
/*********************************************************************************************************/
$('#statistic').waypoint(function() {
$('.timer').countTo();
}, {
triggerOnce: true,
offset: 'bottom-in-view'
});
/*********************************************************************************************************/
/* -------------------------------------- Show and hide color-switcher ------------------------------------------ */
/*********************************************************************************************************/
$(".color-switcher .switcher-button").click(function(){
$( ".color-switcher" ).toggleClass("show-color-switcher", "hide-color-switcher", 800);
});
/*********************************************************************************************************/
/* -------------------------------------- Color Skins ------------------------------------------ */
/*********************************************************************************************************/
$('a.color').click(function(){
var title = $(this).attr('title');
$('#style-colors').attr('href', 'css/color-schemes/' + title + '.css');
return false;
});
/*********************************************************************************************************/
/* -------------------------------------- Loader ------------------------------------------ */
/*********************************************************************************************************/
$(window).load(function() {
$("#loader").delay(450).fadeOut(800);
$(".preload-gif").addClass('fadeOut');
});
});
})(jQuery);
I hope someone can help me find possible conflicts and resolve it.
Update
I looked at console and found an error, so I commented out 'App.gridOption1();' from script and looks like everything is ok. Right now I'm facing an error from console but from some other script. Here is that script:
$.scrollTo = $.fn.scrollTo = function(x, y, options){
if (!(this instanceof $)) return $.fn.scrollTo.apply($('html, body'), arguments);
options = $.extend({}, {
gap: {
x: 0,
y: 0
},
animation: {
easing: 'swing',
duration: 600,
complete: $.noop,
step: $.noop
}
}, options);
return this.each(function(){
var elem = $(this);
elem.stop().animate({
scrollLeft: !isNaN(Number(x)) ? x : $(y).offset().left + options.gap.x,
scrollTop: !isNaN(Number(y)) ? y : $(y).offset().top + options.gap.y
}, options.animation);
});
};
The error I got is:
TypeError: undefined is not an object (evaluating '$.fn')
(anonymous function)
That is the first line in this script. I think that this error is related with some part of the script that I published first. There is a part 'Home part - 100% hight' that is related to this.
Any suggestion?

$.fn is usually used for a jquery module/extension. Make sure that jquery is loading before the scrollto code.
You might also want to look at using drupal behaviors and properly integrating js in drupal

Related

enable vertical scrolling while see the last slide using owl carousel

I disable vertical scrolling on webpage while swiping the carousel horizontally on mobile devices. I'm using the Owl carousel.and I used the solution Disable vertical scrolling while swiping on touch device using owl carousel in my site.it works well but it has a problem and when I see the last side in owl-carousel I can not scroll vertical to anywhere and I have to go back to the prev slide and then it works correctly and I can move on the page. how can solve this issue ? my website is https://khaaspo.com/Product/ProductDeialsInMob?Code=93&Code=93
$(document).ready(function() {
var owl2 = $('.owl-gallery');
owl2.owlCarousel({
rtl: true,
margin: 10,
nav: true,
loop: false,
navSpeed: 1000,
pullDrag: false,
freeDrag: false,
autoplay: false,
onDragged: function () {
$('body').css('overflow', 'auto');
},
onDrag: function () {
$('body').css('overflow', 'hidden');
},
responsive: {
0: {
items: 1
},
400: {
items: 1
},
600: {
items: 1
},
900: {
items: 1
}
},
onTranslate: function () {
$('.owl-item').find('video').each(function () {
this.pause();
this.currentTime = 0;
});
}
});
owl2.on('drag.owl.carousel', function (event) {
document.ontouchmove = function (e) {
e.preventDefault();
}
});
owl2.on('dragged.owl.carousel', function (event) {
document.ontouchmove = function (e) {
return true;
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I changed my code like below and it works correctly and I solved my problem.
var owl2 = $('.owl-gallery');
owl2.owlCarousel({
rtl: true,
margin: 10,
nav: true,
loop: false,
navSpeed: 1000,
pullDrag: false,
freeDrag: false,
autoplay: false,
onDragged: function () {
$('body').css('overflow', 'auto');
},
onDrag: function (e) {
var current = e.item.index + 1;
var total = e.item.count;
if (current === total) {
$('body').css('overflow', 'auto');
}
else {
$('body').css('overflow', 'hidden');
}
},
responsive: {
0: {
items: 1
},
400: {
items: 1
},
600: {
items: 1
},
900: {
items: 1
}
},
onTranslate: function () {
$('.owl-item').find('video').each(function () {
this.pause();
this.currentTime = 0;
});
},
});
owl2.on('drag.owl.carousel', function (e) {
var current = e.item.index + 1;
var total = e.item.count;
document.ontouchmove = function (e) {
if (current !== total) {
e.preventDefault();
}
else {
return true;
}
}
});
owl2.on('dragged.owl.carousel', function (event) {
document.ontouchmove = function (e) {
return true;
}
});

How to preload css called in JS

How do I preload the css in the following code? I have updated my code with Denis suggestions, but it did not work. Now the pages are not finding css at all. I might be missing something since I do not have much about js. Am i missing something? Thanks again Denis, for your suggestion.
This is a free template that i downloaded somewhere. Its quite lite and solves my pbn needs while keeping the site blazing fast. But I have never seen a html template calling css from a js before. I know how to preload files in html, but no clue what would be the proper attribute for it to be used in a js. This can get me the 100 page score i have been trying for long. Any of JS masters help will be much appreciated.
(function($) {
const item = {
reset: 'full',
breakpoints: {
global: { range: '*', rel: 'preload', href: 'css/style.css', containers: 1400, grid: { gutters: 50 } },
wide: { range: '-1680', rel: 'preload', href: 'css/style-wide.css', containers: 1200, grid: { gutters: 40 } },
normal: { range: '-1280', rel: 'preload', href: 'css/style-normal.css', containers: 960, lockViewport: true },
narrow: { range: '-980', rel: 'preload', href: 'css/style-narrow.css', containers: '95%', grid: { gutters: 30 } },
narrower: { range: '-840', rel: 'preload', href: 'css/style-narrower.css', grid: { gutters: 20, collapse: 1 } },
mobile: { range: '-640', rel: 'preload', href: 'css/style-mobile.css', grid: { gutters: 15, collapse: 2 } }
}
}
Object.keys(item.breakpoints).forEach(key=>{
var res = document.createElement("link");
res.rel = item.breakpoints[key].rel;
res.as = "style";
res.href = item.breakpoints[key].href;
document.head.appendChild(res)
})
}
}, {
layers: {
layers: {
navPanel: {
animation: 'pushX',
breakpoints: 'narrower',
clickToClose: true,
height: '100%',
hidden: true,
html: '<div data-action="navList" data-args="nav"></div>',
orientation: 'vertical',
position: 'top-left',
side: 'left',
width: 275
},
titleBar: {
breakpoints: 'narrower',
height: 44,
html: '<span class="toggle" data-action="toggleLayer" data-args="navPanel"></span><span class="title" data-action="copyHTML" data-args="logo"></span>',
position: 'top-left',
side: 'top',
width: '100%'
}
}
}
});
$(function() {
var $window = $(window);
// Forms (IE<10).
var $form = $('form');
if ($form.length > 0) {
$form.find('.form-button-submit')
.on('click', function() {
$(this).parents('form').submit();
return false;
});
if (skel.vars.IEVersion < 10) {
$.fn.n33_formerize=function(){var _fakes=new Array(),_form = $(this);_form.find('input[type=text],textarea').each(function() { var e = $(this); if (e.val() == '' || e.val() == e.attr('placeholder')) { e.addClass('formerize-placeholder'); e.val(e.attr('placeholder')); } }).blur(function() { var e = $(this); if (e.attr('name').match(/_fakeformerizefield$/)) return; if (e.val() == '') { e.addClass('formerize-placeholder'); e.val(e.attr('placeholder')); } }).focus(function() { var e = $(this); if (e.attr('name').match(/_fakeformerizefield$/)) return; if (e.val() == e.attr('placeholder')) { e.removeClass('formerize-placeholder'); e.val(''); } }); _form.find('input[type=password]').each(function() { var e = $(this); var x = $($('<div>').append(e.clone()).remove().html().replace(/type="password"/i, 'type="text"').replace(/type=password/i, 'type=text')); if (e.attr('id') != '') x.attr('id', e.attr('id') + '_fakeformerizefield'); if (e.attr('name') != '') x.attr('name', e.attr('name') + '_fakeformerizefield'); x.addClass('formerize-placeholder').val(x.attr('placeholder')).insertAfter(e); if (e.val() == '') e.hide(); else x.hide(); e.blur(function(event) { event.preventDefault(); var e = $(this); var x = e.parent().find('input[name=' + e.attr('name') + '_fakeformerizefield]'); if (e.val() == '') { e.hide(); x.show(); } }); x.focus(function(event) { event.preventDefault(); var x = $(this); var e = x.parent().find('input[name=' + x.attr('name').replace('_fakeformerizefield', '') + ']'); x.hide(); e.show().focus(); }); x.keypress(function(event) { event.preventDefault(); x.val(''); }); }); _form.submit(function() { $(this).find('input[type=text],input[type=password],textarea').each(function(event) { var e = $(this); if (e.attr('name').match(/_fakeformerizefield$/)) e.attr('name', ''); if (e.val() == e.attr('placeholder')) { e.removeClass('formerize-placeholder'); e.val(''); } }); }).bind("reset", function(event) { event.preventDefault(); $(this).find('select').val($('option:first').val()); $(this).find('input,textarea').each(function() { var e = $(this); var x; e.removeClass('formerize-placeholder'); switch (this.type) { case 'submit': case 'reset': break; case 'password': e.val(e.attr('defaultValue')); x = e.parent().find('input[name=' + e.attr('name') + '_fakeformerizefield]'); if (e.val() == '') { e.hide(); x.show(); } else { e.show(); x.hide(); } break; case 'checkbox': case 'radio': e.attr('checked', e.attr('defaultValue')); break; case 'text': case 'textarea': e.val(e.attr('defaultValue')); if (e.val() == '') { e.addClass('formerize-placeholder'); e.val(e.attr('placeholder')); } break; default: e.val(e.attr('defaultValue')); break; } }); window.setTimeout(function() { for (x in _fakes) _fakes[x].trigger('formerize_sync'); }, 10); }); return _form; };
$form.n33_formerize();
}
}
// Dropdowns.
$('#nav > ul').dropotron({
offsetY: -15,
hoverDelay: 0
});
});
})(jQuery);
You can use Object.keys for get array of breakpoints item, then you can appendChild to document.head
So, write code like this:
const item = {
reset: 'full',
breakpoints: {
global: { range: '*', rel: 'preload', href: 'css/style.css', containers: 1400, grid: { gutters: 50 } },
wide: { range: '-1680', rel: 'preload', href: 'css/style-wide.css', containers: 1200, grid: { gutters: 40 } },
normal: { range: '-1280', rel: 'preload', href: 'css/style-normal.css', containers: 960, lockViewport: true },
narrow: { range: '-980', rel: 'preload', href: 'css/style-narrow.css', containers: '95%', grid: { gutters: 30 } },
narrower: { range: '-840', rel: 'preload', href: 'css/style-narrower.css', grid: { gutters: 20, collapse: 1 } },
mobile: { range: '-640', rel: 'preload', href: 'css/style-mobile.css', grid: { gutters: 15, collapse: 2 } }
}
}
Object.keys(item.breakpoints).forEach(key=>{
var res = document.createElement("link");
res.rel = item.breakpoints[key].rel;
res.as = "style";
res.href = item.breakpoints[key].href;
document.head.appendChild(res)
})
See in playground: https://jsfiddle.net/denisstukalov/3euofv17/#&togetherjs=RqKywyBFh0

Affecting only one element with jQuery toggle

So I have got this code
$('.item').click(function () {
if ($(".secondary", this).is(":hidden")) {
$(".primary", this).toggle('slide', {
direction: 'right'
}, 500, function () {
$('.secondary', this).toggle('slide', {
direction: 'left'
}, 500);
});
}
});
Current behavior is that when I click .item, .primary slides to the right, but .secondary doesn't slide in at all.
Fiddle: http://jsfiddle.net/zm3zp6ax/
$('.item').click(function () {
var $this = $(this);
if ($(".secondary", this).is(":hidden")) {
$(".primary", $this).toggle('slide', {
direction: 'right'
}, 500, function () {
$('.secondary', $this).toggle('slide', {
direction: 'left'
}, 500);
});
}
});
DEMO

iScroll 4 - cancel preventDefault()

In the code below I added three comments that should explain what the question is. In short: I'm wondering how to disable e.preventDefault(); when it's already set?
var startY;
myScroll = new iScroll(DOMElement, {
snap: 'li',
bounce: false,
bounceLock: false,
momentum: false,
hScrollbar: false,
vScrollbar: false,
hScroll: true,
vScroll: false,
wheelAction: 'scroll',
onBeforeScrollStart: function(e){
startY = e.pageY;
// By default it's advisable to disable browser's scroll
e.preventDefault();
},
onScrollStart: function(){ },
onScrollMove: function(e){
// But here I want to enable browser's functionality if user
// explicitly demands this (i.e. tries to scroll vertically)
if(startY >= e.pageY+70 || startY <= e.pageY-70){
console.log('test');
//alert('test');
console.log(e);
// However, I don't know how to restore this functionality
// Touch device detects 'test' alert correctly and this is
// where I'm stuck.
}
},
onScrollEnd: function(){ },
onRefresh: function(){ },
onDestroy: function(){ },
});
Any help would be appreciated!
You can control scrolling in onBeforeScrollStart. Prevent scrolling between specific area. If it exceeds, scroll starts. I think this helps:
var startY;
var isStarted = false;
myScroll = new iScroll(DOMElement, {
snap: 'li',
bounce: false,
bounceLock: false,
momentum: false,
hScrollbar: false,
vScrollbar: false,
hScroll: true,
vScroll: false,
wheelAction: 'scroll',
onBeforeScrollStart: function(e){
var y=e.pageY;
if (!isStarted) {
startY = y + 0;
isStarted = true;
}
if(startY < y+70 || startY > y-70){
e.preventDefault();
}
},
onScrollStart: function(){ },
onScrollMove: function(e){ },
onScrollEnd: function(){
isStarted = false;
},
onRefresh: function(){ },
onDestroy: function(){ },
});

Javascript - how can I properly shrink this code

Regarding the browser version, the player height should change
if older then ie9
//height is fixed
else
//height is auto
The above code is working but, it's the worst thing I've seen, because I do repeat myself again and again, when only one line changes on this conditional.
<script type="text/javascript">
$(document).ready(function() {
if ($.browser.msie && $.browser.version.substr(0,1)<9) {
$("#jquery_jplayer_1").jPlayer({
ready: function ()
{
$(this).jPlayer("setMedia",
{
m4v: "/video/videoK.mp4",
ogv: "/video/videoK.ogg"
}).jPlayer("play");
$('article.about-k').hide();
olark('api.box.hide');
},
swfPath: "/scripts/",
supplied: "m4v, ogv",
size: {
width: "100%",
height: "400px" // THE ONLY CHANGE IS HERE
},
backgroundColor: "#fff",
click: function() {
$(this).jPlayer("play");
},
ended: function() {
$('.jplayer-k').hide();
$('article.about-k').show();
}
})
} else {
$("#jquery_jplayer_1").jPlayer({
ready: function ()
{
$(this).jPlayer("setMedia",
{
m4v: "/video/videoK.mp4",
ogv: "/video/videoK.ogg"
}).jPlayer("play");
$('article.about-k').hide();
olark('api.box.hide');
},
swfPath: "/scripts/",
supplied: "m4v, ogv",
size: {
width: "100%",
height: "auto" // THE ONLY CHANGE IS HERE
},
backgroundColor: "#fff",
click: function() {
$(this).jPlayer("play");
},
ended: function() {
$('.jplayer-k').hide();
$('article.about-k').show();
}
})
}
});
</script>
As noted by the comments, the only change is on ONE single line.
How can I remake this, without stupidly repeating myself ?
height: "auto" //THIS IS THE ONLY DIFFERENCE!
Please advice
That's quite simple with a ternary operator:
$("#jquery_jplayer_1").jPlayer({
ready: function () {
$(this).jPlayer("setMedia", {
m4v: "/video/videoK.mp4",
ogv: "/video/videoK.ogg"
}).jPlayer("play");
$('article.about-k').hide();
olark('api.box.hide');
},
swfPath: "/scripts/",
supplied: "m4v, ogv",
size: {
width: "100%",
height: ($.browser.msie && $.browser.version.substr(0, 1) < 9)
? "400px"
: "auto"
},
backgroundColor: "#fff",
click: function () {
$(this).jPlayer("play");
},
ended: function () {
$('.jplayer-k').hide();
$('article.about-k').show();
}
})
If you don't like that (e.g. because of a more complex condition), you still can use a simple variable:
var height = "auto";
if (/* IE too old */)
height = "400px";
$…({
… // huge config object
height: height,
…
});
Why not:
<script type="text/javascript">
$(document).ready(function() {
if('<?= $cookie; ?>' > '1' || $(window).width() <= 768) {
$('.jplayer-k').remove();
$('article.about-k').show();
}
$("#jquery_jplayer_1").jPlayer({
ready: function ()
{
$(this).jPlayer("setMedia",
{
m4v: "/video/videoK.mp4",
ogv: "/video/videoK.ogg"
}).jPlayer("play");
$('article.about-k').hide();
olark('api.box.hide');
},
swfPath: "/scripts/",
supplied: "m4v, ogv",
size: {
width: "100%",
height: ($.browser.msie && $.browser.version.substr(0,1)<9) ? "400px" : "auto"
},
backgroundColor: "#fff",
click: function() {
$(this).jPlayer("play");
},
ended: function() {
$('.jplayer-k').hide();
$('article.about-k').show();
}
})
It could be like this:
<script type="text/javascript">
$(document).ready(function() {
if('<?= $cookie; ?>' > '1' || $(window).width() <= 768) {
$('.jplayer-k').remove();
$('article.about-k').show();
}
height = $.browser.msie && parseInt($.browser.version, 10) < 9 ? '400px' : 'auto';
$("#jquery_jplayer_1").jPlayer({
ready: function ()
{
$(this).jPlayer("setMedia",
{
m4v: "/video/videoK.mp4",
ogv: "/video/videoK.ogg"
}).jPlayer("play");
$('article.about-k').hide();
olark('api.box.hide');
},
swfPath: "/scripts/",
supplied: "m4v, ogv",
size: {
width: "100%",
height: height
},
backgroundColor: "#fff",
click: function() {
$(this).jPlayer("play");
},
ended: function() {
$('.jplayer-k').hide();
$('article.about-k').show();
}
})
});
</script>
UPDATE:
I added to code above the Fabriccio Matte suggestion so your code dont fail with IE10
Try:
var playerObj = { ready : function () { /* ... */ }, size : /* AUTO */ };
if (/*stupid IE TEST*/) {
playerObj.size.height = "...";
}
$("#jquery_jplayer_1").jPlayer(playerObj);
Separate your configuration from your processes, and it becomes much less of a hassle.
Also, like #Bergi said, a ternary-operation:
value = (test_with_optional_parentheses) ? passed_value : failed_value;
...or in this case, as an object parameter:
{ value : (test_with_optional_parentheses) ? passed_value : failed_value };
Works perfectly well for changing one thing, inline, in the middle of a configuration object.
Keep my advice in mind for organizing large blocks of code, when you start confusing what you need to do with what you're currently doing.
Keep Bergi's advice in mind for when you need to set one single value (at a time), based on a simple test.

Categories