简体   繁体   中英

Hide all Child Divs except active…Javascript

Im attempting to build a website where there is an absolute centered Div with content in it. I want the content to change based on the several clickable buttons on the side. In order to do so I thought the best case might be to create several child divs of the same class and parent and hide the non relevant content and only show the content associated with the clicked link. I can write out 1 million

document.getElementById("ImAnId").onclick = function helpMePlease( {
    document.getElementById("ImAlsoAnId").style.display="none";
}

lines of code. but is there a faster more simpler way to do this?

Give each button a data attribute that contains the ID of the related DIV, eg

<button class="link" data-div="ImAlsoAnId">Click me</button>

Then hide all the DIVs of the given class, and show the selected one.

$(".link").click(function() {
    $(".divclass").hide();
    $('#' + $(this).data("div")).show();
});

You could also use the jQuery UI Tabs plugin.

Give the buttons an id and the corresponding container a similar id (make it different from button's by concatinating some string). for example, I am giving the button id="red" and to the corresponding div id="redD" . Then it would make your javascript a whole lot shorter.

Instead of id , you can also work with any custom attribute.

Here's a working snippet.

 $(".links").click(function(){ var divId = "#"+ $(this).attr("id") + "D"; $(".divs").removeClass("active"); $(divId).addClass("active"); }); 
 .con{ position:relative; width:100%; margin:0; height:150px; } .divs{ position:absolute; width:100px; margin:0; bottom:0; left:0; border:1px solid black; height:100px; display:none; } .divs.active{ display:block; } #redD{ background-color:red; } #greenD{ background-color:green; } #blueD{ background-color:blue; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="con"> <button class="links active" id="green">green</button> <button class="links" id="blue">blue</button> <button class="links" id="red">red</button> <div class="divs active" id="greenD"></div> <div class="divs" id="redD"></div> <div class="divs" id="blueD"></div> </div> 

Here 'hide' is the id of the div that you want to hide.

$("#hide").click(function(){
$("p").hide();
});

Here 'show' is the id of the div that you want to show.

$("#show").click(function(){
$("p").show();
});

Do not forget to add jquery libraries at the head section of your page.

Here is a way of doing it with a data attribute to filter.

 var $things = $('.things div'); $('a').on('click',function(e) { e.preventDefault(); var activeClass = $(this).attr('data-filter'); $things.show().not('.' + activeClass).hide(); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a href="#" data-filter="a">a</a> <a href="#" data-filter="b">b</a> <a href="#" data-filter="c">c</a> <a href="#" data-filter="d">d</a> <div class="things"> <div class="a">a</div> <div class="b">b</div> <div class="c">c</div> <div class="d">d</div> <div class="a">a</div> <div class="b">b</div> <div class="c">c</div> <div class="d">d</div> <div class="a">a</div> <div class="b">b</div> <div class="c">c</div> <div class="d">d</div> <div class="a">a</div> <div class="b">b</div> <div class="c">c</div> <div class="d">d</div> </div> 

Or to hide/show using CSS instead (more performant), something like this

 var $things = $('.things div'); $('a').on('click',function(e) { e.preventDefault(); var activeClass = $(this).attr('data-filter'); $things.removeClass('hide').not('.' + activeClass).addClass('hide'); }); 
 .hide { display: none; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a href="#" data-filter="a">a</a> <a href="#" data-filter="b">b</a> <a href="#" data-filter="c">c</a> <a href="#" data-filter="d">d</a> <div class="things"> <div class="a">a</div> <div class="b">b</div> <div class="c">c</div> <div class="d">d</div> <div class="a">a</div> <div class="b">b</div> <div class="c">c</div> <div class="d">d</div> <div class="a">a</div> <div class="b">b</div> <div class="c">c</div> <div class="d">d</div> <div class="a">a</div> <div class="b">b</div> <div class="c">c</div> <div class="d">d</div> </div> 

This is simply another way with minimal javascript involved.

What I've Done

I've initially hidden all div elements with the class of .content (first CSS rule).

I have then given display:block to a .content element that is the current target of URL. For example, if your url looks like localhost/#content-1 then the :target element is #content-1 .

The rest of the CSS is to just change the display around a bit. You can ignore that.

Compatibility

According to Can I Use basically every modern browser save for IE 8 supports the :target psuedo selector. Now

Where to use

I would use this if this page was self-contained and you wanted it to be link referencing. What I mean is if I go to your webpage, click some link on the side, and want to be able to link that content to a friend without having to tell them "on the right side click 'content 3'"

Where I probably wouldn't use

  1. If you're using Angular and ngRoute, this is probably not a good idea as the $routeProvider might get confused (haven't tested it so I can't say 100%).
  2. Where there are multiple sections updated by links this won't work since a document can only have one :target element.

Obviously all of the other Javascript solutions are great, and they work perfectly well, I just wanted to show you a way to make the same functionality.

 .content { display: none; } .content:target { display: block; } /* The magic bits are above.*/ .content-link, .content-link:visited { display: block; padding: 5px 10px; background: teal; color: #eee; } .content-link:hover { color: #fff; } .content-link + .content-link { margin-top: 10px; } .wrapper { display: flex; } .wrapper .sidebar { flex: 0 0 20%; } 
 <div class="wrapper"> <aside class="sidebar"> <a href="#content-1" class="content-link">Content 1</a> <a href="#content-2" class="content-link">Content 2</a> <a href="#content-3" class="content-link">Content 3</a> <a href="#content-4" class="content-link">Content 4</a> <a href="#content-5" class="content-link">Content 5</a> <a href="#content-6" class="content-link">Content 6</a> <a href="#content-7" class="content-link">Content 7</a> <a href="#content-8" class="content-link">Content 8</a> <a href="#content-9" class="content-link">Content 9</a> <a href="#content-10" class="content-link">Content 10</a> </aside> <main class="main-content"> <div class="content" id="content-1">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sint incidunt voluptate veritatis harum perspiciatis voluptas natus laborum officiis dicta accusantium placeat expedita, nemo obcaecati a, fugit sequi provident adipisci deserunt!</div> <div class="content" id="content-2">Nihil reiciendis, excepturi eos, qui autem eveniet rerum delectus nemo officiis cupiditate architecto quibusdam necessitatibus facere sint nisi quam repudiandae, labore eaque harum non unde sunt eius nostrum. Minima, dolor.</div> <div class="content" id="content-3">Eaque facilis neque veritatis eligendi illo aliquid deserunt ut vitae eius laudantium hic, fugit architecto quasi omnis dicta, molestias itaque? Ipsa ratione laborum eum optio non nam! Ducimus, ex, repudiandae!</div> <div class="content" id="content-4">Esse perspiciatis, maiores tenetur quaerat, maxime asperiores assumenda eum dolore ab minus similique mollitia blanditiis sequi quas laboriosam dolores debitis impedit dicta, fugit laudantium molestiae sunt quia! Placeat, repellendus consectetur?</div> <div class="content" id="content-5">Animi et, ut corporis perferendis placeat ipsa sit iusto voluptatibus id eligendi, pariatur beatae. Velit ex, beatae aut. Beatae ipsam culpa quae! Pariatur veniam, atque sit soluta nam, dolores rerum.</div> <div class="content" id="content-6">Aut ipsa, fugit voluptas, incidunt asperiores, id cupiditate error reprehenderit quibusdam ut ea eligendi eos temporibus! Nobis vel aperiam rem neque harum nostrum corrupti, obcaecati ad facere alias, distinctio fugiat.</div> <div class="content" id="content-7">Architecto quisquam placeat ratione voluptas iure, incidunt laudantium nisi ut aliquid aperiam! Quidem doloremque veritatis voluptas voluptates blanditiis ea quia nesciunt culpa commodi iusto, recusandae quae quo laudantium fuga saepe.</div> <div class="content" id="content-8">Quam iste, accusantium placeat quidem ratione atque sit impedit cum quo quos aspernatur modi assumenda voluptas, ea cumque autem facilis odit. Culpa maxime labore porro dicta voluptatem reiciendis tenetur perspiciatis!</div> <div class="content" id="content-9">Nisi sequi doloribus quos cum alias recusandae quasi eaque fugit sed deleniti magni maiores tenetur minus labore consectetur, quisquam excepturi maxime eveniet iure amet accusamus asperiores tempore. Vitae, sint. Blanditiis.</div> <div class="content" id="content-10">Alias officiis, earum possimus iure. Non, dolores unde magni itaque sed numquam aliquam, vel laudantium ullam? Vitae molestiae deleniti pariatur praesentium culpa ratione necessitatibus nemo, ea suscipit, maxime, ipsa delectus.</div> </main> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM