3

I have sidebar which contains a lot of titles. I don't want to write for all of them a function. Here is a code for one :

$("#menu_documentations").click(function () {
$("#sites").load("documentations/documentations_doc.php");
$("html, body").animate({ scrollTop: 0 }, "slow");
return false;
 });

The sidebar's id always look like "#menu_xyz" and the loading php using the same "xyz_doc.php".

How can I avoid to write one by one ?!

Rickley14
  • 45
  • 7

2 Answers2

3

use a class and a data attribute for the url html:

<a class="load-ajax" href="#" data-url="coustom-page-name.html">Link</a>

or

<a class="load-ajax" href="coustom-page-name.html">Link</a>

js:

$(".load-ajax").click(function () {
var url = $(this).attr('data-url');//$(this).attr('href');
$("#sites").load(url);
$("html, body").animate({ scrollTop: 0 }, "slow");
return false;
 });
madalinivascu
  • 32,064
  • 4
  • 39
  • 55
0

The below would work (same as madalin's except I would just use the data attribute itself to target the elements rather than adding another class):

HTML:

 <button data-get-page="documentations/documentations_doc.php">click me </button>

JS:

$(document).on('click','[data-get-page]',function() {
  var $this=$(this);
  var url=$this.data('get-page');
  $("#sites").load(url);
  $("html, body").animate({
    scrollTop: 0
  }, "slow");
  return false;
});
Wesley Smith
  • 19,401
  • 22
  • 85
  • 133