Alex Alex - 4 months ago 12
jQuery Question

Carousel/slider select to load main image

I am working on a website for a friend, and I have come across a strange problem. The template uses an owl carousel, basically your run of the mill slider, however I also wanted to have the it so that when the user clicks on a carousel image it replaces the main image above. I worked out the following code, however it only works in the intended manner after selecting the 2nd image in the carousel, then the first image. Its as though the main image doesn't get the

property until after doing this sequence.

You can see the example on:


<script type="text/javascript">
jQuery(function () {
// gallery setup
var Img='.'+$(".gallery_image img#active").attr('class')
$("#owl-related-works a").click(function(){
var ImgId = '.'+$(this).attr("href").slice(1);
if (ImgId!=Img) {
return false;


<?php } elseif ($type = 'Photography') { ?>
<section class="related-projects pb-90">
<div class="container">
<h4 class="heading-inline"><?php echo $name . ' Gallery'; ?></h4>
<div class="customNavigation right">
<a class="btn prev"><i class="fa fa-angle-left"></i></a>
<a class="btn next"><i class="fa fa-angle-right"></i></a>
<div class="row mt-20">
<div id="owl-related-works" class="owl-carousel owl-theme">

<?php $counter = 1; foreach ($imagesArr as $image) { ?>
<div class="work-item">
<div class="work-container">
<div class="work-img">
<a href="#img<?php echo $counter++; ?>"><img src="<?php echo $images_core->prepLocation . $image ?>" alt="<?php echo $name; ?>"></a>
<?php } ?>


<? } ?>

Main Image:

<div id="gallery_image">

<?php $counter = 1; foreach ($imagesArr as $image) { ?>
<img src="<?php echo $images_core->prepLocation . $image ?>" alt="<?php echo $name; ?>" <?php echo $counter > 1 ? 'style="display:none;" ' : 'style="display:block;" id="active" '; ?> class="img<?php echo $counter++;?>">
<?php } ?>


Can you please create a codepen or jsbin with an example? I would be happy to help you :)

generally, it would be best if you used jquery callbacks to replace the image src on the big image. But it will be a lot easier to explain if we had a proper jsbin.

In theory, the script needs to be far simpler, you can attach the onclick listener to all the small images. It will steal the href or data-attribute value from the clicked div. It will fadeout the current image, as a callback it will replace the src and fadein the element. And that is all there is to it.