user1709407
user1709407

Reputation: 41

Javascript click function inside a loop

im not so good with javascript but i have searched for 5 hours now and no luck.

Im trying to make buttons work, if i write the code one-by-one it works fine and everthing is OK.

I can understand the problem. The click part only works when the CLICK is actualy made. Am i right? but how to i corret so it would work like i need?

Can i send the $(name) value to click function so when my lets say button-1 is clicked then scrollTop: $(button-1-block) or am i over thinking in this case.

    var divHeight = 700
    var blocks = document.getElementsByClassName("blocks");
    var i = 1;

    for(i=1;i<blocks.length+1; i++) {
        var name = "#button-"+i;
        var blx = "#block-"+i;
        $(name).click(function(){
            $('html, body').stop().animate({
                scrollTop: $(blx).offset().top - ( $(window).height() - divHeight )/2 
              }, 2100,'easeInOutExpo');
         });

    }

Upvotes: 1

Views: 182

Answers (1)

Ram
Ram

Reputation: 144669

Try this:

var divHeight = 700
//var blocks = $(".blocks");

$('[id^="button"]').click(function(){
     var block = '#block-' + this.id.match(/\d+/g).join("");
     $('html, body').stop().animate({
          scrollTop: $(block).offset().top - ( $(window).height() - divHeight )/2 
     }, 2100,'easeInOutExpo');
});

Upvotes: 2

Related Questions