I have a list (menu). When user clicks on link, I want to load content with ajax. The article to be loaded is to be determined based on the links id attribute.
example:
<ul class="ajaxMenu">
<li><a id="services">Services</a>
...
</u>
the variables where I store the links to the article, are named the same as the links’ id (i.e. Services and the url for the ajax call is stored on var services)
This works:
var services = "index.php?option=com_content&view=article&id=2&tmpl=component";
jQuery(".ajaxMenu > li > a ").click(
function(event) {
jQuery("#contentComponent").load(services);
}
);
Since this line of code jQuery(this).attr(“id”) gives me id, I was hoping this would work [it did not work]:
var services = "index.php?option=com_content&view=article&id=2&tmpl=component";
var designs = "index.php?option=com_content&view=article&id=3&tmpl=component";
var contact = "index.php?option=com_content&view=article&id=2&tmpl=component";
jQuery(".ajaxMenu > li > a ").click(
function(event) {
jQuery("#contentComponent").load(jQuery(this).attr("id"));
}
);
I could create an if, or a loop, iterate through each var, (i.e. if jQuery(this).attr(“id”) == “services”…load(services))
but I suspect I can achieve this with simple elegant code.
How could I translate jQuery(this).attr(“id”) into the .load() function without having to if, loop, etc., the value of jQuery(this).attr(“id”) against the named variables where I stored the urls to be loaded?
I would firstly put href attributes into your links as it seems like a really good place to put them.
And then in the click handler, do the load call using the href attribute. And don’t forget to call
preventDefaultto stop the click from actually reloading the entire page.