coder coder - 4 months ago 8
Javascript Question

how to write a single jquery function for different ids

here is my jquery code i want to work with different ids but same function. now in my coding same function/code is being repeated with every different id , but i want to make a single function for all different ids to reduce the code . how can i do this ?



/$(function(){
//
// $('a[href^="#"') .click(function(e){
// var target = $(this).attr('href');
// var strip = target.slice(1);
// var anchor = $ ("a[name='" + strip +"']");
// e.preventDefault();
// $('html,body').animate({
// scrollTop: anchor.offset().top
// },(3000));
// });
//});
$("#get").click(function(){
$('html, body').animate({
scrollTop: $("#getto").offset().top
}, 2000);
});

$("#features").click(function() {
$('html, body').animate({
scrollTop: $("#featuresto").offset().top
}, 2000);
});
1
//$("#myElement").offset({left:34,top:100});

$("#portfolio ").click(function() {
$('html, body').animate({
scrollTop: $("#portfolioto").offset().top
}, 2000);
});

$("#client").click(function() {
$('html, body').animate({
scrollTop: $("#clientto").offset().top
}, 2000);
});

$("#work").click(function() {
$('html, body').animate({
scrollTop: $("#workto").offset().top
}, 2000);
});

$("#contact").click(function() {
$('html, body').animate({
scrollTop: $("#contactto").offset().top
}, 2000);
});



jQuery(document).ready(function($) {
$(window).scroll(function () {
if ($(window).scrollTop() >= 100) {
$(".header").addClass("navbar-fixed-top");
}
else{
$(".header").removeClass("navbar-fixed-top");
}
});
});


jQuery(document).ready(function($) {
$(window).scroll(function () {
if ($(window).scrollTop() >= 200) {
$(".gototop").addClass("appare");
}
else{
$(".gototop").removeClass("appare");
}
});
});




Answer

You can use seperate selectors together by seperating them with comma. Inside the event handler, use this to access the element that the event was fired for.

$("#get,#features,#portfolio,#client,#work,#contact").click(function() {
  $('html, body').animate({
    scrollTop: $("#" + $(this).attr("id") + "to").offset().top
  }, 2000);
});
div {
  margin-top: 400px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="get">Get</button>
<button id="features">Features</button>
<button id="portfolio">Portfolio</button>
<button id="client">Client</button>
<button id="work">Work</button>
<button id="contact">Contact</button>


<div id="getto">Get</div>
<div id="featuresto">Features</div>
<div id="portfolioto">Portfolio</div>
<div id="clientto">Client</div>
<div id="workto">Work</div>
<div id="contactto">Contact</div>