Show/hide 'div' using JavaScript
Asked Answered
P

15

246

For a website I'm doing, I want to load one div, and hide another, then have two buttons that will toggle views between the div using JavaScript.

This is my current code

function replaceContentInContainer(target, source) {
  document.getElementById(target).innerHTML = document.getElementById(source).innerHTML;
}

function replaceContentInOtherContainer(replace_target, source) {
  document.getElementById(replace_target).innerHTML = document.getElementById(source).innerHTML;
}
<html>
<button onClick="replaceContentInContainer('target', 'replace_target')">View Portfolio</button>
<button onClick="replaceContentInOtherContainer('replace_target', 'target')">View Results</button>

<div>
  <span id="target">div1</span>
</div>

<div style="display:none">
  <span id="replace_target">div2</span>
</div>

The second function that replaces div2 is not working, but the first one is.

Platyhelminth answered 12/1, 2014 at 1:12 Comment(1)
If you want to know more about the DOM and how to manipulate elements using javascript and it's jquery version, read the article here: noobieprogrammer.blogspot.com/2020/09/…Caraway
I
532

How to show or hide an element:

In order to show or hide an element, manipulate the element's style property. In most cases, you probably just want to change the element's display property:

element.style.display = 'none';           // Hide
element.style.display = 'block';          // Show
element.style.display = 'inline';         // Show
element.style.display = 'inline-block';   // Show

Alternatively, if you would still like the element to occupy space (like if you were to hide a table cell), you could change the element's visibility property instead:

element.style.visibility = 'hidden';      // Hide
element.style.visibility = 'visible';     // Show

Hiding a collection of elements:

If you want to hide a collection of elements, just iterate over each element and change the element's display to none:

function hide (elements) {
  elements = elements.length ? elements : [elements];
  for (var index = 0; index < elements.length; index++) {
    elements[index].style.display = 'none';
  }
}
// Usage:
hide(document.querySelectorAll('.target'));
hide(document.querySelector('.target'));
hide(document.getElementById('target'));

hide(document.querySelectorAll('.target'));

function hide (elements) {
  elements = elements.length ? elements : [elements];
  for (var index = 0; index < elements.length; index++) {
    elements[index].style.display = 'none';
  }
}
<div class="target">This div will be hidden.</div>

<span class="target">This span will be hidden as well.</span>

Showing a collection of elements:

Most of the time, you will probably just be toggling between display: none and display: block, which means that the following may be sufficient when showing a collection of elements.

You can optionally specify the desired display as the second argument if you don't want it to default to block.

function show (elements, specifiedDisplay) {
  elements = elements.length ? elements : [elements];
  for (var index = 0; index < elements.length; index++) {
    elements[index].style.display = specifiedDisplay || 'block';
  }
}
// Usage:
var elements = document.querySelectorAll('.target');
show(elements);

show(elements, 'inline-block'); // The second param allows you to specify a display value

var elements = document.querySelectorAll('.target');

show(elements, 'inline-block'); // The second param allows you to specify a display value

show(document.getElementById('hidden-input'));

function show (elements, specifiedDisplay) {
  elements = elements.length ? elements : [elements];
  for (var index = 0; index < elements.length; index++) {
    elements[index].style.display = specifiedDisplay || 'block';
  }
}
<div class="target" style="display: none">This hidden div should have a display of 'inline-block' when it is shown.</div>

<span>Inline span..</span>

<input id="hidden-input" />

Alternatively, a better approach for showing the element(s) would be to merely remove the inline display styling in order to revert it back to its initial state. Then check the computed display style of the element in order to determine whether it is being hidden by a cascaded rule. If so, then show the element.

function show (elements, specifiedDisplay) {
  var computedDisplay, element, index;

  elements = elements.length ? elements : [elements];
  for (index = 0; index < elements.length; index++) {
    element = elements[index];

    // Remove the element's inline display styling
    element.style.display = '';
    computedDisplay = window.getComputedStyle(element, null).getPropertyValue('display');

    if (computedDisplay === 'none') {
        element.style.display = specifiedDisplay || 'block';
    }
  }
}

