How to toggle div content when clicking on different navigation links?
I’d like to have my entire website on a single page.
When you click on different links in the navigation bar, the content should cross-fade from the previous to the new one.
As an example, I am on index.html#home and click on About. This should cross-fade between the divs #home and #about.
I was able to hide the material using W3CSS and jQuery as follows:
function hideContent() { $(".content-active").addClass("w3-hide", "content-inactive"); $(".content-active").removeClass("w3-show", "content-active"); };
<link href="https://www.w3schools.com/w3css/4/w3.css" rel="stylesheet"/> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <a href="#home" class="w3-bar-item w3-hide-small" style="width:16.5%">Home</a> <a href="#about" class="w3-bar-item w3-hide-small" style="width:16.5%" onclick="hideContent()">About</a> <div id="home" class="w3-container w3-green w3-show content-active" style="height:50px"></div> <div id="about" class="w3-container w3-red w3-hide content-inactive" style="height:50px"></div>
However, I am unable to display the new content. I intended to add a onclick function to the navigation link and then extract the href-value to replace the class names for the div with the href-ID value’s once again.
But doing this on <a href="#" onclick="showContent()></a>
returns undefined:
function showContent() { var hrefValue = $(this).attr("href"); alert(hrefValue); }
Add comment
Answers (1)
Add Answer$("#aboutclick").click(function(event) { const targetDiv=$(event.target).attr('href'); hideContent(); $(targetDiv).addClass("w3-show", "content-active"); }); function hideContent() { $(".content-active").addClass("w3-hide", "content-inactive"); $(".content-active").removeClass("w3-show", "content-active"); };
<link href="https://www.w3schools.com/w3css/4/w3.css" rel="stylesheet"/> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <a href="#home" class="w3-bar-item w3-hide-small" style="width:16.5%">Home</a> <a href="#about" id="aboutclick" class="w3-bar-item w3-hide-small" style="width:16.5%">About</a> <div id="home" class="w3-container w3-green w3-show content-active" style="height:50px">Home Div</div> <div id="about" class="w3-container w3-red w3-hide content-inactive" style="height:50px">About Div</div>