stacky
stacky

Reputation: 311

Change css through jquery after a click on a div

The below code isn't working, Is there anything wrong in this code, when I click on div.first it has to show div.second and a click again should make it display none.

Html

<div class="first">some text</div>
<div class ="second">bunch of text</div>

Css

.second{display=none;}

Jquery

 $('.first').click(function() {
  $('.second').css('display', 'block');
});

Thanks in advance

Upvotes: 1

Views: 125

Answers (5)

Jack Ch
Jack Ch

Reputation: 71

It's best to use classes to hide and show Elements

HTML

<div class="first">some text</div>
<div class ="second div-hide">bunch of text</div>

CSS

.div-hide{display:none}

JQUERY

$('.first').click(function() {
   if ($('.second').hasClass('div-hide'))
   {
        $('.second').removeClass('div-hide');
   }
   else
   {
       $('.second').addClass('div-hide');
   }
});

Upvotes: 1

Raj
Raj

Reputation: 2028

You simply need this

$('.first').click(function() {
  $('.second').toggle();
});

Here is an example

$('.first').click(function() {
  $('.second').toggle();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="first">some text</div>
<div class ="second">bunch of text</div>

Upvotes: 0

XYZ
XYZ

Reputation: 4480

Use $('.second').toggle();

 $('.first').click(function() {
  $('.second').toggle();
});
.second{display=none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="first">some text</div>
<div class ="second">bunch of text</div>

Upvotes: 0

Michael Coker
Michael Coker

Reputation: 53674

Use $.toggle() to toggle display

$('.first').click(function() {
  $('.second').toggle();
});
.second{display=none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="first">some text</div>
<div class ="second">bunch of text</div>

Upvotes: 0

Tyler Gaffaney
Tyler Gaffaney

Reputation: 86

In your JQuery, you forgot the period in front of second

$('.first').click(function() {
     $('.second').css('display', 'block');
});

Upvotes: 0

Related Questions