0

Hello I am new to programming so please excuse my ignorance.

I have several elements that when clicked use the ScrollTop jQuery function to scroll to a specified point (in another bootstrap nav-tab). I have about 20 different elements that when clicked do this. I have resorted to writing 20 different functions that look similar to the one below. I'm sure there must be a way to store these pairs and have a single ScrollTop function that calls upon those pairs.

$('#element').click(function(e) {
  e.preventDefault();
  var target = $('#element2').closest('.tab-pane').attr('id');
  showTab(target);
  setTimeout(function() {
    $('html, body, nav').animate({
    scrollTop: $("#element2").offset().top -100
}, 500);
}, 500);
});

So my js file has twenty or so of this function, where "#element" and "#element2" are subbed with "#alpha" "#alpha2", "#beta" "#beta2", etc...

Should I be using an array? a class? Thanks for you time.

Vault Dweller
  • 135
  • 2
  • 10

2 Answers2

1

Try adding the class "element" to each of the items that have an element id followed by a number - no need to remove the id at this time.

Then, change the selector in your code to be:

$('.element').click(function(e) {

If you use the class name instead of the id, you'll get notified when any item with a class of "element" is clicked.

If you need to make special allowances based on which one it is - in your single function, you could then check which one you're dealing with by checking its id:

$(this).attr('id')

Good Luck!

murmeister
  • 582
  • 1
  • 4
  • 7
1

See Working Fiddle Here

Yes you can add same class to all element that you want fire click on them, to reduce code see HTML example :

  • <span class="scrollTop" id="element">element text</span>
  • <span class="scrollTop" id="alpha">alpha text</span>
  • <span class="scrollTop" id="beta">beta text</span>

Adding two lignes to javascript code:

JS :

var id = $(this).attr('id'); //Id of clicked item
var scrollToId = '#'+id+"2"; //Id of scrolled to item
  • After that replace static ids by dynamic ones (scrollToId, id).

FULL JS :

$('.scrollTop').click(function(e) { 
    e.preventDefault(); 

    var id = $(this).attr('id'); //Id of clicked item
    var scrollToId = '#'+id+"2"; //Id of scrolled to item
    var target = $(scrollToId).closest('.tab-pane').attr('id');

    showTab(target);
    setTimeout(function() {
        $('html, body, nav').animate({
            scrollTop: $(scrollToId).offset().top -100
        }, 500);
    });
});
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101