show(document.querySelectorAll('.target'));

function show (elements, specifiedDisplay) {
  var computedDisplay, element, index;

  elements = elements.length ? elements : [elements];
  for (index = 0; index < elements.length; index++) {
    element = elements[index];

    // Remove the element's inline display styling
    element.style.display = '';
    computedDisplay = window.getComputedStyle(element, null).getPropertyValue('display');

    if (computedDisplay === 'none') {
        element.style.display = specifiedDisplay || 'block';
    }
  }
}
<span class="target" style="display: none">Should revert back to being inline.</span>

<span class="target" style="display: none">Inline as well.</span>

<div class="target" style="display: none">Should revert back to being block level.</div>

<span class="target" style="display: none">Should revert back to being inline.</span>

(If you want to take it a step further, you could even mimic what jQuery does and determine the element's default browser styling by appending the element to a blank iframe (without a conflicting stylesheet) and then retrieve the computed styling. In doing so, you will know the true initial display property value of the element and you won't have to hardcode a value in order to get the desired results.)

Toggling the display:

Similarly, if you would like to toggle the display of an element or collection of elements, you could simply iterate over each element and determine whether it is visible by checking the computed value of the display property. If it's visible, set the display to none, otherwise remove the inline display styling, and if it's still hidden, set the display to the specified value or the hardcoded default, block.

function toggle (elements, specifiedDisplay) {
  var element, index;

  elements = elements.length ? elements : [elements];
  for (index = 0; index < elements.length; index++) {
    element = elements[index];

    if (isElementHidden(element)) {
      element.style.display = '';

      // If the element is still hidden after removing the inline display
      if (isElementHidden(element)) {
        element.style.display = specifiedDisplay || 'block';
      }
    } else {
      element.style.display = 'none';
    }
  }
  function isElementHidden (element) {
    return window.getComputedStyle(element, null).getPropertyValue('display') === 'none';
  }
}
// Usage:
document.getElementById('toggle-button').addEventListener('click', function () {
  toggle(document.querySelectorAll('.target'));
});

document.getElementById('toggle-button').addEventListener('click', function () {
    toggle(document.querySelectorAll('.target'));
});

function toggle (elements, specifiedDisplay) {
  var element, index;

  elements = elements.length ? elements : [elements];
  for (index = 0; index < elements.length; index++) {
    element = elements[index];

    if (isElementHidden(element)) {
      element.style.display = '';

      // If the element is still hidden after removing the inline display
      if (isElementHidden(element)) {
        element.style.display = specifiedDisplay || 'block';
      }
    } else {
      element.style.display = 'none';
    }
  }
  function isElementHidden (element) {
    return window.getComputedStyle(element, null).getPropertyValue('display') === 'none';
  }
}
.target { display: none; }
<button id="toggle-button">Toggle display</button>

<span class="target">Toggle the span.</span>

<div class="target">Toggle the div.</div>
Inutility answered 12/1, 2014 at 1:33 Comment(1)
hi, in the «toggle» case you invoke toggle() with only one parameter, but its signature has two of them.Mallard
T
111

You can also use the jQuery JavaScript framework:

To Hide Div Block

$(".divIDClass").hide();

To show Div Block

$(".divIDClass").show();
Tessi answered 6/1, 2015 at 11:9 Comment(5)
The question doesn't mention using jQueryBerchtesgaden
which is not a reason for downvoting. the question doesn't specifically say to not use jquery, and besides other people coming here to view the answers may not have the same constraints as the OP.Derbyshire
@KinjalDixit If IMRUP wants to add a note that his answer doesn't use vanilla JS and instead relies on jQuery, then it would have some merit, even though the original question isn't tagged for jQuery/even mentions jQuery. As it currently stands it's an answer using a library without mentioning that it does so, little (albeit probably all that's necessary) explanation, and confusing use of a selector (using class selector whilst stating ID?). As it currently stands, I do not think it is useful answer to this question.Berchtesgaden
When adding a jQuery example (which is perfectly valid approach IMHO) please also provide a vanilla JS example for comparison and explain to the OP the difference. So many new developers these days think jQuery is JavaScript. A little eduction would help them make the right choices.Victual
I think this answer was very useful, and related to the question.Nip
G
51

