How to show/hide a div?

I am a new coder and am just starting to learn javascript.

On my website, I have a row in my grid that is dedicated towards being a “search bar”. There will be a search form field on the bar and also an “advanced search” button on the bar. I only want this bar to display when “search” is clicked on the menu. While I can accomplish this fairly easily via php which would invoke a form action that would reload the page, I would instead like to just use javascript to make this section appear.

I have been studying some tutorials on how to make this happen, but I really don’t know how to proceed. Furthermore there appears to be 2 different approaches to this. One approach is just to switch between 2 different class names – however it sounds like this does not work on IE 9. (That may not be a big issue, but I would like the code to be as platform/browser friendly as possible). The other approach is to just make the section appear or to hide it.

Here is my pseudo code for this so far:

HTML:
if SEARCH is clicked on html page, then execute function searchBarToggle ()
<a href="#"><div onclick="toggleSearch()">SEARCH</div></a>

JS:
		if active: if (searchBarState == true)
			close search bar
			store search bar as inactive (searchBarState = false)
		else
			open search bar
			store search bar as active (searchBarState = true)

I really an now sure how to proceed with this. Currently I have a class for the search bar this displays all the components in a flex box: .searchBar_visible I also have a class which is basically empty class (display: none;) and is appropriately named: searchBar_hidden

Could someone please help me out on this journey through javascript.

It might help to take a look at this article on showing and hiding elements. There are a lot of pitfalls and issues to take into account with each technique, and this piece take you through a lot of the things to consider.

Thanks Paul, that was very informative. It really doesn’t look like javascript well is designed to do what I am trying to do – it appears to me that php is the better route to go for having a section hide or unhide.

The search section will have clickable elements and hopefully a javascript enabled search function that will auto-populate search words from my database as the user types. Trying to make sure all this works on all platforms while also allowing it to hide just does not seem reliable with javascript.

you can use js for almost anything. the thing is to find the shortest possible path. :slight_smile:

that seeing said, you can use some standard techniques.
one is pure css toggles. that is use the status of a sibling element such as a checkbox to determine whether the next element is hidden or displayed.

but if you really want to use js, you can use a toggle class technique.

in either case, you dont want to hide your toggle button along with your target… how would you get back to your original state?

Anyway, here is a simplified version of something I often do:

<html>
	<head>
		<title> </title>
		<style type="text/css" media="screen">
			.hide{
				display:none;
			}
			.srch-btn.show:before{
				content:'Show '
			}
			.srch-btn:before{
				content:'Hide ';
 			}
			.srch-btn {
 				/***aesthetic stuff*/
				padding: .5em;
				text-decoration: none;
				border-radius: 4px;
				border: 1px solid;
				display: inline-block;
			}
			
		</style>
	</head>
	<body>
		<a class="srch-btn" onclick="this.classList.toggle('show'); document.getElementById('searchStuff').classList.toggle('hide')">Search</a><!--no need to use href="#"  this is NOT a real link-->
		<div id="searchStuff">
			<label> Search for: <input id="seach" name="search" /></label>
			<p>I could be a list of search results</p>
		</div>
	</body>
</html>

Hope that helps

Switching classes in IE9 is fine assuming you use js versions that are available in IE9.

That’s a good ideal to follow but you have to bear in mind there must come a point when you say no. How far do you go back and where do you stop? Do you cater for people without electricity? :slight_smile:

It’s not an easy question to answer and may depend on your userbase or location.

As a rule of guide I would not support any browser that the vendor itself does not support. IE8,9 and 10 were discontinued in 2016 and IE11 set to be discontinued in 2021. It could indeed be irresponsible to support an old vulnerable browser and open your users to the recent ransomeware attacks that were specifically targeted at discontinued browsers that had low (and not updated) security.

It depends if the sections you are revealing are new data (or new pages) then you can just load a new page as though you had navigated to a new page (or you could load the new data with js/ajax to avoid a page refresh).

If on the other hand you are just hiding things to make the interface neater then the elements really should be in the page to start with but kept out of sight (bearing in mind to us the correct hiding mechanisms as @Paul_Wilkins pointed out). JS would be perfect for this as you are just revealing existing content/elements. The html of a page should always make semantic sense on its own (because this is mostly what screen readers and bots use to work out what’s in the page).

Thank you dresden for the code example. I believe I can get that working with my existing page structure.

Thank you PaulOB for reviewing why it would be better to reveal existing elements rather than reload the page.

I am also currently taking a continuing education online introductory Javascript course however I am finding that many of the practical applications that I require just aren’t taught in the class.

Something I am trying to figure out is the “toggle” operation. What exactly does “toggle” do? I have tried Googling this but have not found any references to this operation. If there is some online documentation on this operation that you know of, I would really appreciate a link.

Thanks again for your help with this.

@Paul_Wilkins would be better qualified to answer but if you are referring to yourEl.classList.toggle('myClass') then that will look at the element concerned and if it does not contain a class called ‘myClass’ then it will add that class. If the element already has a class called ‘myClass’ it will remove it instead. Basically it toggles the class on and off which is ideal for operations like showing and hiding something. The css then can handle the display via the myClass you added or removed.

As noted above classList is not implemented in IE9 but there are full polyfill methods around for IE9 or snippets like this.

if (el.classList) {
  el.classList.toggle(className);
} else {
  var classes = el.className.split(' ');
  var existingIndex = classes.indexOf(className);

  if (existingIndex >= 0)
    classes.splice(existingIndex, 1);
  else
    classes.push(className);

  el.className = classes.join(' ');
}

In Dresden’s post he toggles a class of .hide to hide the element. When the class is removed the element returns to its original state. Generally though you would not use an inline onclick handler but rather do it all from the js file.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.