Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add click event to all 'a' tags in main menu

$(document).ready(function () {
            $("#MainMenu a").click(function () {
                $("#divContent").load( ???? );
            });
        });

I want to retrieve all links from my main menu, attach click events to them, and tell jQuery to load some content to #divContent via ajax call. Content location should depend ofcourse on href tag in each link.

like image 922
apocalypse Avatar asked Dec 25 '22 20:12

apocalypse


2 Answers

You are almost there, Try:

 $("#MainMenu a").click(function (e) {
     e.preventDefault(); //prevent the default click behavior of the anchor.
     $("#divContent").load(this.href); //just get the href of the anchor tag and feed it onto load.
 });
like image 188
PSL Avatar answered Dec 28 '22 10:12

PSL


If you're looking for performance as well and you have a large list of options the best approach would be:

$(document).ready(function () {

     $('#MainMenu').on('click', 'a', function (e) {
         e.preventDefault();
         var $a = $(this);
         $("#divContent").load($a.prop('href'));
     });

});
like image 38
Meryovi Avatar answered Dec 28 '22 10:12

Meryovi