Rob
Rob

Reputation: 6380

Scroll to div on click of value in select

How can I scroll to a relating div on clicking a value in a select dropdown?

I'm pulling in the service name via Wordpress and filling at the value in the dropdown:

<select>
    <?php if(get_field('services')){ ?>
        <?php while(the_repeater_field('services')):
        $service = get_sub_field('service_name');
        $string = str_replace(' ', '', $service); ?>
            <option value="<?php echo $string; ?>"><?php the_sub_field('service_name'); ?></option>
        <?php endwhile; ?>
    <?php } ?>                                      
</select>

Here's the div's below - which should have matching id's to the value's in the select dropdown above.

<?php if(get_field('services')){ ?>
    <?php while(the_repeater_field('services')):
    $service = get_sub_field('service_name');
    $string = str_replace(' ', '', $service); ?>
        <section class="row service equal" id="<?php echo $string; ?>">
            <div class="columns medium-3">
                <img src="<?php the_sub_field('service_image'); ?>" />
            </div>

            <div class="columns medium-6 flex-center">
                <h3><?php the_sub_field('service_name'); ?></h3>
                <?php the_sub_field('service_description'); ?>
            </div>

            <div class="columns medium-3 flex-center">
                <?php if(get_sub_field('strapline') != "") { ?>
                    <p class="cta-highlight"><span><?php the_sub_field('strapline'); ?></span></p>
                <?php } ?>
                <a class="inner-button" href="<?php the_sub_field('call_to_action_link'); ?>">
                    <?php the_sub_field('call_to_action_text'); ?>  >
                </a>
            </div>
    </section>  
    <?php endwhile; ?>
<?php } ?>

Upvotes: 0

Views: 302

Answers (1)

Tyler Roper
Tyler Roper

Reputation: 21672

Assuming the ID of your select is selectID, you could do something like this:

<script>
  $(document).ready(function() { //When the page loads

    $('#selectID').change(function() { //Initialize "On Select Change" listener
       var val = $(this).val(); //Get the value of the select
       $('html, body').animate({ //Animate the page scroll
         scrollTop: $("#"+val).offset().top //scroll to div with the same ID as the selected value
       }, 2000); //Animation length in MS: 2000 = 2 seconds
    });
  });
</script>

Upvotes: 1

Related Questions