How to open a div by clicking on a link to?

Posted on

Question :


I’m creating an element for a personal site, and would like this element ” <div> ” to be opened / closed when a button is clicked.

It is a <div> containing some country flags to change the language.

I think you could use that function .slide of jQuery to create this effect.

However, I know only the basics in jQuery.

Thank you in advance:)

The div to be opened is this:

<div id="paises">Aqui ficará as bandeiras</div>


Answer :

To show or hide an element based on the click of another we will need to use two methods:

  • jQuery .on() to execute code when button is clicked.

  • >

  • jQuery .slideToggle() to animate the target element and to switch its presentation between “hidden” and “visible” “.

See example in JSFiddle .

$('button').on("click", function() {
div {
  display: none;
<script src=""></script>
<button>Tens bandeiras?</button>
<div>Tenho, bué da bandeiras, mas é assim, não sei onde meti os icons e então acabei por escrever um texto muito longo a dar conta que não sabia dos icons e nem sei se todos estão a ler isto até ao fim? Tu estás? É pá! Bora lá bater um papo...</div>


It is not necessary to use Javascript in most cases where you need to do some toggle in another element. Just a% of type checkbox to make the control of when to show or hide, then in style sheets you can use the pseudo-class <input> to create rules depending on the state of input .

/* Escondendo a caixinha de marcação e o div alvo. */
div, input{ 
  display: none

/* Texto exibido quando o checkbox não estiver marcado. */
input + label::before {
  content: 'Mostrar '

/* Texto exibido quando o checkbox estiver marcado. */
input:checked + label:before {
  content: 'Esconder '

/* Exibe o elemento de ID 'bandeiras' quando o checkbox estiver marcado. */
input:checked ~ #bandeiras {
  display: block

img { width: 300px }
<input type='checkbox' id='toggle'>
<label for='toggle'>Bandeiras</label>

<div id='bandeiras'>
  <img src='' alt='Klingons'>

Of course this needs a better appearance, but I focused only on the behavior question that was asked ignoring that the click should occur on an anchor element.

Issues such as animations and smooth transitions can be easily resolved with the properties :checked and animation CSS.



You can use the .slideToggle() function and a bit of CSS, eg:

function abreFecha(sel) {
#paises {
  display: none;
<script src=""></script><ahref="javascript:abreFecha('#paises')">Clique em mim</a>

<div id="paises">Bandeiras aqui</div>


This link has an example that will help

Higher, you can get the click event from your button via js and use the id of your div in js document.querySelector () or jquery $ () to access the attributes of div and mecher in css of it adding or removing display: none or a visibility: hidden depending on how you want to keep the layout for example …


Leave a Reply

Your email address will not be published. Required fields are marked *