Craig
Craig

Reputation: 195

How to add an ID in Jquery?

I have set up a page with modal's but at the moment it only works with having one modal on the page.

What I would like to achieve is apply id in the Jquery so each modal has it's own ID and opens with multiple modals.

HTML:

<a class="activator1" id="activator1"><img class="edit_icon" align="right" src="/images/edit_icon.png" alt="">Edit</a>
<div class="box1" id="box1">
    <h3>Title here</h3>
    <p>Text in here</p>
</div>`
<a class="activator2" id="activator2"><img class="edit_icon" align="right" src="/images/edit_icon.png" alt="">Edit</a>
<div class="box2" id="box2">
    <h3>Title here</h3>
    <p>Text in here</p>
</div>

Jquery

$(function(){
    $('#activator').click(function(){
        $('#overlay').fadeIn('fast',function(){
            $('#box').animate({'top':'80px'},500);
        });
    });
    $('#boxclose').click(function(){
        $('#box').animate({'top':'-1400px'},500,function(){
            $('#overlay').fadeOut('fast');
        });
    });
});

Upvotes: 0

Views: 37

Answers (1)

charlietfl
charlietfl

Reputation: 171669

Don't use unique classes, keep them common for common elements. Use secondary classes if needed for styling

A simple data attribute can be used for the target and can be read using data() method

<a class="activator" id="activator1" data-target="#box1>

Then use class for click handler selector

$('.activator').click(function(){
   // "this" is element event occurred on
   var modalTargetSelector = $(this).data('target');
   $('#overlay').fadeIn('fast',function(){
        $(modalTargetSelector ).animate({'top':'80px'},500);
   });

});

Similarly for close buttons use common class and do something like:

 $('.boxclose').click(function(){
    $(this).closest('.box').animate({'top':'-1400px'},500,function(){
        $('#overlay').fadeOut('fast');
    });
});

Upvotes: 1

Related Questions