Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Find element's index and add class to current element

Hello,

I'm using owl carousel sync to create my custom gallery . I have all galleries set up, But I'm having issue to scroll to the current item.

Example. http://ocestudio.com/owl-slider-sync/gallery.html This is my gallery landing page, when you click on any image it'll take you to it's specific page and add a class .here to the bottom thumbnails.

As you can see in this example http://ocestudio.com/owl-slider-sync/single-gallery-1.html

Basically what I want to do is when I click on an image I want to scroll to it's position on the bottom carousel

Not sure is that makes sense or if anyone has done this before. I've tried different ways to do this, but no luck.

Please any help will be appreciated

you can download the files

https://www.dropbox.com/sh/fm5oiwlse4jidrc/AAAM8kQDt8BWuH1pOO99gbOba?dl=0

This is my js

$(document).ready(function() {

                var sync1 = $("#sync1");
                var sync2 = $("#sync2");

                sync1.owlCarousel({
                    items : 1,
                    singleItem : true,
                    slideSpeed : 200,
                    navigation: false,
                    pagination:false,
                    autoWdth: true,
                    //afterAction : syncPosition,
                    responsiveRefreshRate : 200,
                    transitionStyle : "fade"
                });

                sync2.owlCarousel({
                    items : 3,
                    mouseDrag: false,
                    responsiveRefreshRate : 10

                });



                var flag = false;
                var slides = sync1.owlCarousel({
                    margin: 10,
                    items: 1,
                    nav:true
                }).on('change.owl.carousel', function(e) {
                    if (e.namespace && e.property.name === 'position' && !flag) {
                        flag = true;    //thumbs.to(e.relatedTarget.relative(e.property.value), 300, true);
                        flag = false;
                    }
                }).data('owl.carousel');



                var thumbs = sync2.owlCarousel({
                    items:4,
                    nav:false
                }).on('click', '.item', function(e) {
                    e.preventDefault();     sync1.trigger('to.owl.carousel', [$(e.target).parents('.owl-item').index(), 300, true]);
                }).on('change.owl.carousel', function(e) {
                    if (e.namespace && e.property.name === 'position' && !flag) {
                    }
                }).data('owl.carousel');



                var patientsActiveSlide = $('.slider.patients .here').index();
                var patientSlider = $('.slider.patients');
                patientSlider.owlCarousel({
                    items : 6, //10 items above 1000px browser width
                    margin: 30,
                    nav: true,
                    startPosition: patientsActiveSlide - 1,
                    dots: true,
                    slideBy: 8,
                    navText: '',
                    responsive: {

                        0: {
                            items: 5,
                            margin: 5,
                            slideBy: 5
                        },
                        576: {
                            items: 5,
                            slideBy: 5,
                            margin: 20
                        },
                        1024: {
                            items: 8,
                            slideBy: 8,
                            margin: 20
                        }

                    }
                });

                //add class here to first thumbnail, and then add/remove on clicks
                $('.thumbnails .owl-item').eq(0).addClass('here');
                $('.thumbnails .owl-item').on('click', function(){
                    $('.thumbnails .owl-item.here').removeClass('here');
                    $(this).addClass('here');
                });

                if($(window).width() > 1024){
                    console.log($('#gallery .owl-item').length);
                    if($('#gallery .item').length <= 8){
                        $('#gallery .owl-controls').hide();
                    } else {
                        $('#gallery').next().find('.btn').addClass('custom');
                    }
                }

                //Find url

                var pgurl = window.location.href.substr(window.location.href
                    .lastIndexOf("/")+1);
                $("#gallery a").each(function(){
                    if($(this).attr("href") == pgurl || $(this).attr("href") == '' )
                        $(this).parent('.item').addClass("here");
                })
            });

3 Answers

Do you mean, that you want to store somewhere JS variable with selector? You have a lot opportunity like Hashtags, Cookies, LocalStorage and so on. It depend on your task goals and so on. Do you have some technical limitation to not to surf from url to url and use AJAX?

Tell me more about your task, please.

