Show and hide div with JavaScript

JavaScript — How to show and hide div by a button click

To display or hide a by a click, you can add the onclick event listener to the element.

The onclick listener for the button will have a function that will change the display attribute of the from the default value (which is block ) to none .

For example, suppose you have an HTML element as follows:

The element above is created to hide or show the element on click.

You need to add the onclick event listener to the element like this:


When you click the element again, the display attribute will be set back to block , so the will be rendered back in the HTML page.

Since this solution is using JavaScript API native to the browser, you don’t need to install any JavaScript libraries like jQuery.

You can add the JavaScript code to your HTML tag using the tag as follows:

Feel free to use and modify the code above in your project.

I hope this tutorial has been useful for you. 👍

Читайте также:  Html select option selected in javascript

Learn JavaScript for Beginners 🔥

Get the JS Basics Handbook, understand how JavaScript works and be a confident software developer.

A practical and fun way to learn JavaScript and build an application using Node.js.

About

Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
Learn statistics, JavaScript and other programming languages using clear examples written for people.

Type the keyword below and hit enter

Tags

Click to see all tutorials tagged with:

Источник

Как в javascript "закрывать" div при клике вне этого дива?

При клике по некоторому элементу управления на экране появляется div c текстом подсказок. У дива есть кнопка "закрыть". Но хочется, чтобы он закрывался не только по клику на кнопку, но и вне области этого div'a. Подскажите, как это реализовать?

5 ответов 5

$(document).mouseup(function (e) < var container = $("YOUR CONTAINER SELECTOR"); if (container.has(e.target).length === 0)< container.hide(); >>); 

что означает следующее - если клик был по области, которая НЕ является нашим div'ом или не содержится в нем, то скрыть блок.

Это решает проблему, если клик был по элементу вложенному в блок (не по самому блоку). Элемент будет скрыт, только если клик по области ВНЕ div'a

В вашем примере есть один нюанс. container.has(e.target) - вернет пустой массив, если нажатие произойдет по самому диву, а не его дочерним элементам. Нужна доп. проверка $(document).click(function(e) < var elem = $("YOUR CONTAINER SELECTOR"); if(e.target!=elem[0]&&!elem.has(e.target).length)< elem.hide(); >>)

$(".button").click(function() < $('.toggled_block').toggle(); >); $(document).on('click', function(e) < if (!$(e.target).closest(".parent_block").length) < $('.toggled_block').hide(); >e.stopPropagation(); >);
.parent_block < width: 200px; height: 100px; >.button < width: 200px; height: 50px; background: #00BB65; border-radius: 5px; overflow: hidden; >.toggled_block

Вот решение на нативном JS, которое учитывает скрытие соседнего элемента по повторному клику на сам элемент. А также скрытие по области вне самого элемента.

let hamburger = document.querySelector('.hamburger'); let menu = document.querySelector('.menu'); const toggleMenu = () => < menu.classList.toggle('active'); >hamburger.addEventListener('click', e => < e.stopPropagation(); toggleMenu(); >); document.addEventListener('click', e => < let target = e.target; let its_menu = target == menu || menu.contains(target); let its_hamburger = target == hamburger; let menu_is_active = menu.classList.contains('active'); if (!its_menu && !its_hamburger && menu_is_active) < toggleMenu(); >>)
* < font-family: sans-serif; >.page < display: flex; >.hamburger < background-color: #222; width: 100px; height: 100px; border: 0; border-radius: 50%; cursor: pointer; >.hamburger .line < width: 70px; height: 10px; margin-left: 10px; background-color: #fff; pointer-events: none; >.hamburger .line:not(:last-child) < margin-bottom: 10px; >.menu < display: none; background-color: #222; color: #fff; padding: 5px 0; >.menu .item < padding: 5px 15px; cursor: pointer; >.menu.active
'use strict'; var hamburger = document.querySelector('.hamburger'); var menu = document.querySelector('.menu'); var toggleMenu = function toggleMenu() < menu.classList.toggle('active'); >; hamburger.addEventListener('click', function(e) < e.stopPropagation(); toggleMenu(); >); document.addEventListener('click', function (e) < var target = e.target; var its_menu = target == menu || menu.contains(target); var its_hamburger = target == hamburger; var menu_is_active = menu.classList.contains('active'); if (!its_menu && !its_hamburger && menu_is_active) < toggleMenu(); >>); 

