If you want to dynamically load content on demand, jQuery's ajax feature is the way to go. The load
method comes in handy for this purpose.
It seems like there might be some confusion between jQuery and ajax. jQuery is essentially a javascript library that simplifies tasks for us. While ajax can still be used without jQuery, incorporating jQuery certainly makes things easier for us.
Assuming you have a setup similar to this in your main page, where links are displayed in one div and their corresponding content is shown in another:
<div class="divNavigation">
<a href="about.html" class="ajaxLink">About</a>
<a href="about.contact" class="ajaxLink">Contact</a>
<a href="about.team" class="ajaxLink">Team</a>
</div>
<div id="divContentArea">
</div>
To asynchronously load the target content upon clicking a link and display it in the designated div area, add the following JavaScript:
<script type="text/javascript">
$(function(){
$("a.ajaxLink").click(function(e){
e.preventDefault();
var linkTargetUrl=$(this).attr("href");
$("#divContentArea").load(linkTargetUrl);
});
});
</script>
What's Happening Here?
#1 : We are binding the click event of all anchor tags with the css class name `ajaxLink` to trigger our specified action upon user interaction.
To select elements by class name, utilize `$(".className")`. In our case, we're instructing jQuery to target all anchor tags with the given class name.
To select an element by ID, employ `$("#elementID")`, where `elementID` represents the ID attribute of the element.
For more details on jQuery selectors, refer to the documentation here.
#2 : We are loading the content asynchronously without redirecting the page to the destination URL. By utilizing the `preventDefault` method from jQuery, we prevent the default behavior associated with clicking a link.
#3 : Accessing the `href` property value of the clicked link and storing it in a local variable. Within the context of the click event, `$(this)` refers to the currently activated element - in this instance, the clicked anchor tag.
#4 : Initiating an ajax call through the `load` method provided by jQuery; this method fetches and inserts the content from the target URL into the inner HTML of the div identified by the ID `divContentArea`.
Experimenting with sample code, adding alerts or console logs for variables/objects, can aid in understanding the process better. Best of luck!
Last statement (personal opinion) : jQuery has proven to be a valuable tool in easing development efforts.