You can simply manipulate the style of the div in question...

document.getElementById('target').style.display = 'none';
Gavotte answered 12/1, 2014 at 1:20 Comment(1)
But I would like it to display the content of the second div as wellPlatyhelminth
D
28

You can Hide/Show Div using Js function. sample below

<script>
    function showDivAttid(){

        if(Your Condition) {

            document.getElementById("attid").style.display = 'inline';
        }
        else
        {
            document.getElementById("attid").style.display = 'none';
        }
    }

</script>

HTML -

<div  id="attid" style="display:none;">Show/Hide this text</div>
Dee answered 26/2, 2015 at 12:43 Comment(1)
if you want to use class name instead of Id, use like document.getElementsByClassName('CLASSNAME')[0].style.display = 'none';Photokinesis
P
17

Using style:

<style type="text/css">
   .hidden {
        display: none;
   }
   .visible {
        display: block;
   }
</style>

Using an event handler in JavaScript is better than the onclick="" attribute in HTML:

<button id="RenderPortfolio_Btn">View Portfolio</button>
<button id="RenderResults_Btn">View Results</button>

<div class="visible" id="portfolio">
    <span>div1</span>
</div>

<div class"hidden" id="results">
    <span>div2</span>
</div>

JavaScript:

<script type="text/javascript">

    var portfolioDiv = document.getElementById('portfolio');
    var resultsDiv = document.getElementById('results');

    var portfolioBtn = document.getElementById('RenderPortfolio_Btn');
    var resultsBtn = document.getElementById('RenderResults_Btn');

    portfolioBtn.onclick = function() {
        resultsDiv.setAttribute('class', 'hidden');
        portfolioDiv.setAttribute('class', 'visible');
    };

    resultsBtn.onclick = function() {
        portfolioDiv.setAttribute('class', 'hidden');
        resultsDiv.setAttribute('class', 'visible');
    };

</script>

jQuery may help you to manipulate DOM elements easy!

Pouliot answered 12/1, 2014 at 1:54 Comment(1)
You can try the hidden attribute of HTML5Dihybrid
J
14

I found this plain JavaScript code very handy!

#<script type="text/javascript">
    function toggle_visibility(id) 
    {
        var e = document.getElementById(id);
        if ( e.style.display == 'block' )
            e.style.display = 'none';
        else
            e.style.display = 'block';
    }
</script>
Jervis answered 26/5, 2014 at 13:3 Comment(0)
I
9

Just Simple Set the style attribute of ID:

To Show the hidden div

<div id="xyz" style="display:none">
     ...............
</div>
//In JavaScript

document.getElementById('xyz').style.display ='block';  // to display

To hide the shown div

<div id="xyz">
     ...............
</div>
//In JavaScript

document.getElementById('xyz').style.display ='none';  // to hide
Impostor answered 10/8, 2018 at 4:4 Comment(1)
The 'to hide' & 'to display' comments need to be switched.Return
L
5

Set your HTML as

<div id="body" hidden="">
 <h1>Numbers</h1>
 </div>
 <div id="body1" hidden="hidden">
 Body 1
 </div>

And now set the javascript as

function changeDiv()
  {
  document.getElementById('body').hidden = "hidden"; // hide body div tag
  document.getElementById('body1').hidden = ""; // show body1 div tag
  document.getElementById('body1').innerHTML = "If you can see this, JavaScript function worked"; 
  // display text if JavaScript worked
   }
Limner answered 28/1, 2017 at 7:13 Comment(0)
H
1
<script type="text/javascript">
    function hide(){
        document.getElementById('id').hidden = true;
    }
    function show(){
        document.getElementById('id').hidden = false;
    }
