Rickley14 Rickley14 - 2 months ago 10
jQuery Question

How to optimize my loading JQuery function?

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 ?!

Answer

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;
 });