How to Move a Carousel Item to the Middle When It's Clicked in Jquery

How to move a carousel item to the middle when it's clicked in jquery

While you have prepared all the information needed about all items, you can calculate the value of the left based on the clicked item.

Here is my modification:

and I've bound the click action of carousel items with this function and passed the clicked item using the self keyword.

var itemClicked=function(item){
var itemIndex=$(item).index(),
newLeft=(itemIndex*itemWidth*-1)+Math.floor(($(viewport).width()/itemWidth)/2)*itemWidth;
$(itemList).animate({left:newLeft+"px"},400);
};

You can check it working on this url: http://jsfiddle.net/rUZHg/3/

I assume that this should work despite of the number of viewed elements while it calculates the padding between the left 0 and the left of the center element.

Move carousel item in middle of carousel on click (JavaScript)

Just change the method getImages as follows. Updated pen
https://codepen.io/Code006/pen/RwwQOoq

function getImages(carouselContainer) {
fetch(`${searchURL}?key=9656065-${apikey}&q=manhattan&image_type=photo&page=1&per_page=9`)
.then((res) => {
return res.json();
})
.then((data) => {
console.log('data', data);
// console.log(type)

let result = '';
data.hits.forEach(elem => {
console.log(typeof elem.largeImageURL);
result +=
`<div class="item animated fadeIn slow">
<a href="#"><img src="${elem.largeImageURL}" role="presentation" alt="Image of ${elem.tags}"/></a>
<p><strong>poster:</strong> <br />${elem.user}</p>
<p><strong>tags:</strong> <br />${elem.tags}
</div>`;
carouselContainer.innerHTML = result;
});

var carouselItems = carouselContainer.children;
for (let k=0; k< carouselItems.length; k++) {
carouselItems[k].setAttribute("index", k);
//click handler to center the clicked item
carouselItems[k].onclick = function(e) {
let slide = e.currentTarget;
let slideWidth = slide.getBoundingClientRect().width;
let slideIndex = parseInt(slide.getAttribute("index"));
let newLeft = (slideIndex*slideWidth*-1)+Math.floor(((carouselContainer.getBoundingClientRect().width) /slideWidth)/2)*slideWidth;
document.getElementById("items-container").style.transition= "all 2s ease 0s";
document.getElementById("items-container").style.left = newLeft+"px";
}
}

const backGroundImage = data.hits[1].largeImageURL;
document.getElementById('header').style.backgroundImage = `linear-gradient(to bottom, rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.7)), url(${backGroundImage})`;
document.getElementById('header').style.backgroundRepeat = 'no-repeat';
});
}

Scrolling carousel item to the middle of carousel with jquery anmate() scrollLeft

It doesn't work because there is no scrolling to be done, your container is as wide as all the elements together. Scrolling would be possible only if there was scrollbars (the browser would add some)

If the intention is to only move an element you could try animating them based on their left position instead.

animate({left: value}, speed);

How to center image in carousel

You've got two options

  1. If you want the image to take up entire carousel then
img 
{
width: 100%;
height: auto;
}

  1. If you dont want the image to stretch 100 %, then set your desired width(or dont, just specify margin) and margin auto:
img
{
width: 50%;
margin: auto;
}

How to create right and left buttons to move product carousel in jQuery?

The goal here is to shift the order of elements to the left or right. With jQuery this is exceptionally easy.

The logic is as so:

  • To shift the order to the right, select the last item, delete it, then insert before the first item

  • To shift the order to the left, select the first item, delete it, then insert after the last item

To achieve this, we attach a click event listener to each respective button. We select all the slider items with the selector $('.item.product'), use last() and first() to get the first and last items, and the remove() function to delete the element. Then, to reorder, we use jQuery's insertBefore() and insertAfter().

This is the result:

$('#right').click(function() {
$('.item.product').last().remove().insertBefore($('.item.product').first());
})
$('#left').click(function() {
$('.item.product').first().remove().insertAfter($('.item.product').last());
})

And the rest is just a matter of styling (note: uses Material Icons for the arrow icons). Define two button elements;

<button id="left" class="nav-btn"><i class="material-icons">chevron_left</i></button>
<button id="right" class="nav-btn"><i class="material-icons">chevron_right</i></button>

The "chevron_right" and "chevron_left" are icon names | List of Icons

Set their position to fixed so that their position isn't lost when the user scrolls. Set the top attribute to calc(50vh - 50px), where 50vh is half the height of the viewport and 50px is the height of the button (to make it exactly in the "center").

A full example (best viewed in full page mode):

var direction_slider = "up";
var current_step = 0;
var scroll_product = false;
var scroll = -1;