</script>
Honora answered 5/12, 2014 at 5:29 Comment(1)
Using Hidden for a problem like this is probably not a good idea - as well as being unsupported in IE versions before 11, the poster is effectively trying to do something equivalent to a simple tab interface, and so the elements won't be hidden in all contexts. In this sort of situation, it's probably better to use 'display' to control the hiding - see #6708747Cestar
D
1

A simple example with a Button to scroll up. It will only scroll if the javascript is active, which is an event listening to the scroll type.

document.getElementById('btn').style.display='none'

window.addEventListener('scroll', (event) => {
    console.log(scrollY)
    document.getElementById('btn').style.display='inline'
})
a
long<br>
text<br>
comes<br>
long<br>
text<br>
again

<button id=btn class = 'btn btn-primary' onclick='window.scrollTo({top: 0, behavior: "smooth"});'>Scroll to Top</button>

Live in action here

Deenadeenya answered 5/2, 2021 at 19:43 Comment(0)
Q
0

And the Purescript answer, for people using Halogen:

import CSS (display, displayNone)
import Halogen.HTML as HH
import Halogen.HTML.CSS as CSS

render state = 
  HH.div [ CSS.style $ display displayNone ] [ HH.text "Hi there!" ]

If you "inspect element", you'll see something like:

<div style="display: none">Hi there!</div>

but nothing will actually display on your screen, as expected.

Quasar answered 10/2, 2018 at 17:40 Comment(0)
N
0

Just Simple Function Need To implement Show/hide 'div' using JavaScript

<a id="morelink" class="link-more" style="font-weight: bold; display: block;" onclick="this.style.display='none'; document.getElementById('states').style.display='block'; return false;">READ MORE</a>


<div id="states" style="display: block; line-height: 1.6em;">
 text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here  
    <a class="link-less" style="font-weight: bold;" onclick="document.getElementById('morelink').style.display='inline-block'; document.getElementById('states').style.display='none'; return false;">LESS INFORMATION</a>
    </div>
Nadaba answered 13/3, 2018 at 5:16 Comment(0)
S
0

I found this question and recently I was implementing some UIs using Vue.js so this can be a good alternative.

First your code is not hiding target when you click on View Profile. You are overriding the content target with div2.

let multiple = new Vue({
  el: "#multiple",
  data: {
    items: [{
        id: 0,
        name: 'View Profile',
        desc: 'Show profile',
        show: false,
      },
      {
        id: 1,
        name: 'View Results',
        desc: 'Show results',
        show: false,
      },
    ],
    selected: '',
    shown: false,
  },
  methods: {
    showItem: function(item) {
      if (this.selected && this.selected.id === item.id) {
        item.show = item.show && this.shown ? false : !item.show;
      } else {
        item.show = (this.selected.show || !item.show) && this.shown ? true : !this.shown;
      }
      this.shown = item.show;
      this.selected = item;
    },
  },
});
<div id="multiple">
  <button type="button" v-for="item in items" v-on:click="showItem(item)">{{item.name}}</button>

  <div class="" v-if="shown">: {{selected.desc}}</div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.7/vue.js"></script>
Soap answered 23/1, 2019 at 6:22 Comment(0)
S
0

You can easily achieve this with the use of jQuery .toggle().

$("#btnDisplay").click(function() {
  $("#div1").toggle();
  $("#div2").toggle();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="div1">
  First Div
</div>
<div id="div2" style="display: none;">
  Second Div
</div>
<button id="btnDisplay">Display</button>
Sickroom answered 4/6, 2020 at 19:34 Comment(0)
S
0

Instead your both functions use toggle function with following body

this[target].parentNode.style.display = 'none'
this[source].parentNode.style.display = 'block'

function toggle(target, source) {
  this[target].parentNode.style.display = 'none'
  this[source].parentNode.style.display = 'block'
}
<button onClick="toggle('target', 'replace_target')">View Portfolio</button>
<button onClick="toggle('replace_target', 'target')">View Results</button>

<div>
  <span id="target">div1</span>
</div>

<div style="display:none">
  <span id="replace_target">div2</span>
</div>
Stilbestrol answered 27/7, 2020 at 13:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.