Trying to show/hide an element when clicked using JavaScript and jQuery -


im trying use if/else statement show/hide element when button clicked. problem have when code runs element gets shown , hides again. code in if block , else bock both executing.

<html>      <head>         <meta charset="utf-8">     </head>      <body>         <section class="variation">             <h2 id="btn">show , hide</h2>             <div class="maincontent">                 <p>nam tincidunt erat et purus porttitor bibendum.</p>             </div>         </section>         <script type="javascript">             var $maincontent = $('.maincontent');             var $variation = $('.variation h2');             $maincontent.hide();             $('#btn').click(function() {                 if ($maincontent.css('display') == 'none') {                     $maincontent.show('fast');                 } else {                     $maincontent.hide('fast');                     console.log($maincontent.css('display'))                 }             });         </script>      </body>  </html> 

i have tested in chrome , firefox.

p.s

i know use jquery toggle() method rather know how without it.

you have wrong type in script tag. should be:

 <script type="text/javascript"> 

not:

<script type="javascript"> 

(also, in html5 there no need put type attribute if javascript, text/javascript default, can ommit entirely)

and bonus - because other type thing, code should work fine, here's bit twisted one-line-toggle-replacement ;)

$('#btn').click(function() {    $maincontent[($maincontent.is(':visible')) ? 'show' : 'hide']('fast'); } 

Comments

Popular posts from this blog

PHP DOM loadHTML() method unusual warning -

python - How to create jsonb index using GIN on SQLAlchemy? -

c# - TransactionScope not rolling back although no complete() is called -