Home > Software design >  How to toggle div content when clicking on different navigation links?
How to toggle div content when clicking on different navigation links?

Time:08-29

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"  style="width:16.5%">Home</a>
<a href="#about"  style="width:16.5%" onclick="hideContent()">About</a>
<div id="home"  style="height:50px"></div>
<div id="about"  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?

CodePudding user response:

Here you go

$("#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"  style="width:16.5%">Home</a>
<a href="#about" id="aboutclick"  style="width:16.5%">About</a>
<div id="home"  style="height:50px">Home Div</div>
<div id="about"  style="height:50px">About Div</div>

CodePudding user response:

Rather than embedding your function in html, add an id to your anchor element and remove the onclick attribute:

<a href="#about" id="aboutclick"  style="width:16.5%">About</a>

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

$('#aboutclick').click(function(event) {
  ...
});

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

  • Related