$(document).ready(adjustEvents);
$(window).on('resize orientationchange', adjustEvents);
function adjustEvents() {
var ww = document.body.clientWidth,
vis = ww > 1030 ? 5 : (ww >= 768 ? 3 : 1);
$('.cycle').cycle({
fx : 'carousel',
swipe : true,
timeout : 5000,
slides : '> article',
carouselVisible : vis,
carouselFluid : true,
autoHeight : 'calc',
prev : '#prev',
next : '#next'
});
}
How can I convert this messy jQuery to be less bloated and responsive
-
29-07-2022 - |
Question
I'm using jQuery cycle2 and the carousel plugin to display some events on my site. It all works great but I want the visible option to change from 5 to 3 on tablets (between 768px and 1030px) and then down to 1 on phones (less than 768px). All of the other options can remain the same. This code is hacked together and messy, so I'm looking for a better way to do it. Also, currently it only works on refresh. That's fine, but it would be nice if it reloaded and worked in real-time when you resize. Here's my current code:
// Events
var ww = document.body.clientWidth;
$(document).ready(function() {
adjustEvents();
})
$(window).bind('resize orientationchange', function() {
ww = document.body.clientWidth;
adjustEvents();
});
var adjustEvents = function() {
if (ww > 1030) {
$('.cycle').cycle({
fx:'carousel',
swipe:true,
timeout:5000,
slides:'> article',
carouselVisible:5,
carouselFluid:true,
autoHeight:'calc',
prev:'#prev',
next:'#next'
});
}
else if (ww >= 768) {
$('.cycle').cycle({
fx:'carousel',
swipe:true,
timeout:5000,
slides:'> article',
carouselVisible:3,
carouselFluid:true,
autoHeight:'calc',
prev:'#prev',
next:'#next'
});
}
else if (ww < 768) {
$('.cycle').cycle({
fx:'carousel',
swipe:true,
timeout:5000,
slides:'> article',
carouselVisible:1,
carouselFluid:true,
autoHeight:'calc',
prev:'#prev',
next:'#next'
});
}
}
Solution
OTHER TIPS
Here's a "trimmed" version of the code...
// Events
var ww = document.body.clientWidth;
$(document).ready(function() {
adjustEvents();
})
$(window).bind('resize orientationchange', function() {
ww = document.body.clientWidth;
adjustEvents();
});
var adjustEvents = function() {
var options = {
fx:'carousel',
swipe:true,
timeout:5000,
slides:'> article',
carouselFluid:true,
autoHeight:'calc',
prev:'#prev',
next:'#next'
}
if (ww > 1030) {
options.carouselVisible = 5;
}
else if (ww >= 768) {
options.carouselVisible = 3;
}
else if (ww < 768) {
options.carouselVisible = 1;
}
$('.cycle').cycle(options);
}
All I really did was create a variable to store the cycle options in, and only change the 1 property that was relevant to each width.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow