1

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');
         });

    }
4
  • 1
    can you share your sample html code? Commented Sep 30, 2012 at 6:54
  • Are you sure blocks.length is not 0? Commented Sep 30, 2012 at 6:55
  • 2
    Well, first of all, you don't need the loop. In jQuery, you use selectors like $('[id^=block-]').click(...) to get all of the elements which start with id="block-#" and end in something else. This you can attach that $.click() to each of the elements in the selected list of elements you found. It's very easy. Commented Sep 30, 2012 at 6:55
  • try something similar to this code stackoverflow.com/questions/8547845/… Commented Sep 30, 2012 at 6:57

1 Answer 1

2

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');
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.