Reputation: 75
I have a few tabs on my website that loads as soon as the page is loaded. I do not want that. I rather want each tab-content to be loaded as soon as I press on it. I have solved this so far in the following way:
I have a tab as follows:
<li><a data-Toggle="tab" href="#Alarm">Larm</a></li>
When I press on this tab, it directs to the Alarm-div, which looks like this:
<div id="Alarm" class="tab-pane fade">
<a class="alarmTab" asp-controller="Customer" asp-action="LoadAlarm" asp-route-id="@Model.Plants.First().STATION">Hämta larm</a>
<div class="larm2" id="larm2"></div>
</div>
Within this div, I have created a link called alarmTab, which calls an action LoadAlarm, which looks like this:
public async Task<IActionResult> LoadAlarm(string id)
{
return ViewComponent("Events", new { id = id});
}
I also have a JS, which presents the result from the ViewComponent within the larm2-div.
This whole procedure works. However, I want this to happen as soon as I press on the alarm-tab, without having to press on the hyperlink alarmTab. Any ideas?
Upvotes: 0
Views: 3185
Reputation: 218722
You can make an ajax call to the server when the tab link is clicked.
Add an html5 data attribute to the links so we can store a value indicating whether the content needed for the tab pane is already loaded.
<div class="tab-content">
<div role="tabpanel" class="tab-pane active" id="home">
<a class="contentLink" style="display: none;"
data-loaded="0" asp-controller="Home" asp-action="LoadAlarm"
asp-route-id="1">Hämta larm</a>
<div class="content" ></div>
</div>
<div role="tabpanel" class="tab-pane" id="profile">
<a class="contentLink" style="display: none;"
data-loaded="0" asp-controller="Home" asp-action="LoadAlarm"
asp-route-id="2">Hämta larm</a>
<div class="content" ></div>
</div>
</div>
Now when the tab content pane is shown, read the href value generated by the link tag helper and make an ajax call if the data-loaded
attribute value is 0. Once we get the response from the server, update the data-loaded
value to 1 and update the inner html of the content div.
$(function() {
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
var target = $(e.target).attr("href");
var $c = $(target).find(".contentLink");
var $content = $(target).find(".content");
if ($c.data("loaded") === 0) {
var url = $c.attr("href");
$.get(url, function (r) {
$content.html(r);
$c.data("loaded",1);
});
}
});
});
You can now modify the above code to load the content for the active tab on page laod as well. The idea is same for that as well.
Upvotes: 2