Multiple javascript functions in one file - javascript

I used some bootstrap javascript functions and one swiper function in one file. Problem is the swiper function doesnt work if i put it last in the code. If I put it first it works fine but the other functions stop working. How to seperate them correctly so that each function is loaded fine.
/* SIDEBAR */
$("#menu-toggle").click(function(e) {
e.preventDefault();
$("#wrapper").toggleClass("toggled");
});
/* SIDEBAR COLLAPSE */
$('.collapse').collapse()
$('.collapse-up').on('click',function(){
$('.collapse').collapse('hide');
});
/* ON/OFF BUTTON */
$("[name='checkbox']").bootstrapSwitch();
/* LOGIN MODAL*/
$('#login').modal(options) ;
/* RATING SLIDER */
$('#rate').slider({
formatter: function(value) {
tooltip: 'always'
return value + ' % ';
}
});
/* SWIPER */
var swiper = new Swiper('.keyword-swiper', {
slidesPerView: 2,
scrollbarHide: true,
grabCursor: true,
paginationClickable: true,
spaceBetween: 0,
freeMode: true,
});

<!--scrollbar: '.swiper-scrollbar',--> is not valid JavaScript. You need to use the /* */ comment style:
var swiper = new Swiper('.keyword-swiper', {
/* scrollbar: '.swiper-scrollbar', */
slidesPerView: 2,
...
Or the // comment style:
var swiper = new Swiper('.keyword-swiper', {
// scrollbar: '.swiper-scrollbar',
slidesPerView: 2,
...
The JavaScript interpreter tries to interpret <!-- --> (an HTML comment) as JS code.

Related

How to init hidden swiper on page load?

I have a swiper positioned inside a tab on a wordpress site, thus it is not initiated on page load, so the navigation function does not work. You can see it here by clicking on the "görüşler" tab.
I did a research and I found out that it's a common issue and it can be initiated with some custom jquery. I've added the following code as an external javascript, however I can't get it to work. If anyone can help me out, I'd appreciate it as it is driving me insane. Many thanks in advance.
jQuery(document).on("pageinit", function($) {
var swiper = new Swiper('.swiper-container', {
parallax: true,
autoHeight: true,
setWrapperSize: true,
slidesPerView: 1,
spaceBetween: 30,
centeredSlides: true,
autoplay: {
delay: 2500,
disableOnInteraction: false,
},
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev',
},
observer: true,
observeParents: true,
});
swiper.init();
});
I ended up using this code, posting it here in case anyone needs it.
// Call On Page Load
var observer = new IntersectionObserver( (entries, observer) => {
entries.forEach(entry => {
if (entry.intersectionRatio > 0) {
window.dispatchEvent(new Event('resize'));
observer.unobserve(entry.target);
if (entry.target.swiper) {
entry.target.swiper.slideTo(0);
}
};
});
}, null);
observer.observe(document.querySelector('#yepss .swiper-container'));

How do I change a property in Javascript with media query?

I'm new to JS. I'm trying to use media queries with Vanilla JavaScript. I'm trying to design a Slider to my webpage. I'm using Swiper.js. This is my JS code:
var mySwiper = new Swiper('.swiper-container', {
// Optional parameters
loop: true,
slidesPerView: 3,
spaceBetween: 30,
// If we need pagination
pagination: {
el: '.swiper-pagination',
clickable: true,
},
// Navigation arrows
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev',
}, });
I want to modify the slidesPerView property value to 1 with media-query max-width of 750px. I tried this way:
var media = window.matchMedia("(max-width: 750px)");
mediaSlider(media);
media.addListener(mediaSlider);
function mediaSlider(media) {
if(media.matches) {
mySwiper.slidesPerView = 1;
}
}
This method is not working. Kindly help me to find out where I've missed something.
Thank you
its called addEventListener. There is only 1 event. Its called change
let media = window.matchMedia("(max-width: 750px)");
function mediaSlider(media) {
if (media.matches) {
mySwiper.slidesPerView = 1;
}
}
media.addEventListener("change", mediaSlider);
It's always suggested to read the documentation properly. I'd made the same mistake again. Swiper.js provides an option to add responsive breakpoints. I modified my code like this in order to work it out.
var mySwiper = new Swiper('.swiper-container', {
// Optional parameters
loop: true,
slidesPerView: 1,
spaceBetween: 30,
breakpoints: {
750: {
slidesPerView: 3,
},
},

Swiper not working on browser is resized to Smartphone view in chrome

I'm having some issue now in my swiper. I'm currently on test phase and my swiper is not working when the window is changed to smartphone and I have to refresh my browser to make the swiper work again. Is there any way I can re initialize my swiper to adapt to the new browser type? Here's what I have:
var swiper = new Swiper('.swiper-container', {
effect: 'slide',
direction: 'horizontal',
loop: true,
simulateTouch: true,
slidesPerView: 1,
spaceBetween: 0,
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev',
},
on: {
slideChangeTransitionEnd:function() {
//other codes
}
}
});
I have tried
setTimeout(() => {
swiper.update()
}, 500)
and
$(window).resize(function(){
swiper.reInit()
})
$(window).trigger("resize")
but they are all not working. Can you help me figure out what I'm missing? or is it really needed to refresh the page to make the js adapt to its new browser environment?
Slider only works if clicking the previous or next button but not on drag.
Try this
let resize = function () {
// Whatever you like to do
}
window.onresize = resize
You can read more about resize event here
https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onresize

Swiper slider add class to active slide when attribute in HTML is set

I want to add class to navbar when active slide has got attribute set for example "navbar-dark". I tried with class but my function doesn't work perfect. It is when I changed slide the class was adding to the second slide not to first slide.
$(document).ready(function () {
var mySwiper = new Swiper('.swiper-container', {
direction: 'horizontal',
loop: false,
mousewheel: {
invert: false,
},
});
mySwiper.on('slideChange', function (realIndex) {
if ($('.swiper-slide.swiper-slide-active').hasClass('dark')) {
$('#navbar').addClass('darknav')
} else {
$('#navbar').removeClass('darknav');
}
});
});
I googled for "swiper jQuery plugin", opened the first suggested page and went to the API.
And there's the Events section, and there's the .on init method. Let's try it
jQuery(function($) {
function darkNav() {
//if ( $('.swiper-slide.swiper-slide-active').hasClass('dark') ) { // `this` rather?
if ( $(this).find('.swiper-slide-active').hasClass('dark') ) {
$('#navbar').addClass('darknav')
} else {
$('#navbar').removeClass('darknav');
}
}
var mySwiper = new Swiper('.swiper-container', {
direction: 'horizontal',
loop: false,
mousewheel: {
invert: false,
},
on: {
init: darkNav, // do also on init
slideChange: darkNav // is this needed?
}
});
});
Also, instead of $('.swiper-slide.swiper-slide-active').hasClass('dark') you could rather try with $(this).find('.swiper-slide-active').hasClass('dark')

Can I use an if statement to change the API options of the Swiper javascript slider?

Sorry if this is a dumb question. I'm using the Swiper javascript slider, developed by iDangerous. It comes with an initialization field that I have in my HTML file, in it are the initialization options for the slider.
I'm in a situation where I need to search the webpage for a certain element called #editor-content. If the element is found, I need the simulateTouch option of the Swiper initialization to be set to false. If the element is not found, the stimulateTouch option should be set to true.
I am using jQuery to accomplish the finding-the-element. I'm using if(($('#editor-content').length)){...} to accomplish this. This part works just fine.
Here is what the Swiper initialization looks like...
<script>
swiper = new Swiper('.swiper-container', {
spaceBetween: 30,
centeredSlides: true,
// This is the option that needs to be set to true/false depending on whether the #editor-content element exists in the webpage or not...
stimulateTouch = false;***
autoplay: {
delay: 2500,
disableOnInteraction: true,
},
pagination: {
el: '.swiper-pagination',
clickable: true,
},
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev',
},
});
</script>
So far, I've tried to initialize the slider differently based on outcome. If it finds the element, initialize the swiper with the option disabled. If it doesn't, initialize the swiper with the option enabled. That didn't work (see code below--and I'm very sorry for the indentation mess):
<script>
var swiper = undefined;
function initSwiper() {
// If the jQuery detects an #editor-content element (meaning you're in the editor...)
if((jQuery('#editor-content').length)){
swiper = new Swiper('.swiper-container', {
spaceBetween: 30,
centeredSlides: true,
// Element found, so initialize the slider with option below set to false
simulateTouch = false,
autoplay: {
delay: 2500,
disableOnInteraction: true,
},
pagination: {
el: '.swiper-pagination',
clickable: true,
},
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev',
},
});
} else {
var swiper2 = new Swiper('.swiper-container', {
spaceBetween: 30,
centeredSlides: true,
// Element not found, so initialize the slider with option below set to true
simulateTouch = true,
autoplay: {
delay: 2500,
disableOnInteraction: true,
},
pagination: {
el: '.swiper-pagination',
clickable: true,
},
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev',
},
});
}
}
// Initialize the function
initSwiper();
</script>
I'm expecting the slider to have the stimulateTouch option set to false when the #editor-content does exist, and have it set the option to true when the element in the body does not exist. But so far my attempted code is just making the entire slider js not function. Help?
If you run your code through a Javascript validator (such as this: http://esprima.org/demo/validate.html) you'll find you have a syntax error on line 12.
stimulateTouch = false,
needs to be
stimulateTouch: false,
as per the other properties.
Just FYI, you may want to look into using Chrome Developer Tools or some other debugging tool to pick up small issues like this. The console will let you know if you have any syntax errors, and you can use the debugger to set breakpoints and step through your code line by line so you can find the exact spot where things start to go pear-shaped.

Categories