javascript - how to write a single jquery function for different ids -
here jquery code want work different ids same function. in coding same function/code being repeated every different id , want make single function different ids reduce code . how can ?
/$(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"); } }); });
you can use seperate selectors seperating them comma
. inside event handler, use this
access element event 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>
Comments
Post a Comment