Daniel Daniel - 4 years ago 160
jQuery Question

Add dynamic ID to each div, call those later

I have multiple menu generated, but they have different menu items and different positions in my content.

For each '.ff_ftmenu' and '.ff_ftmenu_block' there is a separate ID, so that ffmenu-0 for example would match.

I click '.ff_ftmenu_block #ffmenu-0' and '.ff_ftmenu #ffmenu-0' gets triggered and opens. That’s the idea. But how do I assign the 'ffmenu-' + index' to the loop so just that one will open?

var tl = new TimelineMax({paused:true, reversed:true});
tl
.staggerFromTo('.ff_ftmenu li', 1.5,
{rotationX:-90, transformOrigin:"50% 0%"},
{rotationX:0, ease:Elastic.easeOut}, 0.4);

$('.ff_ftmenu').each(function(index){
$(this).attr('id', 'ffmenu-' + index);
//console.log( this.id );
});

$('.ff_ftmenu_block').each(function(index){
$(this).attr('id', 'ffmenu-' + index);
});

$('.ff_ftmenu_block').each(function(index){
$(this).click(function(index){
$('.swp-col-1-3 .ff_ftmenu').toggleClass('open');

if (!$('.swp-col-1-3 .ff_ftmenu').hasClass('open')) {
TweenMax.to($('.swp-col-1-3 .ff_ftmenu'), 0.5, {opacity: 0});
tl.reversed() ? tl.play() : tl.pause(0).reversed(true);
}
else {
TweenMax.to($('.swp-col-1-3 .ff_ftmenu'), 1, {opacity: 1});
tl.reversed() ? tl.play() : tl.pause(0).reversed(true);
}

});
});

Answer Source

With jQuery in this case to get the element where you clicked on you don't need each. So I think you can replace

$('.ff_ftmenu_block').each(function(index){
$(this).click(function(index){
$('.swp-col-1-3 .ff_ftmenu').toggleClass('open');

  if (!$('.swp-col-1-3 .ff_ftmenu').hasClass('open')) {
    TweenMax.to($('.swp-col-1-3 .ff_ftmenu'), 0.5, {opacity: 0});
    tl.reversed() ? tl.play() : tl.pause(0).reversed(true);
  }
  else {
    TweenMax.to($('.swp-col-1-3 .ff_ftmenu'), 1, {opacity: 1});
    tl.reversed() ? tl.play() : tl.pause(0).reversed(true);
  }

});

with (just to give you a starting - point - idea)

$('.ff_ftmenu_block').on('click', function(){
    console.log($(this).attr('id');
    // move on from here with the id
    // and do whatever you want to do
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download