Reputation: 11
<div class="logo-contentBlock">
<a href="#logo-first-content" class="content-page-scroll-1">BLOG</a>
</div>
<div class="logo-contentBlock">
<a href="#logo-second-content" class="content-page-scroll-2">BLOG</a>
</div>
.
.
.
<div id="#logo-first-content">.....</div>
<div id="#logo-second-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);
});
Hello, ı just want scrolltop 60 but ı have 9 content like that that means a lot of jquery. How can i do shorten my code with jquery?
Upvotes: 0
Views: 35
Reputation: 2255
The thing to notice here is that the only thing changing between the callbacks is the CSS-selector. To stay DRY here, I would define a function that takes a CSS-selector and returns the click-handler.
Working off your example, for example like so:
const cbFactory = selector => () => {
$('html, body').animate({
scrollTop: $(selector).offset().top - 60
},5000);
};
$(".content-page-scroll-1").click(cbFactory('#content-first-content'));
$(".content-page-scroll-2").click(cbFactory('#content-second-content'));
$(".content-page-scroll-3").click(cbFactory('#logo-thirt-content'));
Upvotes: 1