Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

113
Views
How to trigger click event of anchor tag via jQuery for dynamic data?

Trying to trigger click event of a tag with jQuery but the event is linked with data set by $.getJSON in a section.

Following is the code of HTML:

...

const page=1, dataList=[];
$.getJSON('https://api.punkapi.com/v2/beers?page=' + page + '&per_page=25', function (beerList) {
        console.log(beerList)
        dataList.push(beerList);
        currentElements = renderFuntion(beerList);
        $('#dynamicData').html(currentElements);
    });

 function renderFuntion(data) {
    var temp = '';
    data.forEach(element => {
        var item = `
        <div class="card col-xs-12 col-lg-4 my-2">
            <div class="card-body">
                   <figure> <img src=${element.image_url} class="img-fluid" alt=${element.name}></figure>
            <article class="ms-3">
                    <h5 class="card-title">${element.name}</h5>
                    <p class="card-text">${element.description.length > 220 ? element.description.substring(0, 220) + '...' : element.description}</p>
            </article>
<!--- This is what's suppose to give the event on click. --->
            <a href="javascript:void(0)"  id=${element.id}> <i class="fa fa-star-o usericon mt-3"></i></a>
            </div>
        </div>`
        temp += item;
    });
    return temp;
}

//this is what's not working
 $('.card a').click(function () {
    var usersid = $(this).attr("id");
    favouritesList.push(usersid);
    console.log(favouritesList);

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.js"></script>
<section class="my-3 g-0" id="dynamicData">
</section>

Please do guide if possible. Thanks.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Your code isn't working because your element isn't loaded with the page, so when jQuery runs $('.card a').click(function..., $('.card a') returns null, so the listener is not attached.

Add your listener to the document like so:

$(document).on("click", ".card a", function() { ... })

When the user clicks on the document, jQuery will check if $(".card a") is the target, even if added after the page was initially loaded, and will execute your function if it is.

about 4 years ago · Juan Pablo Isaza Report

0

As @will already pointed out: it is a timing problem. In your code the click event was attached before the contents form your $.getJSON() arrives. By using a delegated event attachment you can solve the problem:

const page=1, dataList=[], favouritesList=[];
$.getJSON('https://api.punkapi.com/v2/beers?page=' + page + '&per_page=25', function (beerList) {
        // console.log(beerList)
        dataList.push(beerList);
        currentElements = renderFuntion(beerList);
        $('#dynamicData').html(currentElements);
    });

 function renderFuntion(data) {
    var temp = '';
    data.forEach(element => {
        var item = `
        <div class="card col-xs-12 col-lg-4 my-2">
            <div class="card-body">
                   <figure> <img src=${element.image_url} class="img-fluid" alt=${element.name}></figure>
            <article class="ms-3">
                    <h5 class="card-title">${element.name}</h5>
                    <p class="card-text">${element.description.length > 220 ? element.description.substring(0, 220) + '...' : element.description}</p>
            </article>
<!--- This is what's suppose to give the event on click. --->
            <a href="javascript:void(0)"  id=${element.id}> <i class="fa fa-star-o usericon mt-3">click me</i></a>
            </div>
        </div>`
        temp += item;
    });
    return temp;
}

//this is now working:
 $('section').on("click",".card a",function () {
    favouritesList.push($(this).attr("id"));
    console.log(favouritesList);

});
.img-fluid {height:80px}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.js"></script>
<section class="my-3 g-0" id="dynamicData">
</section>

about 4 years ago · Juan Pablo Isaza Report

0

ajaxComplete also solve your problem.

$(document).ajaxComplete(function () {
    $('.card a').click(function () {
        const favouritesList = [];
        let usersId = $(this).attr("id");
        favouritesList.push(usersId);
        console.log(favouritesList);
    })
})
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!