Источник

How can I hide/show a div when a button is clicked?

Use JQuery. You need to set-up a click event on your button which will toggle the visibility of your wizard div.

Refer to the JQuery website for more information.

This can also be done without JQuery. Using only standard JavaScript:

 function toggle_visibility(id) 

Then add onclick="toggle_visibility('id_of_element_to_toggle');" to the button that is used to show and hide the div.

I do think that the OP is looking for an easier solution than having to use a third-party library (jQuery not tagged). This can be done without JQuery.

Just a note to the OP: use visibility: hidden/ visible; when you don't want the #wizard div to free space for other elements. Use display: none/ block; if you want the #wizard div to be hidden with a size, margin & padding properties equivalent to 0 when hidden.

     Click to show/hide. 

Content goes here.

This can't be done with just HTML/CSS. You need to use javascript here. In jQuery it would be:

       

This div will be show and hide on button click

The following solution is:

  • briefest. Somewhat similar to here. It's also minimal: The table in the DIV is orthogonal to your question.
  • fastest: getElementById is called once at the outset. This may or may not suit your purposes.
  • It uses pure JavaScript (i.e. without JQuery).
  • It uses a button. Your taste may vary.
  • extensible: it's ready to add more DIVs, sharing the code.
mydiv = document.getElementById("showmehideme"); function showhide(d)
 
This div will show and hide on button click.

Firefox. Not at home now . So cant comment on the version. Thanks for taking the time to respond. Much appreciated.

if you want to begin with the div hidden, you should add style="display:none;" , like this:

Task can be made simple javascript without jQuery etc.

This function is simple if statement that looks if wizard has class swMain and change class to swHide and else if it's not swMain then change to swMain. This code doesn't support multiple class attributes but in this case it is just enough.

Now you have to make css class named swHide that has display: none

Then add on to the button onclick="showhide()"

You can do this entirely with html and css and i have.

HTML First you give the div you wish to hide an ID to target like #view_element and a class to target like #hide_element . You can if you wish make both of these classes but i don't know if you can make them both IDs. Then have your Show button target your show id and your Hide button target your hide class. That is it for the html the hiding and showing is done in the CSS.

CSS The css to show and hide this should look something like this

#hide_element:target < display:none; >.show_element:target

This should allow you to hide and show elements at will. This should work nicely on spans and divs.

Источник

toggle show/hide div with button?

I was checking out other questions and I came across an answer in this thread: stackoverflow.com/questions/18808112/… . Apparently it's because the new versions of JQuery don't support toggle anymore.

@BarryDoyle: Actually, toggle-event was deprecated in 1.8. The way this answer uses toggle is still available, see this example: jsfiddle.net/KpFRb/532

jQuery(document).ready(function()< jQuery('#hideshow').live('click', function(event) < jQuery('#content').toggle('show'); >); >); 

For versions of jQuery 1.7 and newer use

jQuery(document).ready(function()< jQuery('#hideshow').on('click', function(event) < jQuery('#content').toggle('show'); >); >); 

For reference, kindly check this demo

Now .live() is deprecated in 1.7,and removed in 1.9 so in new versions you can use .on() (for details api.jquery.com/on )

How do you set this to hide by default? Edit: Figured it out, just added the toggle before the code that catches the button push.

I suppose toggle('show') is a typo (that some have blatantly copied and pasted into other answers) because only 'slow' and 'fast' are accepted strings for duration. It works nonetheless because I think any invalid string will default to 'slow' . jsfiddle.net/d5y06e6o

Since toggling using style like:

