0

So what im trying to do here is to show and hide div when i click button but it does not work and i dont know why.

script $(document).ready(function(){ $('article').addClass("hidden"); $('#hide').click(function() { var $this = $(this); if ($this.hasClass("hidden")) { $(this).removeClass("hidden").addClass("visible"); } else { $(this).removeClass("visible").addClass("hidden"); } }); }); 

Here is CSS

.hidden>div { display: none; } .visible>div { display: block; } 

Here is HTML

<article> <button type="button" id="hide"></button> <div> <img /> <img /> </div> </article> 
0

4 Answers 4

2

You should add class hidden to article instead of button

var $this = $(this).parent(); 

Selector .hidden>div adds style to first div child of element with class hidden.

Sign up to request clarification or add additional context in comments.

Comments

0

Instead of putting if condition and then removing and adding classes, you can just toggle the class hidden.

$(document).ready(function(){ $('article').addClass("hidden"); $('#hide').click(function() { $('article').toggleClass('hidden') }); }); 

See this working demo: Toggle class

Comments

0
$(document).ready(function(){ $('article').addClass("hidden"); $( '#hide' ).click(function() { if ( $( 'article' ).hasClass( "hidden" ) ) { $( 'article' ).removeClass("hidden").addClass("visible"); } else { $('article').removeClass("visible").addClass("hidden"); } }); }); 

You can use toggle also

Comments

0

Jquery has a toggle function that hides and shows selected elements. It also has hide and show functions that mean your css isn't needed.

$(document).ready(function(){ // Hide the div to start with. $('#divToHide').hide(); // When the button is clicked, toggle the div's visibility. $('#hide').click(function() { $('#divToHide').toggle(); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <body> <article> <button type="button" id="hide">Click me to toggle the visibility of the div</button> <div id="divToHide"> Hello World! </div> </article> </body>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.