How to scroll through an element that has a dynamic id using jquery
I made this function in a static way, but how can I do this scrolling with jquery so that it scrolls smoothly to the specific element that I added dynamically.
var data = [{"name": "Aruba", "code": "A"},{"name": "AndorrA", "code": "A"},{"name": "Bhutan", "code": "B"},{"name": "Bolivia", "code": "B"}]
var num=0;
$.each(data, function(key, val) {
if (!$("#aZContent ul." + val.code).is("*")) {
$("<ul />", {"class": val.code,"html": "<li>"+ val.name + "</li>"}).appendTo("#aZContent").before('<b class=' + val.code + ' id="letter_' + num++ + '">' + val.code + '</a></b>');
} else {
$("b." + val.code).each(function() {
if (this.textContent === val.code) {
$(this).next("ul").append("<li>" + val.name + "</li>");
}
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="alphabet" id="alphaTab">
<a href="#letter_0">A</a>
<a href="#letter_1">B</a>
</div>
<div id="aZContent">
<ul></ul>
</div>
<div style="height:500px"></div>
When clicking link "A" it should scroll to "A" and also
source to share
Some answers have already been given. Hope this helps you.
pass dynamic id value to jquery div go to function
source to share
In my application, I have a button that adds field shapes to the body every time the button is clicked. I wanted to scroll the page to a new element, but that didn't work due to the bubbling restrictions and event binding of jQuery scroll functions. I came up with a simple solution ...
function scroll(pixels){
$('html, body').animate({
scrollTop: pixels
}, 1000);
};
function addObservation(x){
$('body').append(x);
newFieldSet = $('fieldset').last();
pixelsFromTop = newFieldSet.offset().top;
scroll(pixelsFromTop);
};
$(document).on("click", "#add_observation", function(){
addObservation("<fieldset>SOME FORM FIELDS HERE</fieldset>");
});
This way, every time you add the fieldset, jQuery finds the last one, then .offset().top
measures how many pixels the fieldset has on top, and then smoothly scrolls the window whose distance is
source to share
I haven't received your application. But it should be simple.
You say the IDs are "dynamic", which means there will be items dynamically generated and corresponding buttons / links.
Now all you have to do is ...
let's say that the calss of the links .linksy
.
jQuery(".linksy").on('click', function(){
e.preventDefault();
$id = jQuery(this).attr('href');
$('body').scrollTo('#' + $id);
});
source to share