I want to have my whole website as one page.
When clicking on different links in the navigation bar, the content should cross-fade from the old to the new one.
Example: I am on index.html#home and click on About. This should cross-fade between the divs #home and #about.
Using W3CSS and jQuery I managed to hide the content like this:
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>
I am not able to show the new content though. I wanted to add an onclick function to the navigation link and then extract the href-value to again change the class names for the div that has the ID of the href-value.
But doing this on <a href="#" onclick="showContent()></a>
returns undefined:
function showContent() {
var hrefValue = $(this).attr("href");
alert(hrefValue);
}
I guess this
is not in the proper scope of <a>
here. Am I assuming correctly?
What would be an easy way to show the content otherwise?
3
Answers
Thank you so much! It took me a while to digest your answer and apply it properly to my website layout. But I think I found a good way to do it now. At least it does what it's supposed to do and I managed to separate HTML from jQuery. Please don't hesitate to tell me if there is anything wonky going on:
Rather than embedding your function in html, add an id to your anchor element and remove the onclick attribute:
Then add an event handler to the element by using the following code to show or hide and do the other things you need to do
Then
event.target
will give you the element you need and you can use this to get attribute values. If you’re handling click events then don’t forget to prevent the default action if needed.More details here
Here you go