Show and hide div with JavaScript

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.

Источник

Скрыть / показать div по клику (со сменой текста)

Нужно реализовать блок, который показываеться и скрываеться по клику, с учетом смены внутреннего текста. Наброски на jquery, блок выежает и прячется, текст «Больше» появляеться, но вот при открытие блока, текст «Больше» на «Меньше» не меняеться 🙁

3 ответа 3

$('#button').html('Больше'); $('#button').on('click', function(e) < e.preventDefault(); var $this = $(this), content = $('#block'); if(!$this.hasClass('trigger'))< $this.addClass('trigger'); $this.html('Меньше'); content.slideDown(); >else < $this.removeClass('trigger'); $this.html('Больше'); content.slideUp(); >>);

Добрый вечер. Как раз столкнулся с данной проблемой, с которой столкнулся flappy_ Просто хочу предоставить вам свой код, правда кому-то он может показаться громоздким и могут найти альтернативы попроще, но мне доработанный код помог доработать div по клику, когда их несколько, ибо с существующим кодом возможно, что могут открываться/закрываться сразу все div с данным классом (или id)

$(document).ready(function() < $('.button_header').html('Show More. '); $('.button_header').on('click', function(e) < e.preventDefault(); var $this = $(this); if (!$this.hasClass('trigger')) < $this.addClass('trigger'); $this.html('Hide'); $this.toggleClass('r').siblings('.sitenews_text').slideToggle(600); >else < $this.removeClass('trigger'); $this.html('Show More. ') $this.toggleClass('r').siblings('.sitenews_text').slideToggle(600); >>); >); 

Я рискнул добавить вместо content toggleClass и .siblings, и начали открываться/закрываться только нужные мне div Надеюсь, что был полезен

Источник

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.

Источник

Show / hide div on click with CSS

I have a menu and three hidden divs that show up depending on what option the user selects. I would like to show / hide them on click using only CSS. I have it working with jquery right now but I want it to be accessible with js disabled. Somebody here provided this code for someone else but it only works with div:hover or div:active, when I change it to div:visited it doesn’t work. Would I need to add something or perhaps this isn’t the right way to do it? I appreciate any help 🙂 The thing is my client wants this particular divs to slide/fade when the menu is selected, but I still want them to display correctly with javascript turned off. Maybe z-index could do the trick.

13 Answers 13

For a CSS-only solution, try using the checkbox hack. Basically, the idea is to use a checkbox and assign different styles based on whether the box is checked or not used the :checked pseudo selector. The checkbox can be hidden, if need be, by attaching it to a label .

For some reason I have this obsession with using CSS over java whenever possible, and I like this solution. Anyone else like that too?

@AlexBanman Yes. I have yet to find a cross-browser, cross-device compatible CSS-only solution I didn’t love.

How do you keep the browser from focusing (or attempting to focus) on the checkbox when clicking the label? Using this solution, my browser scrolls to the top of the page when I click the label

@froggomad You can try using display:none on the checkbox instead of absolute positioning. It definitely seems to alleviate the jumping, but I haven’t fully tested it to see if it causes any other issues.

@AlexBanman Could you ever use Java to show/hide HTML elements like this? Even when Java was widely supported by browsers, there was no reason to use it for something like this.

This can be achieved by attaching a «tabindex» to an element. This will make that element «clickable». You can then use :focus to select your hidden div as follows.

.clicker < width:100px; height:100px; background-color:blue; outline:none; cursor:pointer; >.hiddendiv < display:none; height:200px; background-color:green; >.clicker:focus + .hiddendiv

The + selector will select the nearest element AFTER the «clicker» div. You can use other selectors but I believe there is no current way to select an element that is not a sibling or child.

Although a bit unstandard, a possible solution is to contain the content you want to show/hide inside the so it can be reachable through CSS:

It halfs work for what I need since the div will also have to hide on a second click. But you gave me an idea with only CSS, thanks!

In 2022 you can do this with just HTML by using the details element. A summary or label must be provided using the summary element. details is supported by all major browsers.

 
Click Here for more info Here is the extra info you were looking for.
.hiddendiv .testA:focus ~ #testA .testB:focus ~ #testB

You can put your menu links horizontally = one after the other in HTML code, and then you can put all the content one after another in the HTML code, after the menu.

In other words — other solutions offer an accordion approach where you click a link and the content appears immediately after the link. The next link then appears after that content.

With this approach you don’t get the accordion effect. Rather, all links remain in a fixed position and clicking any link simply updates the displayed content. There is also no limitation on content height.

How it works

In your HTML, you first have a DIV . Everything else sits inside this DIV . This is important — it means every element in your solution (in this case, A for links, and DIV for content), is a sibling to every other element.

Secondly, the anchor tags ( A ) have a tabindex property. This makes them clickable and therefore they can get focus. We need that for the CSS to work. These could equally be DIV s but I like using A for links — and they’ll be styled like my other anchors.

Third, each menu item has a unique class name. This is so that in the CSS we can identify each menu item individually.

Fourth, every content item is a DIV , and has the class=»hiddendiv» . However each each content item has a unique id .

In your CSS, we set all .hiddendiv elements to display:none; — that is, we hide them all.

Secondly, for each menu item we have a line of CSS. This means if you add more menu items (ie. and more hidden content), you will have to update your CSS, yes.

Third, the CSS is saying that when .testA gets focus ( .testA:focus ) then the corresponding DIV , identified by ID ( #testA ) should be displayed.

Last, when I just said «the corresponding DIV «, the trick here is the tilde character ( ~ ) — this selector will select a sibling element, and it does not have to be the very next element, that matches the selector which, in this case, is the unique ID value ( #testA ).

It is this tilde that makes this solution different than others offered and this lets you simply update some «display panel» with different content, based on clicking one of those links, and you are not as constrained when it comes to where/how you organise your HTML. All you need, though, is to ensure your hidden DIV s are contained within the same parent element as your clickable links.

Источник

Читайте также:  Horizontal navigation in css
Оцените статью