Hide/Show div on specific page with jquery

There’s quite a lot of possible answers to your questions, I’ll try to give you as much answers as I can, with details.

1) Include the Sidebar only on pages you want it to be displayed ( using PHP )

If you want your sidebar to be on, let’s say, only 3 pages out of 5, then create a sidebar.php file with your sidebar code in it, and include this page on the pages you want your sidebar on.

Read more at : http://php.net/manual/en/function.include.php

2) With jQuery

You can set your sidebar hidden and .toggle it whenever you want it to be displayed. It can be easily done using jQuery, here’s an example : https://jsfiddle.net/g5bwwtvd/

Obviously, you can change the .toggle method and let jQuery detect the current page the user is on, and depending on which page he is on, .toggle ( or not ) the sidebar.

Keep in mind that this is not a proper way to do it, just mentionning it so you know.

3) Using CSS ( not recommended )

You can include a specific css stylesheet whenever you do not want to display your sidebar, and in this stylesheet you hide your sidebar with visibility: hidden, and display: none. Keep in mind that doing that is not a good way to do so, since you write more code to hide something.

I recommand the ìnclude method, since that is a good way to do it, and it works with nearly every language, not only web ones.

EDIT : Adding example for JavaScript.

HTML

<div class="sidebar" hidden> // Hidden sidebar
  <p>
    I am the sidebar
  </p>
</div>

<p class="path">
</p>

JavaScript / JQuery

$(function(){

    var currPath = window.location.pathname; // Gets the current pathname ( /_display/ )

  $('.path').text('Current path is : '+ currPath);
  if(currPath == '/webpage.html'){ // Checks if the pathname equals the webpage you want the sidebar to be displayed on
    $('.sidebar').toggle(); // Set the sidebar to visibility: visible and display: block
  }else {}

})

DEMO

If you want to properly understand the code, change the if(currPath == '/webpage.html') to if(1 == 1), the sidebar will now be displayed properly.

Browse More Popular Posts

Leave a Comment