Reputation: 11
<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
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
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
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