Pass dynamic id value to jquery div go to function

I am stuck jumping jquery div to the problem. The problem is I am creating a dynamic <a href="" id="1_1"></a>

and dynamic div also say <div id="1_1_div"></div>

I am using the following jquery function to scroll to a specific div

<script>
        $(document).ready(function (){
            $("#click").click(function (){
                alert ("test");
                //$(this).animate(function(){
                    $('html, body').animate({
                        scrollTop: $("#div1").offset().top
                    }, 1000);
                //});
            });
        });
    </script>

      

My question is how to pass a dynamic id to $("")

. Any help would be much appreciated.

+1


source to share


4 answers


$(document).ready(function (){
        $(".click").click(function (){
            alert ("test");
            var divID = '#' + $(this).attr('id') + '_div';
                $('html, body').animate({
                    scrollTop: $(divID).offset().top
                }, 1000);
        });
    });

      



And add <a class="click" ...

+1


source


String concatenation:

$("#" + this.id + "_div").offset().top

      

Note that there is no need to create unique IDs, DOM duo provides many different methods to move and select target elements to create a tree structure.



Since you are generating elements dynamically you must delegate events as well, you can add classes to your elements and use the method on

:

$('#aStaticParentElement').on('click', '.anchors', function() {
   // TODO:
   // select the target element either by traversing 
   // or by using an identifier
});

      

+2


source


Visualize it here

First, since you have multiple links, use a class to group them:

Html

<a href="#" id="1_1" class="click">Click me 1_1</a>
<a href="#" id="1_2" class="click">Click me 1_2</a>    
<a href="#" id="1_3" class="click">Click me 1_3</a>

      

JQuery

$(document).on('click', '.click', function (e) {
    var theID = $(this).attr('id');
    $('html, body').animate({
        scrollTop: $('#' + theID + '_div').offset().top
    }, 1000);
    return false;
});

      

I did this with the slight assumption that you were creating these links dynamically (hence the delegation). If they are static and will not change during page load, you can use $('.click').click(function()...

instead$(document).on('click', '.click', function()...

+1


source


User of this line

$("#" + $(this).attr("id") + "_div").offset().top

      

...

0


source







All Articles