Tomer Lichtash
Tomer Lichtash

Reputation: 9262

How to set an onClick attribute that would load dynamic content?

This code is suppose to add an onClick event to each of the a elements, so that clicking on the element would load the content of the page dynamically into a DIV.

Now, I got this far - It will add the onClick event, but how can I load the dynamic content?

$(document.body).ready(function () {
  $("li.cat-item a").each(function (i) {
      this.setAttribute('onclick','alert("[load content dynamically into #preview]")');
  });
});

Thank you.

Upvotes: 0

Views: 2299

Answers (4)

Glenn Jorde
Glenn Jorde

Reputation: 580

$(document.body).ready(function () {
  $("li.cat-item a").click(function (e) {
      $('#this-is-your-target-div').load(this.href);
      e.preventDefault();
  });
});

See the documentation for jQuery ajax functions here: http://api.jquery.com/category/ajax/.

Upvotes: 4

Jan Jongboom
Jan Jongboom

Reputation: 27322

$("li.cat-item a").click(function() {
    $.get($(this).attr('href'), function(data) {
        $("#preview").html(data);
    });
});

Does an AJAX request using $.get which is more easier to read imho to the href attribute of the clicked element, and puts the retrieved data into the div preview.

Upvotes: 1

Matt
Matt

Reputation: 75317

$(document).ready(function () {
  $('li.cat-item a').bind('click', function (e) {
    $('#preview').load($(this).attr('href'));

    e.preventDefault();
  });
});

There is an extensive amount of AJAX functions in jQuery: http://api.jquery.com/category/ajax

Upvotes: 1

o15a3d4l11s2
o15a3d4l11s2

Reputation: 4059

Use $('div.container').html(htmlString);

where htmlString is the html code of the content you want to place inside the div with class container

Upvotes: 0

Related Questions