crowley
crowley

Reputation: 11

How can i do shorten my code with jquery?

 <div class="logo-contentBlock"> 
   <a href="#logo-first-content" class="content-page-scroll-1">BLOG</a>
 </div>

 <div id="#logo-first-content"></div>




    $(".content-page-scroll-1").click(function() {
        $('html, body').animate({
            scrollTop: $('#content-first-content').offset().top - 60
        },5000);
    });
    $(".content-page-scroll-2").click(function() {
        $('html, body').animate({
            scrollTop: $('#content-second-content').offset().top - 60
        }, 5000);
    });
    $(".content-page-scroll-3").click(function() {
        $('html, body').animate({
            scrollTop: $('#logo-thirt-content').offset().top - 60
        }, 5000);
    });

I have about 9 codes like this way. How can I shorten them? Clicking buttons, they all go to different div.

Upvotes: 0

Views: 85

Answers (3)

user11113880
user11113880

Reputation: 73

In php:

<script>
<?php
for ($x=1; $x<9; $x++){
echo '$(".content-page-scroll-'.$x.'").click(function() {
        $(\'html, body\').animate({
            scrollTop: $(\'#content-'.$x.'-content\').offset().top - 60
        },5000);
    });';
}
?>
</script>

Upvotes: 0

Kamal Kant
Kamal Kant

Reputation: 1130

This will be my purposed solution for the above problem.

<div class="content-page-scroll" data-id="content-first-content"></div>
<div class="content-page-scroll" data-id="content-second-content"></div>
<div class="content-page-scroll" data-id="content-third-content"></div>
            .
            .
            .
<div class="content-page-scroll" data-id="content-n-content"></div>

Here the JS code for the click event.

$(".content-page-scroll").click(function () {
$thisDataId = $(this).data('id');
$('html, body').animate({
      scrollTop: $(`#${$thisDataId}`).offset().top - 60
     }, 5000);
});

In this way, you sum up this problem with a single JS click event. Hopefully it may help you to resolve this issue.

Upvotes: 3

kshetline
kshetline

Reputation: 13682

I'd create a function like this:

function createScrollClick(elem, location) {
    $(elem).click(function() {
        $('html, body').animate({
            scrollTop: $(location).offset().top - 60
        },5000);
    });
}

Then either call it the nine times you need to call it for each click you want to set up:

createScrollClick('.content-page-scroll-1', '#content-first-content''), etc.

...or you could put all of those values in an array or object and loop through those values calling the function.

Upvotes: 0

Related Questions