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

1
  • 1
    use a class and a data attribute for the url Commented Sep 9, 2016 at 11:33

2 Answers 2

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;
 });
Sign up to request clarification or add additional context in comments.

3 Comments

dont forget the event.preventDefalt() if we use an a tag.
Ah, honestly I'm so used to preventDefault() I didnt even notice the return false :)
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;
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.