Jquery/javascript else statement not working

Discussion in 'JavaScript' started by battista, Dec 15, 2022.

  1. #1
    Hi there,

    I am trying to learn a javascript framework named "pikajs"; it seems based on jquery.

    But as I am progressing, I am encountering a problem and can't get around it.

    Here is the code, in case somebody may help, please:

    <html xml:lang="fr" lang="fr">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <script src="pika-min.js"></script>
    <style>
    b{display:block;margin-top:50px;}
    </style>
    </head>
    
    <body>
    
    <div id="content">
    
    <b class="showing">show/hide</b>
    <em class="texte" style="display:none;">texte</em>
    
    <b class="showing">show/hide</b>
    <em class="texte" style="display:none;">kkkjjhkhj</em>
    
    <b class="showing">show/hide</b>
    <em class="texte" style="display:none;">texte</em>
    
    <b class="showing">show/hide</b>
    <em class="texte" style="display:none;">dfdgfdfgdfdgfdgfdgfdgfdgfdgfdgf</em>
    
    <b class="showing" id="test1">show/hide</b>
    <em class="texte" style="display:none;">dgfdgfdgf</em>
    
    </div>
    
    
    
    <script type="text/javascript">
    
    $('#content')._on('click', '.showing', function() {
    
    var val = $(this).next('em.texte').attr('style');
    
    if (val='display:none'){
    $(this).next('em.texte').attr('style', 'display:block');
    } else if (val='display:block'){
    $(this).next('em.texte').attr('style', 'display:none');
    }
    
    })
    
    </script>
    HTML:
    (needs pikajsmin for execution:https://raw.githubusercontent.com/Scottie35/PikaJS/master/pika-min.js)

    I am trying to achieve a "show/hide" system: by clicking a <b> element, the <em> pops up.

    But hiding does not and I don't understand why.

    Any help would be greatly appreciated,

    Thank you!

    EDIT: got it working:

    <script type="text/javascript">
    
    $('#content')._on('click', '.showing', function() {
    
    if($(this).next('em.texte').attr('style')==='display:none;'){
    $(this).next('em.texte').attr('style', 'display:block;');
    } else if($(this).next('em.texte').attr('style')==='display:block;'){
    $(this).next('em.texte').attr('style', 'display:none;');
    }
    
    })
    
    </script>
    
    Code (JavaScript):

     
    Last edited: Dec 15, 2022
    battista, Dec 15, 2022 IP
    sarahk likes this.
  2. Vooler

    Vooler Well-Known Member

    Messages:
    1,146
    Likes Received:
    64
    Best Answers:
    4
    Trophy Points:
    150
    #2
    You can further simply it:
    
    $('#content').on('click', '.showing', function() {
         $(this).next('em.texte').toggle();
    });
    
    Code (markup):
    Also ensure, it is in ready function
    $(function() {
    ................
    });
     
    Vooler, Dec 21, 2022 IP