I have an image gallery with a main image and some thumbnail images on the right side of the main image.
I want to set the height of the thumbnails div the same as the main image. The problem is, this image is always different so it doesn't have a static height. Tried to use javascript to get it's height then give it to the thumbnails div, but it doesn't do anything.
<div class="gallery">
<a href="images/1.jpg">
<div class="main-image">
<img class="card-img-top" id="modal-img-top" src="images/1.jpg" alt="Fő kép">
</div>
<div class="image-container" id="image-thumbnails">
<img src="images/1.jpg" alt="Egy kép a hirdetésről">
<img src="images/motor.jpg" alt="Egy kép a hirdetésről">
<img src="images/motor2.jpg" alt="Egy kép a hirdetésről">
<img src="images/2.jpg" alt="Egy kép a hirdetésről">
<img src="images/1.jpg" alt="Egy kép a hirdetésről">
<img src="images/motor.jpg" alt="Egy kép a hirdetésről">
<img src="images/motor2.jpg" alt="Egy kép a hirdetésről">
<img src="images/2.jpg" alt="Egy kép a hirdetésről">
</div>
</a>
</div>
<script type="text/javascript">
const img = new Image();
img.onload = function() {
alert(this.width + 'x' + this.height);
document.getElementById("image-thumbnails").style.height = this.height;
}
img.src = document.getElementById("modal-img-top").getElementsByTagName('img');
</script>
Edit: Ok let's have another try.
The main issue is to size your main image which should stay in its ratio and be wrapped in its parent. After trial and error there seems to be no easy method to archive this. I also tried object-fit property, but event this is not working as you want to. So here are my two solutions.
Solution 1:
The most easy way is to use a div with the background-image property instead of an img. As you see in the solution below, the main-image is a div now. You could also use the element .image-wrapper as the background image. But I wrapped a main-image into it to get some padding between these two elements.
Solution 2: Instead of using the background-image property you can still use a img, but you'll need some javascript and calculations. The calculation is done by the function calculateMainImage. It is not too complex, but it needs some lines. The strategy is this:
Get the dimensions of the main image and its parent element
Assume that the image fits into its parent (in css: width: 100%). So calculate the image dimensions for this assumption.
If the calculated height is greater than the height of the parent, the image won't fit into the parent. So now set the image's height to the height of its parent and recalculate the width.
This function is also called when the document is ready (initialization) and when the window resizes (window.onresize).
let mainImage = document.querySelector('.main-image');
let thumbnails = document.querySelectorAll('.thumbnail');
thumbnails.forEach(thumbnail => {
thumbnail.addEventListener('click', () => {
let backgroundImage = 'url(' + thumbnail.src +')';
mainImage.style.backgroundImage = backgroundImage;
});
});
.gallery{
position: relative;
width: 100%;
height: 400px;
background: #dedede;
display: grid;
grid-template-columns: 70% 30%;
}
.image-wrapper{
position: relative;
width: 100%;
height: 100%;
background: #aaa;
padding: 12px;
box-sizing: border-box;
}
.main-image{
position: relative;
width: 100%;
height: 100%;
background-image: url("https://via.placeholder.com/350x150");
background-size: contain;
background-repeat: no-repeat;
background-position: center;
}
.thumbnail-wrapper{
position: relative;
width: 100%;
height: 100%;
overflow-y: auto;
padding: 12px;
box-sizing: border-box;
}
.thumbnail-wrapper > .thumbnail:not(:last-child){
margin-bottom: 12px;
}
.thumbnail{
position: relative;
display: block;
width: 100%;
height: auto;
margin-left: auto;
margin-right: auto;
cursor: pointer;
}
<section class="gallery">
<!-- Main image -->
<div class="image-wrapper">
<div class="main-image">
</div>
</div>
<!-- Thumbnails -->
<div class="thumbnail-wrapper">
<img class="thumbnail" src="https://via.placeholder.com/350x150">
<img class="thumbnail" src="https://via.placeholder.com/200x100">
<img class="thumbnail" src="https://via.placeholder.com/140x100">
<img class="thumbnail" src="https://via.placeholder.com/350x65">
<img class="thumbnail" src="https://via.placeholder.com/350x150">
<img class="thumbnail" src="https://via.placeholder.com/200x100">
<img class="thumbnail" src="https://via.placeholder.com/140x100">
</div>
</section>
let gallery = document.querySelector('.gallery');
let container = document.querySelector('.container');
let mainImage = document.querySelector('.main-image');
let thumbnails = document.querySelectorAll('.thumbnail');
(function(){
// Document ready
calculateMainImage();
// When window resizes
window.addEventListener('resize', () => {
calculateMainImage();
});
})();
thumbnails.forEach(thumbnail => {
thumbnail.addEventListener('click', () => {
mainImage.src = thumbnail.src;
// Fit image to container
calculateMainImage();
});
});
function calculateMainImage(){
// Reset current dimensions
mainImage.style.width = 'initial';
mainImage.style.height = 'initial';
// Container dimensions
let containerWidth = container.getBoundingClientRect().width;
let containerHeight = container.getBoundingClientRect().height;
// Image dimensions
let width = mainImage.getBoundingClientRect().width;
let height = mainImage.getBoundingClientRect().height;
let ratio = width / height;
// Calculate image dimensions when width: 100%
let maxWidth = containerWidth;
let maxHeight = maxWidth / ratio;
// Check if image fits in parent
if(maxHeight > containerHeight){
// Scale image down. Recalculate image's width
let newHeight = containerHeight;
let newWidth = newHeight * ratio;
setMainImageSize(newWidth, newHeight);
}else{
setMainImageSize(maxWidth, maxHeight);
}
}
function setMainImageSize(width, height){
mainImage.style.width = width + 'px';
mainImage.style.height = height + 'px';
}
.gallery{
position: relative;
width: 100%;
height: 400px;
background: #dedede;
display: grid;
grid-template-columns: 70% 30%;
}
.image-wrapper{
position: relative;
width: 100%;
height: 100%;
background: #aaa;
padding: 12px;
box-sizing: border-box;
}
.container{
position: relative;
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
}
.main-image{
position: relative;
flex-grow: 0;
flex-shrink: 0;
}
.thumbnail-wrapper{
position: relative;
width: 100%;
height: 100%;
overflow-y: auto;
padding: 12px;
box-sizing: border-box;
}
.thumbnail-wrapper > .thumbnail:not(:last-child){
margin-bottom: 12px;
}
.thumbnail{
position: relative;
display: block;
width: 100%;
height: auto;
margin-left: auto;
margin-right: auto;
cursor: pointer;
}
<section class="gallery">
<!-- Main image -->
<div class="image-wrapper">
<div class="container">
<img class="main-image" src="https://via.placeholder.com/200x100">
</div>
</div>
<!-- Thumbnails -->
<div class="thumbnail-wrapper">
<img class="thumbnail" src="https://via.placeholder.com/350x150">
<img class="thumbnail" src="https://via.placeholder.com/200x100">
<img class="thumbnail" src="https://via.placeholder.com/140x100">
<img class="thumbnail" src="https://via.placeholder.com/350x65">
<img class="thumbnail" src="https://via.placeholder.com/350x150">
</div>
</section>
Update
When you have several gallerys on your page and use use solution #1, then you need to add this JS snipped.
let gallerys = document.querySelectorAll('.gallery');
gallerys.forEach(gallery => {
updateGalleryPictures(gallery)
});
function updateGalleryPictures(gallery) {
// Get gallery's main image
let mainImage = gallery.querySelector('.main-image');
if (mainImage === null) return;
// Get gallery's thumbnail images
let thumbnails = gallery.querySelectorAll('.thumbnail');
// Change the background-image property on click
thumbnails.forEach(thumbnail => {
thumbnail.addEventListener('click', () => {
let backgroundImage = 'url(' + thumbnail.src + ')';
mainImage.style.backgroundImage = backgroundImage;
});
});
// Initialize background-image property using the 1st thumbnail image
let firstThumbnail = thumbnails[0];
if (firstThumbnail === null || firstThumbnail === undefined) return;
let initialBackgroundImage = 'url(' + firstThumbnail.src + ')';
mainImage.style.backgroundImage = initialBackgroundImage;
}
Update 2: Usage of baguetteBox
Step 1: Add the property overflow: hidden; to the class .image-wrapper and create a new class
.baguettebox-image{
opacity: 0 !important;
}
Step 2: Change the structure of the main-image setup.
<div class="image-wrapper">
<div class="main-image"> <!-- THis is the baguette box -->
<a class="baguettebox-link" href="">
<img class="baguettebox-image" src=""></a>
</a>
</div>
</div>
Step 3: Change the JS snipped of the 1st update to:
Note that the baguette boxes are also initialized in this script. According to the documentation querySelectorAll is used, so all boxes (.main-image) should be initialized.
let gallerys = document.querySelectorAll('.gallery');
gallerys.forEach(gallery => {
updateGalleryPictures(gallery);
});
// Initialize all baguette boxes
baguetteBox.run('.main-image');
function updateGalleryPictures(gallery) {
// Get gallery's thumbnail images
let thumbnails = gallery.querySelectorAll('.thumbnail');
// Change the background-image property on click
thumbnails.forEach(thumbnail => {
thumbnail.addEventListener('click', () => {
updateMainImage(gallery, thumbnail.src)
});
});
// Initialize background-image property using the 1st thumbnail image
let firstThumbnail = thumbnails[0];
if (firstThumbnail === null || firstThumbnail === undefined) return;
updateMainImage(gallery, firstThumbnail.src)
// Initialize baguette
}
function updateMainImage(gallery, src) {
// Get main image and check if it exists
let mainImage = gallery.querySelector('.main-image');
if (mainImage === null) return;
mainImage.style.backgroundImage = 'url(' + src + ')';
// Get baguette elements
let boxLink = gallery.querySelector('.baguettebox-link');
let boxImage = gallery.querySelector('.baguettebox-image');
// Update baguette elements href and src
if (boxLink !== null && boxLink !== undefined) boxLink.href = src;
if (boxImage !== null && boxImage !== undefined) boxImage.src = src;
}
document.getElementById("image-thumbnails").style.height = '300px';
Related
I've been trying to make use of html2canvas to take a screenshot of a element
I noticed an image inside the div element that uses the object-fit property becomes stretched after the html2canvas screenshot
Is there a walk around for this. Here is my code
<script>window.addEventListener('load', function () {
var bigCanvas = $("<div>").appendTo('body');
var scaledElement = $("#Element").clone()
.css({
'transform': 'scale(1,1)',
'transform-origin': '0 0'
})
.appendTo(bigCanvas);
var oldWidth = scaledElement.width();
var oldHeight = scaledElement.height();
var newWidth = oldWidth * 1;
var newHeight = oldHeight * 1;
bigCanvas.css({
'width': newWidth,
'height': newHeight
})
html2canvas(bigCanvas, {
onrendered: function(canvasq) {
var image = document.getElementById('image');
image.style.width='300px';
image.src = canvasq.toDataURL();
bigCanvas.remove() ;
}
});}) </script>
While html goes as
<div id="Element" class="container">
<div class="bg-light p-3 text-center">
<h3>iPhone 12 Pro Max</h3>
<div class="m-2 shadow" style="height:400px;width:100%;">
<img src="img/agency.jpeg" style="object-fit:cover;height:100%;width:100%;" />
</div>
<h4>Now available for free</h4>
</div>
</div>
<div class="container" style="width:100%;border:2px solid black;overflow:hidden">
<img src="" id="image" style="max-width:100%;"/>
</div>
I had the same issue, unfortunally it seems that html2cavas doesn't support the object-fit property but i resolve with flexbox and the result it's good, it's important to set the width and height for parent node:
.logo-preview-inner {
height: 200px;
width: 200px;
border-radius: 50%;
border: solid 1px #e6e6e6;
margin: 0 auto;
overflow: hidden;
display: flex;
align-items: center;
justify-content: center;
position: relative;
img {
width: 100%;
}
where the class .logo-preview-inner is the parent node and the image is the child
i hope to help you!
I'm trying to figure out the probable basic error here. I'm just trying to get the background image to apply to the parent .img-wrap class rather than to the image itself.
Adding a background colour works, but the background image fails. Any ideas why?
var imgs = document.querySelectorAll('.img-wrap img');
for (let img of imgs) {
let imgSrc = img.getAttribute("src");
img.parentNode.style["background-image"] = imgSrc;
/* this works: img.parentNode.style["background-color"] = 'blue'; */
}
img {
width: 100px;
object-position: -9999px; /* hides image */
border: 1px solid red;
}
.img-wrap {
float: left;
}
<div class='img-wrap'>
<img src = 'https://i.ytimg.com/vi/dw5eILfy-c8/maxresdefault.jpg'>
</div>
<div class='img-wrap'>
<img src = 'https://i.ytimg.com/vi/dw5eILfy-c8/maxresdefault.jpg'>
</div>
<div class='img-wrap'>
<img src = 'https://i.ytimg.com/vi/dw5eILfy-c8/maxresdefault.jpg'>
</div>
Codepen: https://codepen.io/anon/pen/MNydoe
Thanks for any help here.
You need to specify the url() when using the background-image property:
var imgs = document.querySelectorAll('.img-wrap img');
for (let img of imgs) {
let imgSrc = img.getAttribute("src");
img.parentNode.style["background-image"] = 'url("' + imgSrc + '")'; // or `url("${imgSrc}")`
/* this works: img.parentNode.style["background-color"] = 'blue'; */
}
img {
width: 100px;
object-position: -9999px; /* hides image */
border: 1px solid red;
}
.img-wrap {
float: left;
}
<div class='img-wrap'>
<img src = 'https://i.ytimg.com/vi/dw5eILfy-c8/maxresdefault.jpg'>
</div>
<div class='img-wrap'>
<img src = 'https://i.ytimg.com/vi/dw5eILfy-c8/maxresdefault.jpg'>
</div>
<div class='img-wrap'>
<img src = 'https://i.ytimg.com/vi/dw5eILfy-c8/maxresdefault.jpg'>
</div>
I did a slideshow with fade animation of images in a div. However, when the next image shows, the div gets smaller/bigger according to the image and the page auto-scrolls, and I do not want that. How can I avoid this?
I wrote a function that once the page loads, it finds the biggest image, and sets the div to have that height of that image so that whenever a new image shows, the div height does not change. However, the problem is when the browser gets smaller/larger, the value of the div's height does not change even though I am resitting it every time the browser changes the size using on resize listener ("biggestImage" variable).
JQuery
var slideIndex = 0;
showSlides();
divResizeIssue();
function showSlides() {
var slides = $(".images");
slides.each(function(){
$(this).fadeOut(500).delay(490);
});
slideIndex++;
if (slideIndex > slides.length) {
slideIndex = 1;
}
slides.each(function(index){
if(index == slideIndex-1){
$(this).fadeIn(500).delay(490);
}
});
setTimeout(showSlides, 5000);
}
function divResizeIssue(){
var biggestImage;
var object;
var slides = $(".images");
var firstLoad = true;
if(firstLoad){
slides.each(function(index){
if(index == 0 || $(this).outerHeight() > biggestImage){
biggestImage = $(this).outerHeight();
object = $(this)[0]
}
});
slides.each(function(){
if($(this)[0] != object){
$(this).outerHeight(biggestImage);
}
});
firstLoad = false;
}
$(window).on('resize', function(){
biggestImage = 0;
object = null;
slides.each(function(index){
if(index == 0 || $(this).outerHeight() > biggestImage){
biggestImage = $(this).outerHeight();
object = $(this)[0];
}
});
slides.each(function(){
if($(this)[0] != object){
$(this).outerHeight(biggestImage);
}
});
});
}
HTML
<div id="top-div" class="row">
<div class="row">
<h1 class="col-sm-12">Activities</h1>
<span class="col-sm-2"><!-- <button class="leftButton"></button> --></span>
<div class="col-sm-12 col-lg-8">
<figure class="images">
<figcaption class="caption">Outdoor</figcaption>
<img class="img-fluid" id="Outdoor" src=".\src\Hiking.jpg">
</figure>
<figure class="images">
<figcaption class="caption">Indoor</figcaption>
<img class="img-fluid" id = "Indoor" src=".\src\indoor.jpg">
</figure>
<figure class="images">
<figcaption class="caption">Join Us!</figcaption>
<img class="img-fluid" id = "Member" src=".\src\member.png">
</figure>
</div>
<span class="col-sm-2"><!-- <button class="rightButton"> --></button></span>
</div>
</div>
CSS
#top-div {
width: 100%;
margin-top:90vh;
background: #AB3F05;
text-align: center;
height: auto;
}
figure img{
padding-left: 5vh;
padding-right: 5vh;
padding-top: 0;
padding-bottom: 0;
margin: 0;
}
.images{
position: relative;
}
If you have some better suggestion, please do suggest, or if you can tell me what's wrong with my code, that would be great.
Generally speaking, when doing slide shows it's much easier and looks nicer when you just manually resize the images to the same resolution using gimp or photoshop.
However if for whatever reason you can't do that you can use percentages in CSS to create dynamic lengths.
Here's what I came up with
//changed '.images' to '.image-container' also removed the divResizeIssue //function because we don't need it
var slideIndex = 0;
showSlides();
function showSlides() {
var slides = $(".image-container"); //here
slides.each(function(){
$(this).fadeOut(500).delay(490);
});
slideIndex++;
if (slideIndex > slides.length) {
slideIndex = 1;
}
slides.each(function(index){
if(index == slideIndex-1){
$(this).fadeIn(500).delay(490);
}
});
setTimeout(showSlides, 5000);
}
CSS
#top-div {
width: 100%;
margin-top:90vh;
background: #AB3F05;
text-align: center;
height: auto;
}
figure img{
padding-left: 5vh;
padding-right: 5vh;
padding-top: 0;
padding-bottom: 0;
margin: 0;
}
/*Changed Below*/
.image-container {
width: 50%;
margin: 0 auto;
}
.image {
width: 100%;
height: 400px;
}
.image-container
the width: 50% makes it so the .image-container resizes when the browser viewport changes width. margin: 0 auto centers the .image-container inside it's parent.
.image
the width: 100% streaches the img tag to be the width of its parent (the .image-container).
the fixed height: 400px keeps tall images from expanding the height of the parent.
HTML
<div id="top-div" class="row">
<div class="row">
<h1 class="col-sm-12">Activities</h1>
<span class="col-sm-2"><!-- <button class="leftButton"></button> --></span>
<div class="col-sm-12 col-lg-8">
<figure class="image-container">
<figcaption class="caption">Outdoor</figcaption>
<img class="image img-fluid" id="Outdoor" src="https://picsum.photos/200/300">
</figure>
<figure class="image-container">
<figcaption class="caption">Indoor</figcaption>
<img class="image img-fluid" id = "Indoor" src="https://picsum.photos/300/300">
</figure>
<figure class="image-container">
<figcaption class="caption">Join Us!</figcaption>
<img class="image img-fluid" id = "Member" src="https://picsum.photos/400/300">
</figure>
</div>
<span class="col-sm-2"><!-- <button class="rightButton"> --></button></span>
</div>
</div>
I just renamed the class="images" to class="image-container" and added an image class to the img elements, also changed the src on the images to use picsum so you might want to change them back.
The solution that I did was harcoding height values when the screen size changes, I don't really like to hardcode it, but it's the only way I can think of right now.
CSS
#media only screen and (min-width: 576px) {
/*Change slides height to 950px when at sm (576px)*/
#top-div{
height: 950px;
}
}
#media only screen and (max-width: 576px) {
/*Change slides height to 440px when greater than sm*/
#top-div{
height: 440px;
}
}
Hi There,
I try to create very simple slider using Jquery scrollLeft() method .
I found some answers and i tried this one here .... but not working .... I'm still beginner in jquery and don't know why .
HTML
<div class="gallery-slider ">
<div class="images-preview">
<img alt="" class="img-responsive" src="http://placehold.it/300">
<img alt="" class="img-responsive" src="http://placehold.it/300">
<img alt="" class="img-responsive" src="http://placehold.it/300">
<img alt="" class="img-responsive" src="http://placehold.it/300">
<img alt="" class="img-responsive" src="http://placehold.it/300">
<img alt="" class="img-responsive" src="http://placehold.it/300">
<img alt="" class="img-responsive" src="http://placehold.it/300">
<img alt="" class="img-responsive" src="http://placehold.it/300">
<img alt="" class="img-responsive" src="http://placehold.it/300">
<img alt="" class="img-responsive" src="http://placehold.it/300">
<img alt="" class="img-responsive" src="http://placehold.it/300">
<img alt="" class="img-responsive" src="http://placehold.it/300">
</div>
<div class="controls">
<div class="right-arrow"><i class="fa fa-angle-left fa-3x"></i></div>
<div class="left-arrow"><i class="fa fa-angle-right fa-3x"></i></div>
</div>
</div>
CSS
.gallery-slider {
position: relative;
}
.gallery-slider .images-preview {
margin: auto;
height: 230px;
overflow: hidden;
}
.gallery-slider .images-preview img {
display: inline-block;
overflow: visible;
width: 410px;
margin: 10px 17px;
}
.gallery-slider .images-preview img, .controls {
height: 200px;
width: 26%;
}
/* Controls */
.controls {
position: absolute;
top: 10px;
width: 100%;
}
.right-arrow, .left-arrow {
display: inline-block;
padding: 62px;
background-color: rgba(255, 255, 255, 0.76);
position: absolute;
height: 100%;
cursor: pointer;
}
.right-arrow i, .left-arrow i{
margin: 23px 20px;
}
.left-arrow {
right: 0px;
}
.right-arrow {
left: 0px;
text-align: right;
}
jQuery
$(".left-arrow").click(function () {
var leftPos = $('.images-preview img').scrollLeft();
$(".images-preview img").animate({scrollLeft: leftPos - 100}, 1000);
});
$(".right-arrow").click(function () {
var leftPos = $('.images-preview img').scrollLeft();
$(".images-preview img").animate({scrollLeft: leftPos + 100}, 1000);
});
So Any help ?!
Thanks in advance
Fiddle here
Update:
also i need it to return to scrollleft():0 at the end of scrolling
What you are asking for is simple but full of issues. These issues makes things complicated.
I have made images-preview position absolute. It allows you to
scroll by controlling the left(css). Couldnt get the scrollLeft to
work. Dont know why. If anyone do, i would love to know.
Need to calculate the number of img inside the images-preview. Allow you to add or delete images.
var active is added to prevent clicking too fast.
javascript:
var target = $('.images-preview');
//get the total number of images
var total = $('.images-preview img').length;
//calculate the width of the image-preview
var width = total * 300 + total * 40;
var c = 1;
// 80 is to center the image-preview
var originalLeft = 80;
// 300 is the image size, 40 is the total margin (this is how many px image-preview
// would have to move left for one image
var totalImg = 300 + 40;
// startToEnd is the total width when you click left(arrow-right) on first image
var startToEnd = width -originalLeft -340;
var a = '';
//need this to prevent multiple clicks
var active = false;
//put in the width at page rendering
$(document)function(){
target.css('width', width);
});
$(".left-arrow").click(function () {
if (active === false){
if (c === total){
a = originalLeft;
c = 1;
}else{
a = '-='+totalImg;
c++;
}
//turn the active to true to prevent another animation from activating
active = true;
target.animate(
{left: a},
{duration:500,
//turn the active off after animation is complete
complete: function(){
active = false;
}
});
}
});
$(".right-arrow").click(function () {
if (active === false){
if (c === 1){
a = '-'+startToEnd;
c = total;
}else{
a = '+='+totalImg;
c--;
}
active = true;
target.animate(
{left: a},
{duration:500,
complete: function(){
active = false;
}
});
}
});
css:
.gallery-slider{
width:500px;
height:300px;
position:relative;
overflow:hidden;
}
.images-preview{
width:300px;
height:300px;
position:absolute;
left:80px;
}
.images-preview img{
width:300px;
height:300px;
position:relative;
float:left;
margin:0 20px;
}
.control{
width:100%;
height:100%;
position:relative;
}
.right-arrow, .left-arrow{
position:absolute;
padding:0 26px;
}
.right-arrow i, .left-arrow i{
line-height:300px;
}
.right-arrow{
left:0;
}
.left-arrow{
right:0;
}
Here is the demo: https://jsfiddle.net/ood26n7b/1/
I want to automatically scroll a div based on mouse position using jQuery.
If you see this fiddle here, you can see a number of images that are horizontally ordered in a div that is scrollable:
<div id="parent">
<div id="propertyThumbnails">
<img src="http://www.millport.org/wp-content/uploads/2013/05/Flower-festival.jpg" />
<img src="http://www.millport.org/wp-content/uploads/2013/05/Flower-festival.jpg" />
<img src="http://www.millport.org/wp-content/uploads/2013/05/Flower-festival.jpg" />
<img src="http://www.millport.org/wp-content/uploads/2013/05/Flower-festival.jpg" />
<img src="http://www.millport.org/wp-content/uploads/2013/05/Flower-festival.jpg" />
</div>
</div>
CSS:
#parent {
height: 300px;
width: 100%;
background: #ddd;
}
#propertyThumbnails {
background: #666;
height: 80px;
white-space: nowrap;
overflow: scroll;
}
#propertyThumbnails img {
width: 125px;
height: 80px;
display: inline-block;
margin: 3px;
margin-right: 0;
opacity: 0.6;
}
I found out that you can use $("#container").scrollLeft(position) to set the position of the scroller but I want to do it based on the mouse position of the parent. So that when the mouse is fully to the right hand side, the right most image displays, and when the mouse is fully left, the left most image displays.
How can I do this?
A slightly different way to achieve what you need:
jQuery(function($) {
$(window).load(function() {
var $gal = $("#propertyThumbnails"),
galW = $gal.outerWidth(true),
galSW = $gal[0].scrollWidth,
wDiff = (galSW / galW) - 1, // widths difference ratio
mPadd = 60, // Mousemove Padding
damp = 20, // Mousemove response softness
mX = 0, // Real mouse position
mX2 = 0, // Modified mouse position
posX = 0,
mmAA = galW - (mPadd * 2), // The mousemove available area
mmAAr = (galW / mmAA); // get available mousemove fidderence ratio
$gal.mousemove(function(e) {
mX = e.pageX - $(this).offset().left;
mX2 = Math.min(Math.max(0, mX - mPadd), mmAA) * mmAAr;
});
setInterval(function() {
posX += (mX2 - posX) / damp; // zeno's paradox equation "catching delay"
$gal.scrollLeft(posX * wDiff);
}, 10);
});
});
#parent {
position: relative;
margin: 0 auto;
width: 60%;
height: 260px;
}
#propertyThumbnails {
position: relative;
overflow: hidden;
background: #444;
width: 100%;
height: 262px;
white-space: nowrap;
}
#propertyThumbnails img {
vertical-align: middle;
height: 100%;
display: inline;
margin-left: -4px;
}
<div id="parent">
<div id="propertyThumbnails">
<img src="//placehold.it/600x400/0bf" />
<img src="//placehold.it/600x400/f0b" />
<img src="//placehold.it/600x400/0fb" />
<img src="//placehold.it/600x400/b0f" />
<img src="//placehold.it/600x400/bf0" />
</div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
where mPadd is the area (in PX, at the left and right border zone) without any sensitivity to prevent user frustrations :)
this should at least get you headed in the right direction.
var parent = $('#parent');
var img = $('img:first-child');
parent.on('mousemove', function(e) {
mouseX = e.pageX
img.css('margin-left',-mouseX/parent.width()*100);
});
http://jsfiddle.net/xWcXt/4/