Each time you reload URL browser updating the local "scope". You can not keep "var name". All variables are throw away and the thing you want to do is calling, as option, "persist javascript variables".

If you change URL on the same tab of your browser you can keep your data (or object, or sting, whatever) on browser "window" object. It can be something like

window.myNewUniqUrlFromPastPage = "#blah-bla-blah";

But it's bad practice. Check this out. Start this path and look at localStorage I've mentioned before.

Hello Daniel,

Thanks for the reply.

I don't have any technical limitation. I surf from url to url because I needed to select specific element on the page, so using the url seemed to be the best option. I added an script to find and match the element based on it's url and add class ".here" to the parent element which is ".item " it works fine, but unfortunately it doesn't scrolling to start position, it just adds the class ".here". However when I add the class ".here" manually to the parent element ".item" it works. It scrolls to start position.

<!-- Thumbs from gallery.html -->

        <section id="gallery">
            <div class="container">

                <div class="slider patients">

                    <div class="item">
                        <a href="single-gallery-1.html">
                            <img src="https://placehold.it/250x250">
                        </a>
                    </div><!-- item -->

                    <div class="item">
                        <a href="single-gallery-2.html">
                            <img src="https://placehold.it/250x250">
                        </a>
                    </div><!-- item -->

                    <div class="item">
                        <a href="single-gallery-3.html">
                            <img src="https://placehold.it/250x250">
                        </a>
                    </div><!-- item -->
                                        // Manually added class
                    **<div class="item here">**
                        <a href="single-gallery-4.html">
                            <img src="https://placehold.it/250x250">
                        </a>
                    </div><!-- item -->

                    <div class="item">
                        <a href="single-gallery-5.html">
                            <img src="https://placehold.it/250x250">
                        </a>
                    </div><!-- item -->

                    <div class="item">
                        <a href="single-gallery-6.html">
                            <img src="https://placehold.it/250x250">
                        </a>
                    </div><!-- item -->

                    <div class="item">
                        <a href="single-gallery-7.html">
                            <img src="https://placehold.it/250x250">
                        </a>
                    </div><!-- item -->

                    <div class="item">
                        <a href="single-gallery-8.html">
                            <img src="https://placehold.it/250x250">
                        </a>
                    </div><!-- item -->

                    <div class="item">
                        <a href="single-gallery-9.html">
                            <img src="https://placehold.it/250x250">
                        </a>
                    </div><!-- item -->

                    <div class="item">
                        <a href="single-gallery-10.html">
                            <img src="https://placehold.it/250x250">
                        </a>
                    </div><!-- item -->

                    <div class="item">
                        <a href="single-gallery-11.html">
                            <img src="https://placehold.it/250x250">
                        </a>
                    </div><!-- item -->

                    <div class="item">
                        <a href="single-gallery-12.html">
                            <img src="https://placehold.it/250x250">
                        </a>
                    </div><!-- item -->

                </div><!-- slider -->
            </div><!-- container -->
        </section><!-- gallery -->

So I think my script it's not reading the element's index. http://ocestudio.com/owl-slider-sync/gallery.html

This piece of code its where Im storing the clicked element index

var patientsActiveSlide = $('.slider.patients .here').index();

This is a owl carousel option, so it will scroll by 1 based on the index.

startPosition: patientsActiveSlide - 1

For example if I clicked on the third Item, it will scroll to two and third, if I clicked on the fourth, it will scroll to third and fourth and so on.

                var patientsActiveSlide = $('.slider.patients .here').index();
                var patientSlider = $('.slider.patients');
                patientSlider.owlCarousel({
                    items : 6, //10 items above 1000px browser width
                    margin: 30,
                    nav: true,
                    startPosition: patientsActiveSlide - 1,
                    dots: true,
                    slideBy: 8,
                    navText: '',
                    responsive: {

                        0: {
                            items: 5,
                            margin: 5,
                            slideBy: 5
                        },
                        576: {
                            items: 5,
                            slideBy: 5,
                            margin: 20
                        },
                        1024: {
                            items: 8,
                            slideBy: 8,
                            margin: 20
                        }

                    }
                });