enable vertical scrolling while see the last slide using owl carousel - javascript

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;
}
});

Related

JavaScript not triggering events when dynamically loaded

I'm using the Swiper.js library and I have an issue getting the 'slideChange' event to trigger when dynamically loading elements through JavaScript.
Here is where my swipers both horizontal and vertical are initialised:
var swiper = {
initialize : function() {
swiperH = new Swiper('.swiper-container-h', {
slidesPerView: 1,
preloadImages: false,
updateOnImagesReady: true,
lazy: true,
})
.on('slideChange', function () {
console.log('Swiped Horizonally');
});
swiperV = new Swiper('.swiper-container-v', {
direction: 'vertical',
slidesPerView: 1,
preloadImages: false,
updateOnImagesReady: true,
lazy: true,
effect: 'fade',
loop: true,
fadeEffect: {
crossFade: true
},
pagination: {
el: '.swiper-pagination-v',
clickable: true,
},
})
.on('slideChange', function () {
console.log('Swiped Vertically');
});
}
};
The reason why the horizontal's 'slideChange' triggers is because its already in the html file:
<!-- Swiper -->
<div class="dash-container">
<div class="swiper-container swiper-container-h">
<div class="swiper-wrapper" id="swipeData">
</div>
</div>
</div>
Now, the vertical slides are loading through JavaScript and that's where the vertical's 'slideChange' doesn't trigger.
function loadDresses(selectedDresses) {
return new Promise((resolve, reject) => {
$('#swipeData').html('');
for (var i = 0; i < selectedDresses.length; i++) {
var vScroll = '<div class="swiper-slide"><div class="swiper-container swiper-container-v"><div class="swiper-wrapper" style="height: 100%;">';
for (var j = 0; j < selectedDresses[i].images.length; j++) {
vScroll += '<div class="swiper-slide"><img src="' + selectedDresses[i].images[j] + '"/></div>';
}
vScroll += '<div class="swiper-slide" style="display:table;height:100%;width:100%;">';
vScroll += '</div></div></div><div class="swiper-pagination swiper-pagination-v">';
$('#swipeData').append(vScroll).trigger('create');
}
resolve(true);
});
}
The error occurs at this snippet:
.on('slideChange', function () {
console.log('Swiped Vertically');
});
Any ideas? Thanks!
Edit:
I have tried the following to stop it from initialising too early, but still no luck:
loadDresses(dresses).then(function(result) {
var t = setInterval(() => {
swiper.initialize();
clearInterval(t);
}, 5000);
});
And doesn't that help?
var swiper = {
initialize : function() {
swiperH = new Swiper('.swiper-container-h', {
slidesPerView: 1,
preloadImages: false,
updateOnImagesReady: true,
lazy: true,
})
.on('slideChange', function () {
console.log('Swiped Horizonally');
});
swiperV = new Swiper('.swiper-container-v', {
direction: 'vertical',
slidesPerView: 1,
preloadImages: false,
updateOnImagesReady: true,
lazy: true,
effect: 'fade',
loop: true,
fadeEffect: {
crossFade: true
},
pagination: {
el: '.swiper-pagination-v',
clickable: true,
},
on: {
slideChange: function() {
console.log('Swiped Vertically');
}
}
});
}
};
You have some options here:
To keep the flow of your application, you can destroy the slider and reinitialize it.
swiperH.destroy()
then
loadDresses();
swiper.initialize();
OR
you can just mySwiper.update() every time you change your slide manually
The problem is that an element with class swiper-pagination-v is not found during initialization.
You can make condition for class swiper-pagination-v exists.
var swiper = {
initialize : function() {
swiperH = new Swiper('.swiper-container-h', {
slidesPerView: 1,
preloadImages: false,
updateOnImagesReady: true,
lazy: true,
})
.on('slideChange', function () {
console.log('Swiped Horizonally');
});
if ($('.swiper-container-v').length > 0) {
swiperV = new Swiper('.swiper-container-v', {
direction: 'vertical',
slidesPerView: 1,
preloadImages: false,
updateOnImagesReady: true,
lazy: true,
effect: 'fade',
loop: true,
fadeEffect: {
crossFade: true
},
pagination: {
el: '.swiper-pagination-v',
clickable: true,
},
})
.on('slideChange', function () {
console.log('Swiped Vertically');
});
}
}
};

called a jQuery function only over a specific width of window

I use this code on my site. I want to load this code only in a specific width of window.
For example, in the less than 768 pixels, this script will no longer be called.
jQuery(document).ready(function() {
var owl = jQuery('.owl-carousel');
owl.owlCarousel({
rtl: true,
margin: 10,
nav: true,
loop: true,
responsive: {
0: {
items: 1
},
600: {
items: 3
},
1000: {
items: 5
}
}
})
})
You can use jQuery's width function and then do something like this:
jQuery(document).ready(function() {
if (jQuery( window ).width() > 768) {
/// your code here
}
});
.width() Refernece
Try This
jQuery(document).ready(function() {
if ($(window).width() < 768){
var owl = jQuery('.owl-carousel');
owl.owlCarousel({
rtl: true,
margin: 10,
nav: true,
loop: true,
responsive: {
0: {
items: 1
},
600: {
items: 3
},
1000: {
items: 5
}
}
})
}
})
if ($( window ).width() > 768){//ur code}

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

OWL Carousel: center slide if click on it

I'm just wondering if there is a way to easily center a slide if I click on it.
So the clicked slide moves to the middle.
Here is my code. The "center on click" function should work on the first slide called "#singleprice".
jQuery(document).ready(function ($) {
var $sync1 = $("#singleprice"),
$sync2 = $("#meanprice"),
flag = false,
duration = 300;
$sync1
.owlCarousel({
nav: true,
items: '3',
startPosition: '4',
dots: false,
center: true,
navContainer: '#priceNav',
})
.on('changed.owl.carousel', function (e) {
if (!flag) {
flag = true;
$sync2.trigger('to.owl.carousel', [e.item.index, duration, true]);
flag = false;
}
});
$sync2
.owlCarousel({
nav: false,
items: '1',
startPosition: '4',
touchDrag: false,
mouseDrag: false,
dots: false
})
.on('click', '.owl-item', function () {
$sync1.trigger('to.owl.carousel', [$(this).index(), duration, true]);
})
.on('changed.owl.carousel', function (e) {
if (!flag) {
flag = true;
$sync1.trigger('to.owl.carousel', [e.item.index, duration, true]);
flag = false;
}
});
});

Some conflicts in JS file

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

Categories