myElement.style.display = someBoolState ? "block" : "none" 

is a really bad idea, here are some examples in JS, jQuery, HTML, CSS:

JavaScript .classList.toggle()

const elToggle = document.querySelector("#toggle"); const elContent = document.querySelector("#content"); elToggle.addEventListener("click", function() < elContent.classList.toggle("is-hidden"); >);

The beauty of the above is that the styling is purely handled where it should, and that's in your stylesheet. Also, by removing the .is-hidden class your element will regain its original display mode, being it block , table , flex , or whatever.

jQuery .toggle()

jQuery - Toggle .toggleClass() Docs

.toggle() toggles an element's display "block"/"none" values

HTML5 - Toggle using and

(unsupported on IE and Opera Mini)

HTML - Toggle using checkbox

[id^=toggle], [id^=toggle] + * < display:none; >[id^=toggle]:checked + *

HTML - Switch using radio

[id^=switch], [id^=switch] + * < display:none; >[id^=switch]:checked + *
  
1 Merol Muspi.
2 Lorem Ipsum.

CSS - Switch using :target

(just to make sure you have it in your arsenal)

[id^=switch] + * < display:none; >[id^=switch]:target + *
SHOW 1 SHOW 2 
1 Merol Muspi .
2 Lorem Ipsum.

Animating class transition

If you pick one of JS / jQuery way to actually toggle a className , you can always add animated transitions to your element, here's a basic example:

const elToggle = document.querySelector("#toggle"); const elContent = document.querySelector("#content"); elToggle.addEventListener("click", () => < elContent.classList.toggle("is-hidden"); >);
 
Some Togglable content.

Hi Sir @Roko C. Buljan is there a way to show the div initially in CSS - Switch using :target toggle please help I really need that.Thanks.

@ProgrammingHobby absolutely, if you want to make "Default open" one of the above containers (that use :target toggle method) simply add the desired hash ID to the page URI i.e: index.html#switch1 - and see the Element ID switch1 open right away. You can also manipulate the URL object using JS URL.hash - if needed: developer.mozilla.org/en-US/docs/Web/API/URL/hash

@Roko C. Buljan Thank you so much sir.Have a nice day.You answer was great and I have used that in many of mine projects.Thanks for that.

Источник

Скрывать по клику javascript

Last updated: Jan 11, 2023
Reading time · 2 min

banner

# Hide element when clicked outside using JavaScript

To hide an element when clicked outside:

  1. Add a click event listener to the document object.
  2. On each click, check if the clicked element is outside of the specific element using the contains() method.
  3. If the clicked element is outside, hide the original element.

Here is the HTML for the example.

Copied!
DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> title>bobbyhadz.comtitle> head> body> div id="box" style="height: 150px; width: 150px; background-color: salmon"> Box div> script src="index.js"> script> body> html>

And here is the related JavaScript code.

Copied!
document.addEventListener('click', function handleClickOutsideBox(event) const box = document.getElementById('box'); if (!box.contains(event.target)) box.style.display = 'none'; > >);

We added a click handler on the document object.

We used the document.getElementById() method to select the element we want to hide when the user clicks outside.

The event handler function gets passed the event object as a parameter.

We used the target property on the event object. The target property is a reference to the object (element) on which the event was dispatched.

You can console.log the target property to see the DOM element that was clicked by the user.

Copied!
document.addEventListener('click', function handleClickOutsideBox(event) // 👇️ the element the user clicked console.log('user clicked: ', event.target); const box = document.getElementById('box'); if (!box.contains(event.target)) box.style.display = 'none'; > >);

The last step is to use the Node.contains method to check if the clicked element is not contained by the original element.

If the clicked element is not contained in the box, we hide the box element.

The contains() method takes a Node as a parameter and returns a boolean value that indicates if the passed in Node is contained in the Node the method was called on.

If the clicked element is not contained in the box element, then the user clicked outside, so we hide the box .

If the user clicks on the box element, the if condition is not met and the element is not hidden.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Оцените статью