$(function() {
$('#right').click(function() {
$('.item.product').last().remove().insertBefore($('.item.product').first());
})
$('#left').click(function() {
$('.item.product').first().remove().insertAfter($('.item.product').last());
})
var $product_carousel = $('.slider');
var products = $product_carousel.children().length;
var product_width = (products * 140);
$product_carousel.css('width', product_width);
var rotating = true;
$(document).on({
mouseenter: function() {
rotating = false;
},
mouseleave: function() {
rotating = true;
}
}, '#carousel');

$product_carousel.on("mousedown", function(e) {
scroll_product = true;
scroll = e.pageX;
event.preventDefault();
}).on("mouseup", function(e) {
scroll_product = false;
var num = Math.floor(Math.abs(scroll - e.pageX) / 140);
var dir = scroll - e.pageX < 0 ? "up" : "down";
for (var x = 0; x < num; x++) {
var $first = $('.slider .item:first');
var $last = $('.slider .item:last');
if (dir == "up") {
$last.prependTo(".slider");
} else {
$first.appendTo(".slider");
}
}
$(".slider").css("transform", "translate(0, 0)")
}).on("mousemove", function(e) {
if (scroll_product) {
$(".slider").css("transform", "translate(" + (e.pageX - scroll) + "px, 0)")
}
});
});
/* button integration styling (start) */

#left {
left: 10px;
}

#right {
right: 10px;
}

.nav-btn {
position: fixed;
top: calc(50vh - 50px);
z-index: 100;
z-index: 100;
height: 50px;
width: 50px;
border-radius: 50%;
cursor: pointer;
background-color: white;
box-shadow: 0 0 1px black;
transition: 0.2s;
}

.nav-btn:hover {
background-color: #d1d1d1;
}

/* button integration styling (end) */

.carousel {
margin: 0 auto;
padding: 1em;
width: 100%;
max-width: 1170px;
margin-left: auto;
overflow: hidden;
}

.slider {
width: 100% !important;
display: flex;
}

.item {
display: inline-table;
width: 280px;
height: 325px;
margin: 0.5em;
border: 1px solid #ccc;
}

a {
color: #8563CF;
text-decoration: none;
font-weight: 100;
}

.thumbnail {
height: 150px;
position: relative;
}

.thumbnail img {
height: 100%;
width: 100%;
object-fit: cover;
object-position: 50% 15%;
}

img {
border: 0;
height: auto;
max-width: 100%;
vertical-align: middle;
}

.p1em {
padding: 1em;
}
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<div class="carousel">
<button id="left" class="nav-btn"><i class="material-icons">chevron_left</i></button>
<button id="right" class="nav-btn"><i class="material-icons">chevron_right</i></button>
<div id="carousel">
<div class="slider" style="width: 280px; transform: translate(0px, 0px);">
<div class="item product">
<a href="#">
<div class="thumbnail image">
<img src="https://i.ytimg.com/vi/ZxrUVuOqsy0/maxresdefault.jpg">
</div>
<div class="box p1em">
<div class="heading ellipsis">
<h3>Prueba 1</h3>
</div>
<div class="author">
<span></span>
</div>
<div class="price right">
<p>
<label></label>
<em class="item-price">$40.130,00</em>
</p>
</div>
</div>
</a>
</div>
<div class="item product">
<a href="#">
<div class="thumbnail image">
<img src="https://i.ytimg.com/vi/ZxrUVuOqsy0/maxresdefault.jpg">
</div>
<div class="box p1em">
<div class="heading ellipsis">
<h3>Curso de PHP 8 básico, intermedio y, avanzado. </h3>
</div>
<div class="author">
<span>Acaded</span>
</div>
<div class="purchased items-center">
<button>Ir al curso</button>
</div>
</div>
</a>
</div>
<div class="item product">
<a href="#">
<div class="thumbnail image">
<img src="https://www.gravatar.com/avatar/0fdacb141bca7fa57c392b5f03872176?s=96&d=identicon&r=PG&f=1">
</div>
<div class="box p1em">
<div class="heading ellipsis">
<h3>Spectric</h3>
</div>
<div class="author">
<span>Spectric</span>
</div>
<div class="purchased items-center">
<button>Check out</button>
</div>
</div>
</a>
</div>
</div>
</div>
</div>

How to adjust page to scroll to center on clicking on carousel?

Hey I updated your fiddle to make it work: http://jsfiddle.net/8bJUc/649/

Basically you are using $(".owl-demo") as if it's a class, but it's an ID. Then the onClick function tries to get the clicked element but fails doing so.

var el = $( e.target.getAttribute('href') );

This line basically says:

Get the href-attribute from the clicked element and use jQuery to locate any elements matching the href attribute. I removed this since you don't specify the href attribute anywhere.

$('.owl-carousel').on('click', function(e) { 

var el = $(".lazyOwl", this);
var elOffset = el.offset().top;
var elHeight = el.height();
var windowHeight = $(window).height();
var offset;

if (elHeight < windowHeight) {
offset = elOffset - ((windowHeight / 2) - (elHeight / 2));
}
else {
offset = elOffset;
}
var speed = 700;
$('html, body').animate({scrollTop:offset}, speed);
});

Please note that the example carousel you posted doesn't work as expected on my Macbook Air 11''. The carousel jumps around whenever I click on it.

Using Jquery to shift reorder list item

here is jquery plugin Roundabout demo

and sourcecode is available at github



Related Topics



Leave a reply



Submit