Ricky Bailey
Ricky Bailey

Reputation: 133

Scroll to content in jQuery

I have a 2-column layout with tabbed content on desktop. However, on mobile the second column displays below the first column. When clicking the tabs, you can't see the second column and therefore can't see what content is changing.

Is there a way using the following code I can get it to scroll down to the second column on clicking each tab?

HMTL:

<div class="video-carousel">
    <div class="video-titles">
        <div class="video-title">
            <h4>Video Title 1</h4>
        </div>
        <div class="video-title">
            <h4>Video Title 2</h4>
        </div>
        <div class="video-title">
            <h4>Video Title 3</h4>
        </div>
    </div>
    <div class="video-contents">
        <div class="video-content">
            FIRST VIDEO HERE
        </div>
        <div class="video-content">
            SECOND VIDEO HERE
        </div>
        <div class="video-content">
            THIRD VIDEO HERE
        </div>
    </div>
</div>

jQuery:

"use strict";
jQuery(document).ready(function($) {
    $('.video-title').click(function() {
        $('.video-title').removeClass('highlighted');
        var index = $(this).addClass('highlighted').index();
        $('.video-content').hide().eq(index).show();
    });
});

Upvotes: 1

Views: 690

Answers (2)

lennert_h
lennert_h

Reputation: 213

I addthis little function:

jQuery.scrollTo = function scrollTo(place,speed) {
    $('html, body').animate({
        scrollTop: $(place).offset().top
    }, speed);
}

Then when clicking:

 $('.video-title').click(function() {
   //highlights etc.
  $.scrollTo('.video-contents',1500);
}

Edit: just found the link, I got this code via this question

Upvotes: 0

Jeff Huijsmans
Jeff Huijsmans

Reputation: 1418

See this question: jQuery scroll to element

You could add the code to the $('.video-title').click(function() { ... }. If you could provide a fiddle or something reproducible, I could help you with the actual code.

If the scroll code is executed without the need to scroll, it should do nothing. If it does something you don't want, like scroll a few pixels on desktop, you could optionally write code/css to avoid that.

Upvotes: 2

Related Questions